xref: /freebsd/sys/dev/bxe/bxe.c (revision 97549c34ecaf74580941fdc9c5bd1050e4b1f6ce)
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.89"
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     { STATS_OFFSET32(bxe_tx_mq_start_lock_failures),
494                 4, STATS_FLAGS_FUNC, "bxe_tx_mq_start_lock_failures"},
495     { STATS_OFFSET32(tx_request_link_down_failures),
496                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
497     { STATS_OFFSET32(bd_avail_too_less_failures),
498                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
499     { STATS_OFFSET32(tx_mq_not_empty),
500                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"}
501 
502 };
503 
504 static const struct {
505     uint32_t offset;
506     uint32_t size;
507     char string[STAT_NAME_LEN];
508 } bxe_eth_q_stats_arr[] = {
509     { Q_STATS_OFFSET32(total_bytes_received_hi),
510                 8, "rx_bytes" },
511     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
512                 8, "rx_ucast_packets" },
513     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
514                 8, "rx_mcast_packets" },
515     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
516                 8, "rx_bcast_packets" },
517     { Q_STATS_OFFSET32(no_buff_discard_hi),
518                 8, "rx_discards" },
519     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
520                 8, "tx_bytes" },
521     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
522                 8, "tx_ucast_packets" },
523     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
524                 8, "tx_mcast_packets" },
525     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
526                 8, "tx_bcast_packets" },
527     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
528                 8, "tpa_aggregations" },
529     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
530                 8, "tpa_aggregated_frames"},
531     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
532                 8, "tpa_bytes"},
533     { Q_STATS_OFFSET32(rx_calls),
534                 4, "rx_calls"},
535     { Q_STATS_OFFSET32(rx_pkts),
536                 4, "rx_pkts"},
537     { Q_STATS_OFFSET32(rx_tpa_pkts),
538                 4, "rx_tpa_pkts"},
539     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
540                 4, "rx_erroneous_jumbo_sge_pkts"},
541     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
542                 4, "rx_bxe_service_rxsgl"},
543     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
544                 4, "rx_jumbo_sge_pkts"},
545     { Q_STATS_OFFSET32(rx_soft_errors),
546                 4, "rx_soft_errors"},
547     { Q_STATS_OFFSET32(rx_hw_csum_errors),
548                 4, "rx_hw_csum_errors"},
549     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
550                 4, "rx_ofld_frames_csum_ip"},
551     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
552                 4, "rx_ofld_frames_csum_tcp_udp"},
553     { Q_STATS_OFFSET32(rx_budget_reached),
554                 4, "rx_budget_reached"},
555     { Q_STATS_OFFSET32(tx_pkts),
556                 4, "tx_pkts"},
557     { Q_STATS_OFFSET32(tx_soft_errors),
558                 4, "tx_soft_errors"},
559     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
560                 4, "tx_ofld_frames_csum_ip"},
561     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
562                 4, "tx_ofld_frames_csum_tcp"},
563     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
564                 4, "tx_ofld_frames_csum_udp"},
565     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
566                 4, "tx_ofld_frames_lso"},
567     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
568                 4, "tx_ofld_frames_lso_hdr_splits"},
569     { Q_STATS_OFFSET32(tx_encap_failures),
570                 4, "tx_encap_failures"},
571     { Q_STATS_OFFSET32(tx_hw_queue_full),
572                 4, "tx_hw_queue_full"},
573     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
574                 4, "tx_hw_max_queue_depth"},
575     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
576                 4, "tx_dma_mapping_failure"},
577     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
578                 4, "tx_max_drbr_queue_depth"},
579     { Q_STATS_OFFSET32(tx_window_violation_std),
580                 4, "tx_window_violation_std"},
581     { Q_STATS_OFFSET32(tx_window_violation_tso),
582                 4, "tx_window_violation_tso"},
583     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
584                 4, "tx_chain_lost_mbuf"},
585     { Q_STATS_OFFSET32(tx_frames_deferred),
586                 4, "tx_frames_deferred"},
587     { Q_STATS_OFFSET32(tx_queue_xoff),
588                 4, "tx_queue_xoff"},
589     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
590                 4, "mbuf_defrag_attempts"},
591     { Q_STATS_OFFSET32(mbuf_defrag_failures),
592                 4, "mbuf_defrag_failures"},
593     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
594                 4, "mbuf_rx_bd_alloc_failed"},
595     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
596                 4, "mbuf_rx_bd_mapping_failed"},
597     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
598                 4, "mbuf_rx_tpa_alloc_failed"},
599     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
600                 4, "mbuf_rx_tpa_mapping_failed"},
601     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
602                 4, "mbuf_rx_sge_alloc_failed"},
603     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
604                 4, "mbuf_rx_sge_mapping_failed"},
605     { Q_STATS_OFFSET32(mbuf_alloc_tx),
606                 4, "mbuf_alloc_tx"},
607     { Q_STATS_OFFSET32(mbuf_alloc_rx),
608                 4, "mbuf_alloc_rx"},
609     { Q_STATS_OFFSET32(mbuf_alloc_sge),
610                 4, "mbuf_alloc_sge"},
611     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
612                 4, "mbuf_alloc_tpa"},
613     { Q_STATS_OFFSET32(tx_queue_full_return),
614                 4, "tx_queue_full_return"},
615     { Q_STATS_OFFSET32(bxe_tx_mq_start_lock_failures),
616                 4, "bxe_tx_mq_start_lock_failures"},
617     { Q_STATS_OFFSET32(tx_request_link_down_failures),
618                 4, "tx_request_link_down_failures"},
619     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
620                 4, "bd_avail_too_less_failures"},
621     { Q_STATS_OFFSET32(tx_mq_not_empty),
622                 4, "tx_mq_not_empty"}
623 };
624 
625 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
626 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
627 
628 
629 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
630                                  uint8_t          read_cfg,
631                                  uint8_t          cmng_type);
632 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
633 static void    storm_memset_cmng(struct bxe_softc *sc,
634                                  struct cmng_init *cmng,
635                                  uint8_t          port);
636 static void    bxe_set_reset_global(struct bxe_softc *sc);
637 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
638 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
639                                  int              engine);
640 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
641 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
642                                    uint8_t          *global,
643                                    uint8_t          print);
644 static void    bxe_int_disable(struct bxe_softc *sc);
645 static int     bxe_release_leader_lock(struct bxe_softc *sc);
646 static void    bxe_pf_disable(struct bxe_softc *sc);
647 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
648 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
649                                       struct bxe_fastpath *fp,
650                                       uint16_t            rx_bd_prod,
651                                       uint16_t            rx_cq_prod,
652                                       uint16_t            rx_sge_prod);
653 static void    bxe_link_report_locked(struct bxe_softc *sc);
654 static void    bxe_link_report(struct bxe_softc *sc);
655 static void    bxe_link_status_update(struct bxe_softc *sc);
656 static void    bxe_periodic_callout_func(void *xsc);
657 static void    bxe_periodic_start(struct bxe_softc *sc);
658 static void    bxe_periodic_stop(struct bxe_softc *sc);
659 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
660                                     uint16_t prev_index,
661                                     uint16_t index);
662 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
663                                      int                 queue);
664 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
665                                      uint16_t            index);
666 static uint8_t bxe_txeof(struct bxe_softc *sc,
667                          struct bxe_fastpath *fp);
668 static void    bxe_task_fp(struct bxe_fastpath *fp);
669 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
670                                      struct mbuf      *m,
671                                      uint8_t          contents);
672 static int     bxe_alloc_mem(struct bxe_softc *sc);
673 static void    bxe_free_mem(struct bxe_softc *sc);
674 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
675 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
676 static int     bxe_interrupt_attach(struct bxe_softc *sc);
677 static void    bxe_interrupt_detach(struct bxe_softc *sc);
678 static void    bxe_set_rx_mode(struct bxe_softc *sc);
679 static int     bxe_init_locked(struct bxe_softc *sc);
680 static int     bxe_stop_locked(struct bxe_softc *sc);
681 static __noinline int bxe_nic_load(struct bxe_softc *sc,
682                                    int              load_mode);
683 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
684                                      uint32_t         unload_mode,
685                                      uint8_t          keep_link);
686 
687 static void bxe_handle_sp_tq(void *context, int pending);
688 static void bxe_handle_fp_tq(void *context, int pending);
689 
690 static int bxe_add_cdev(struct bxe_softc *sc);
691 static void bxe_del_cdev(struct bxe_softc *sc);
692 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
693 static void bxe_free_buf_rings(struct bxe_softc *sc);
694 
695 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
696 uint32_t
697 calc_crc32(uint8_t  *crc32_packet,
698            uint32_t crc32_length,
699            uint32_t crc32_seed,
700            uint8_t  complement)
701 {
702    uint32_t byte         = 0;
703    uint32_t bit          = 0;
704    uint8_t  msb          = 0;
705    uint32_t temp         = 0;
706    uint32_t shft         = 0;
707    uint8_t  current_byte = 0;
708    uint32_t crc32_result = crc32_seed;
709    const uint32_t CRC32_POLY = 0x1edc6f41;
710 
711    if ((crc32_packet == NULL) ||
712        (crc32_length == 0) ||
713        ((crc32_length % 8) != 0))
714     {
715         return (crc32_result);
716     }
717 
718     for (byte = 0; byte < crc32_length; byte = byte + 1)
719     {
720         current_byte = crc32_packet[byte];
721         for (bit = 0; bit < 8; bit = bit + 1)
722         {
723             /* msb = crc32_result[31]; */
724             msb = (uint8_t)(crc32_result >> 31);
725 
726             crc32_result = crc32_result << 1;
727 
728             /* it (msb != current_byte[bit]) */
729             if (msb != (0x1 & (current_byte >> bit)))
730             {
731                 crc32_result = crc32_result ^ CRC32_POLY;
732                 /* crc32_result[0] = 1 */
733                 crc32_result |= 1;
734             }
735         }
736     }
737 
738     /* Last step is to:
739      * 1. "mirror" every bit
740      * 2. swap the 4 bytes
741      * 3. complement each bit
742      */
743 
744     /* Mirror */
745     temp = crc32_result;
746     shft = sizeof(crc32_result) * 8 - 1;
747 
748     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
749     {
750         temp <<= 1;
751         temp |= crc32_result & 1;
752         shft-- ;
753     }
754 
755     /* temp[31-bit] = crc32_result[bit] */
756     temp <<= shft;
757 
758     /* Swap */
759     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
760     {
761         uint32_t t0, t1, t2, t3;
762         t0 = (0x000000ff & (temp >> 24));
763         t1 = (0x0000ff00 & (temp >> 8));
764         t2 = (0x00ff0000 & (temp << 8));
765         t3 = (0xff000000 & (temp << 24));
766         crc32_result = t0 | t1 | t2 | t3;
767     }
768 
769     /* Complement */
770     if (complement)
771     {
772         crc32_result = ~crc32_result;
773     }
774 
775     return (crc32_result);
776 }
777 
778 int
779 bxe_test_bit(int                    nr,
780              volatile unsigned long *addr)
781 {
782     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
783 }
784 
785 void
786 bxe_set_bit(unsigned int           nr,
787             volatile unsigned long *addr)
788 {
789     atomic_set_acq_long(addr, (1 << nr));
790 }
791 
792 void
793 bxe_clear_bit(int                    nr,
794               volatile unsigned long *addr)
795 {
796     atomic_clear_acq_long(addr, (1 << nr));
797 }
798 
799 int
800 bxe_test_and_set_bit(int                    nr,
801                        volatile unsigned long *addr)
802 {
803     unsigned long x;
804     nr = (1 << nr);
805     do {
806         x = *addr;
807     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
808     // if (x & nr) bit_was_set; else bit_was_not_set;
809     return (x & nr);
810 }
811 
812 int
813 bxe_test_and_clear_bit(int                    nr,
814                        volatile unsigned long *addr)
815 {
816     unsigned long x;
817     nr = (1 << nr);
818     do {
819         x = *addr;
820     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
821     // if (x & nr) bit_was_set; else bit_was_not_set;
822     return (x & nr);
823 }
824 
825 int
826 bxe_cmpxchg(volatile int *addr,
827             int          old,
828             int          new)
829 {
830     int x;
831     do {
832         x = *addr;
833     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
834     return (x);
835 }
836 
837 /*
838  * Get DMA memory from the OS.
839  *
840  * Validates that the OS has provided DMA buffers in response to a
841  * bus_dmamap_load call and saves the physical address of those buffers.
842  * When the callback is used the OS will return 0 for the mapping function
843  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
844  * failures back to the caller.
845  *
846  * Returns:
847  *   Nothing.
848  */
849 static void
850 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
851 {
852     struct bxe_dma *dma = arg;
853 
854     if (error) {
855         dma->paddr = 0;
856         dma->nseg  = 0;
857         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
858     } else {
859         dma->paddr = segs->ds_addr;
860         dma->nseg  = nseg;
861     }
862 }
863 
864 /*
865  * Allocate a block of memory and map it for DMA. No partial completions
866  * allowed and release any resources acquired if we can't acquire all
867  * resources.
868  *
869  * Returns:
870  *   0 = Success, !0 = Failure
871  */
872 int
873 bxe_dma_alloc(struct bxe_softc *sc,
874               bus_size_t       size,
875               struct bxe_dma   *dma,
876               const char       *msg)
877 {
878     int rc;
879 
880     if (dma->size > 0) {
881         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
882               (unsigned long)dma->size);
883         return (1);
884     }
885 
886     memset(dma, 0, sizeof(*dma)); /* sanity */
887     dma->sc   = sc;
888     dma->size = size;
889     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
890 
891     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
892                             BCM_PAGE_SIZE,      /* alignment */
893                             0,                  /* boundary limit */
894                             BUS_SPACE_MAXADDR,  /* restricted low */
895                             BUS_SPACE_MAXADDR,  /* restricted hi */
896                             NULL,               /* addr filter() */
897                             NULL,               /* addr filter() arg */
898                             size,               /* max map size */
899                             1,                  /* num discontinuous */
900                             size,               /* max seg size */
901                             BUS_DMA_ALLOCNOW,   /* flags */
902                             NULL,               /* lock() */
903                             NULL,               /* lock() arg */
904                             &dma->tag);         /* returned dma tag */
905     if (rc != 0) {
906         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
907         memset(dma, 0, sizeof(*dma));
908         return (1);
909     }
910 
911     rc = bus_dmamem_alloc(dma->tag,
912                           (void **)&dma->vaddr,
913                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
914                           &dma->map);
915     if (rc != 0) {
916         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
917         bus_dma_tag_destroy(dma->tag);
918         memset(dma, 0, sizeof(*dma));
919         return (1);
920     }
921 
922     rc = bus_dmamap_load(dma->tag,
923                          dma->map,
924                          dma->vaddr,
925                          size,
926                          bxe_dma_map_addr, /* BLOGD in here */
927                          dma,
928                          BUS_DMA_NOWAIT);
929     if (rc != 0) {
930         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
931         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
932         bus_dma_tag_destroy(dma->tag);
933         memset(dma, 0, sizeof(*dma));
934         return (1);
935     }
936 
937     return (0);
938 }
939 
940 void
941 bxe_dma_free(struct bxe_softc *sc,
942              struct bxe_dma   *dma)
943 {
944     if (dma->size > 0) {
945         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
946 
947         bus_dmamap_sync(dma->tag, dma->map,
948                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
949         bus_dmamap_unload(dma->tag, dma->map);
950         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
951         bus_dma_tag_destroy(dma->tag);
952     }
953 
954     memset(dma, 0, sizeof(*dma));
955 }
956 
957 /*
958  * These indirect read and write routines are only during init.
959  * The locking is handled by the MCP.
960  */
961 
962 void
963 bxe_reg_wr_ind(struct bxe_softc *sc,
964                uint32_t         addr,
965                uint32_t         val)
966 {
967     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
968     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
969     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
970 }
971 
972 uint32_t
973 bxe_reg_rd_ind(struct bxe_softc *sc,
974                uint32_t         addr)
975 {
976     uint32_t val;
977 
978     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
979     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
980     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
981 
982     return (val);
983 }
984 
985 static int
986 bxe_acquire_hw_lock(struct bxe_softc *sc,
987                     uint32_t         resource)
988 {
989     uint32_t lock_status;
990     uint32_t resource_bit = (1 << resource);
991     int func = SC_FUNC(sc);
992     uint32_t hw_lock_control_reg;
993     int cnt;
994 
995     /* validate the resource is within range */
996     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
997         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
998             " resource_bit 0x%x\n", resource, resource_bit);
999         return (-1);
1000     }
1001 
1002     if (func <= 5) {
1003         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1004     } else {
1005         hw_lock_control_reg =
1006                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1007     }
1008 
1009     /* validate the resource is not already taken */
1010     lock_status = REG_RD(sc, hw_lock_control_reg);
1011     if (lock_status & resource_bit) {
1012         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1013               resource, lock_status, resource_bit);
1014         return (-1);
1015     }
1016 
1017     /* try every 5ms for 5 seconds */
1018     for (cnt = 0; cnt < 1000; cnt++) {
1019         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1020         lock_status = REG_RD(sc, hw_lock_control_reg);
1021         if (lock_status & resource_bit) {
1022             return (0);
1023         }
1024         DELAY(5000);
1025     }
1026 
1027     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1028         resource, resource_bit);
1029     return (-1);
1030 }
1031 
1032 static int
1033 bxe_release_hw_lock(struct bxe_softc *sc,
1034                     uint32_t         resource)
1035 {
1036     uint32_t lock_status;
1037     uint32_t resource_bit = (1 << resource);
1038     int func = SC_FUNC(sc);
1039     uint32_t hw_lock_control_reg;
1040 
1041     /* validate the resource is within range */
1042     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1043         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1044             " resource_bit 0x%x\n", resource, resource_bit);
1045         return (-1);
1046     }
1047 
1048     if (func <= 5) {
1049         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1050     } else {
1051         hw_lock_control_reg =
1052                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1053     }
1054 
1055     /* validate the resource is currently taken */
1056     lock_status = REG_RD(sc, hw_lock_control_reg);
1057     if (!(lock_status & resource_bit)) {
1058         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1059               resource, lock_status, resource_bit);
1060         return (-1);
1061     }
1062 
1063     REG_WR(sc, hw_lock_control_reg, resource_bit);
1064     return (0);
1065 }
1066 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1067 {
1068 	BXE_PHY_LOCK(sc);
1069 	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1070 }
1071 
1072 static void bxe_release_phy_lock(struct bxe_softc *sc)
1073 {
1074 	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1075 	BXE_PHY_UNLOCK(sc);
1076 }
1077 /*
1078  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1079  * had we done things the other way around, if two pfs from the same port
1080  * would attempt to access nvram at the same time, we could run into a
1081  * scenario such as:
1082  * pf A takes the port lock.
1083  * pf B succeeds in taking the same lock since they are from the same port.
1084  * pf A takes the per pf misc lock. Performs eeprom access.
1085  * pf A finishes. Unlocks the per pf misc lock.
1086  * Pf B takes the lock and proceeds to perform it's own access.
1087  * pf A unlocks the per port lock, while pf B is still working (!).
1088  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1089  * access corrupted by pf B).*
1090  */
1091 static int
1092 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1093 {
1094     int port = SC_PORT(sc);
1095     int count, i;
1096     uint32_t val = 0;
1097 
1098     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1099     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1100 
1101     /* adjust timeout for emulation/FPGA */
1102     count = NVRAM_TIMEOUT_COUNT;
1103     if (CHIP_REV_IS_SLOW(sc)) {
1104         count *= 100;
1105     }
1106 
1107     /* request access to nvram interface */
1108     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1109            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1110 
1111     for (i = 0; i < count*10; i++) {
1112         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1113         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1114             break;
1115         }
1116 
1117         DELAY(5);
1118     }
1119 
1120     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1121         BLOGE(sc, "Cannot get access to nvram interface "
1122             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1123             port, val);
1124         return (-1);
1125     }
1126 
1127     return (0);
1128 }
1129 
1130 static int
1131 bxe_release_nvram_lock(struct bxe_softc *sc)
1132 {
1133     int port = SC_PORT(sc);
1134     int count, i;
1135     uint32_t val = 0;
1136 
1137     /* adjust timeout for emulation/FPGA */
1138     count = NVRAM_TIMEOUT_COUNT;
1139     if (CHIP_REV_IS_SLOW(sc)) {
1140         count *= 100;
1141     }
1142 
1143     /* relinquish nvram interface */
1144     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1145            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1146 
1147     for (i = 0; i < count*10; i++) {
1148         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1149         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1150             break;
1151         }
1152 
1153         DELAY(5);
1154     }
1155 
1156     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1157         BLOGE(sc, "Cannot free access to nvram interface "
1158             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1159             port, val);
1160         return (-1);
1161     }
1162 
1163     /* release HW lock: protect against other PFs in PF Direct Assignment */
1164     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1165 
1166     return (0);
1167 }
1168 
1169 static void
1170 bxe_enable_nvram_access(struct bxe_softc *sc)
1171 {
1172     uint32_t val;
1173 
1174     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1175 
1176     /* enable both bits, even on read */
1177     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1178            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1179 }
1180 
1181 static void
1182 bxe_disable_nvram_access(struct bxe_softc *sc)
1183 {
1184     uint32_t val;
1185 
1186     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1187 
1188     /* disable both bits, even after read */
1189     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1190            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1191                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1192 }
1193 
1194 static int
1195 bxe_nvram_read_dword(struct bxe_softc *sc,
1196                      uint32_t         offset,
1197                      uint32_t         *ret_val,
1198                      uint32_t         cmd_flags)
1199 {
1200     int count, i, rc;
1201     uint32_t val;
1202 
1203     /* build the command word */
1204     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1205 
1206     /* need to clear DONE bit separately */
1207     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1208 
1209     /* address of the NVRAM to read from */
1210     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1211            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1212 
1213     /* issue a read command */
1214     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1215 
1216     /* adjust timeout for emulation/FPGA */
1217     count = NVRAM_TIMEOUT_COUNT;
1218     if (CHIP_REV_IS_SLOW(sc)) {
1219         count *= 100;
1220     }
1221 
1222     /* wait for completion */
1223     *ret_val = 0;
1224     rc = -1;
1225     for (i = 0; i < count; i++) {
1226         DELAY(5);
1227         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1228 
1229         if (val & MCPR_NVM_COMMAND_DONE) {
1230             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1231             /* we read nvram data in cpu order
1232              * but ethtool sees it as an array of bytes
1233              * converting to big-endian will do the work
1234              */
1235             *ret_val = htobe32(val);
1236             rc = 0;
1237             break;
1238         }
1239     }
1240 
1241     if (rc == -1) {
1242         BLOGE(sc, "nvram read timeout expired "
1243             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1244             offset, cmd_flags, val);
1245     }
1246 
1247     return (rc);
1248 }
1249 
1250 static int
1251 bxe_nvram_read(struct bxe_softc *sc,
1252                uint32_t         offset,
1253                uint8_t          *ret_buf,
1254                int              buf_size)
1255 {
1256     uint32_t cmd_flags;
1257     uint32_t val;
1258     int rc;
1259 
1260     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1261         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1262               offset, buf_size);
1263         return (-1);
1264     }
1265 
1266     if ((offset + buf_size) > sc->devinfo.flash_size) {
1267         BLOGE(sc, "Invalid parameter, "
1268                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1269               offset, buf_size, sc->devinfo.flash_size);
1270         return (-1);
1271     }
1272 
1273     /* request access to nvram interface */
1274     rc = bxe_acquire_nvram_lock(sc);
1275     if (rc) {
1276         return (rc);
1277     }
1278 
1279     /* enable access to nvram interface */
1280     bxe_enable_nvram_access(sc);
1281 
1282     /* read the first word(s) */
1283     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1284     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1285         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1286         memcpy(ret_buf, &val, 4);
1287 
1288         /* advance to the next dword */
1289         offset += sizeof(uint32_t);
1290         ret_buf += sizeof(uint32_t);
1291         buf_size -= sizeof(uint32_t);
1292         cmd_flags = 0;
1293     }
1294 
1295     if (rc == 0) {
1296         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1297         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1298         memcpy(ret_buf, &val, 4);
1299     }
1300 
1301     /* disable access to nvram interface */
1302     bxe_disable_nvram_access(sc);
1303     bxe_release_nvram_lock(sc);
1304 
1305     return (rc);
1306 }
1307 
1308 static int
1309 bxe_nvram_write_dword(struct bxe_softc *sc,
1310                       uint32_t         offset,
1311                       uint32_t         val,
1312                       uint32_t         cmd_flags)
1313 {
1314     int count, i, rc;
1315 
1316     /* build the command word */
1317     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1318 
1319     /* need to clear DONE bit separately */
1320     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1321 
1322     /* write the data */
1323     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1324 
1325     /* address of the NVRAM to write to */
1326     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1327            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1328 
1329     /* issue the write command */
1330     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1331 
1332     /* adjust timeout for emulation/FPGA */
1333     count = NVRAM_TIMEOUT_COUNT;
1334     if (CHIP_REV_IS_SLOW(sc)) {
1335         count *= 100;
1336     }
1337 
1338     /* wait for completion */
1339     rc = -1;
1340     for (i = 0; i < count; i++) {
1341         DELAY(5);
1342         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1343         if (val & MCPR_NVM_COMMAND_DONE) {
1344             rc = 0;
1345             break;
1346         }
1347     }
1348 
1349     if (rc == -1) {
1350         BLOGE(sc, "nvram write timeout expired "
1351             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1352             offset, cmd_flags, val);
1353     }
1354 
1355     return (rc);
1356 }
1357 
1358 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1359 
1360 static int
1361 bxe_nvram_write1(struct bxe_softc *sc,
1362                  uint32_t         offset,
1363                  uint8_t          *data_buf,
1364                  int              buf_size)
1365 {
1366     uint32_t cmd_flags;
1367     uint32_t align_offset;
1368     uint32_t val;
1369     int rc;
1370 
1371     if ((offset + buf_size) > sc->devinfo.flash_size) {
1372         BLOGE(sc, "Invalid parameter, "
1373                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1374               offset, buf_size, sc->devinfo.flash_size);
1375         return (-1);
1376     }
1377 
1378     /* request access to nvram interface */
1379     rc = bxe_acquire_nvram_lock(sc);
1380     if (rc) {
1381         return (rc);
1382     }
1383 
1384     /* enable access to nvram interface */
1385     bxe_enable_nvram_access(sc);
1386 
1387     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1388     align_offset = (offset & ~0x03);
1389     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1390 
1391     if (rc == 0) {
1392         val &= ~(0xff << BYTE_OFFSET(offset));
1393         val |= (*data_buf << BYTE_OFFSET(offset));
1394 
1395         /* nvram data is returned as an array of bytes
1396          * convert it back to cpu order
1397          */
1398         val = be32toh(val);
1399 
1400         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1401     }
1402 
1403     /* disable access to nvram interface */
1404     bxe_disable_nvram_access(sc);
1405     bxe_release_nvram_lock(sc);
1406 
1407     return (rc);
1408 }
1409 
1410 static int
1411 bxe_nvram_write(struct bxe_softc *sc,
1412                 uint32_t         offset,
1413                 uint8_t          *data_buf,
1414                 int              buf_size)
1415 {
1416     uint32_t cmd_flags;
1417     uint32_t val;
1418     uint32_t written_so_far;
1419     int rc;
1420 
1421     if (buf_size == 1) {
1422         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1423     }
1424 
1425     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1426         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1427               offset, buf_size);
1428         return (-1);
1429     }
1430 
1431     if (buf_size == 0) {
1432         return (0); /* nothing to do */
1433     }
1434 
1435     if ((offset + buf_size) > sc->devinfo.flash_size) {
1436         BLOGE(sc, "Invalid parameter, "
1437                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1438               offset, buf_size, sc->devinfo.flash_size);
1439         return (-1);
1440     }
1441 
1442     /* request access to nvram interface */
1443     rc = bxe_acquire_nvram_lock(sc);
1444     if (rc) {
1445         return (rc);
1446     }
1447 
1448     /* enable access to nvram interface */
1449     bxe_enable_nvram_access(sc);
1450 
1451     written_so_far = 0;
1452     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1453     while ((written_so_far < buf_size) && (rc == 0)) {
1454         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1455             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1456         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1457             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1458         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1459             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1460         }
1461 
1462         memcpy(&val, data_buf, 4);
1463 
1464         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1465 
1466         /* advance to the next dword */
1467         offset += sizeof(uint32_t);
1468         data_buf += sizeof(uint32_t);
1469         written_so_far += sizeof(uint32_t);
1470         cmd_flags = 0;
1471     }
1472 
1473     /* disable access to nvram interface */
1474     bxe_disable_nvram_access(sc);
1475     bxe_release_nvram_lock(sc);
1476 
1477     return (rc);
1478 }
1479 
1480 /* copy command into DMAE command memory and set DMAE command Go */
1481 void
1482 bxe_post_dmae(struct bxe_softc    *sc,
1483               struct dmae_cmd *dmae,
1484               int                 idx)
1485 {
1486     uint32_t cmd_offset;
1487     int i;
1488 
1489     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1490     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1491         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1492     }
1493 
1494     REG_WR(sc, dmae_reg_go_c[idx], 1);
1495 }
1496 
1497 uint32_t
1498 bxe_dmae_opcode_add_comp(uint32_t opcode,
1499                          uint8_t  comp_type)
1500 {
1501     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1502                       DMAE_CMD_C_TYPE_ENABLE));
1503 }
1504 
1505 uint32_t
1506 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1507 {
1508     return (opcode & ~DMAE_CMD_SRC_RESET);
1509 }
1510 
1511 uint32_t
1512 bxe_dmae_opcode(struct bxe_softc *sc,
1513                 uint8_t          src_type,
1514                 uint8_t          dst_type,
1515                 uint8_t          with_comp,
1516                 uint8_t          comp_type)
1517 {
1518     uint32_t opcode = 0;
1519 
1520     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1521                (dst_type << DMAE_CMD_DST_SHIFT));
1522 
1523     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1524 
1525     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1526 
1527     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1528                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1529 
1530     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1531 
1532 #ifdef __BIG_ENDIAN
1533     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1534 #else
1535     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1536 #endif
1537 
1538     if (with_comp) {
1539         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1540     }
1541 
1542     return (opcode);
1543 }
1544 
1545 static void
1546 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1547                         struct dmae_cmd *dmae,
1548                         uint8_t             src_type,
1549                         uint8_t             dst_type)
1550 {
1551     memset(dmae, 0, sizeof(struct dmae_cmd));
1552 
1553     /* set the opcode */
1554     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1555                                    TRUE, DMAE_COMP_PCI);
1556 
1557     /* fill in the completion parameters */
1558     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1559     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1560     dmae->comp_val     = DMAE_COMP_VAL;
1561 }
1562 
1563 /* issue a DMAE command over the init channel and wait for completion */
1564 static int
1565 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1566                          struct dmae_cmd *dmae)
1567 {
1568     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1569     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1570 
1571     BXE_DMAE_LOCK(sc);
1572 
1573     /* reset completion */
1574     *wb_comp = 0;
1575 
1576     /* post the command on the channel used for initializations */
1577     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1578 
1579     /* wait for completion */
1580     DELAY(5);
1581 
1582     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1583         if (!timeout ||
1584             (sc->recovery_state != BXE_RECOVERY_DONE &&
1585              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1586             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1587                 *wb_comp, sc->recovery_state);
1588             BXE_DMAE_UNLOCK(sc);
1589             return (DMAE_TIMEOUT);
1590         }
1591 
1592         timeout--;
1593         DELAY(50);
1594     }
1595 
1596     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1597         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1598                 *wb_comp, sc->recovery_state);
1599         BXE_DMAE_UNLOCK(sc);
1600         return (DMAE_PCI_ERROR);
1601     }
1602 
1603     BXE_DMAE_UNLOCK(sc);
1604     return (0);
1605 }
1606 
1607 void
1608 bxe_read_dmae(struct bxe_softc *sc,
1609               uint32_t         src_addr,
1610               uint32_t         len32)
1611 {
1612     struct dmae_cmd dmae;
1613     uint32_t *data;
1614     int i, rc;
1615 
1616     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1617 
1618     if (!sc->dmae_ready) {
1619         data = BXE_SP(sc, wb_data[0]);
1620 
1621         for (i = 0; i < len32; i++) {
1622             data[i] = (CHIP_IS_E1(sc)) ?
1623                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1624                           REG_RD(sc, (src_addr + (i * 4)));
1625         }
1626 
1627         return;
1628     }
1629 
1630     /* set opcode and fixed command fields */
1631     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1632 
1633     /* fill in addresses and len */
1634     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1635     dmae.src_addr_hi = 0;
1636     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1637     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1638     dmae.len         = len32;
1639 
1640     /* issue the command and wait for completion */
1641     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1642         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1643     }
1644 }
1645 
1646 void
1647 bxe_write_dmae(struct bxe_softc *sc,
1648                bus_addr_t       dma_addr,
1649                uint32_t         dst_addr,
1650                uint32_t         len32)
1651 {
1652     struct dmae_cmd dmae;
1653     int rc;
1654 
1655     if (!sc->dmae_ready) {
1656         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1657 
1658         if (CHIP_IS_E1(sc)) {
1659             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1660         } else {
1661             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1662         }
1663 
1664         return;
1665     }
1666 
1667     /* set opcode and fixed command fields */
1668     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1669 
1670     /* fill in addresses and len */
1671     dmae.src_addr_lo = U64_LO(dma_addr);
1672     dmae.src_addr_hi = U64_HI(dma_addr);
1673     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1674     dmae.dst_addr_hi = 0;
1675     dmae.len         = len32;
1676 
1677     /* issue the command and wait for completion */
1678     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1679         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1680     }
1681 }
1682 
1683 void
1684 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1685                         bus_addr_t       phys_addr,
1686                         uint32_t         addr,
1687                         uint32_t         len)
1688 {
1689     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1690     int offset = 0;
1691 
1692     while (len > dmae_wr_max) {
1693         bxe_write_dmae(sc,
1694                        (phys_addr + offset), /* src DMA address */
1695                        (addr + offset),      /* dst GRC address */
1696                        dmae_wr_max);
1697         offset += (dmae_wr_max * 4);
1698         len -= dmae_wr_max;
1699     }
1700 
1701     bxe_write_dmae(sc,
1702                    (phys_addr + offset), /* src DMA address */
1703                    (addr + offset),      /* dst GRC address */
1704                    len);
1705 }
1706 
1707 void
1708 bxe_set_ctx_validation(struct bxe_softc   *sc,
1709                        struct eth_context *cxt,
1710                        uint32_t           cid)
1711 {
1712     /* ustorm cxt validation */
1713     cxt->ustorm_ag_context.cdu_usage =
1714         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1715             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1716     /* xcontext validation */
1717     cxt->xstorm_ag_context.cdu_reserved =
1718         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1719             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1720 }
1721 
1722 static void
1723 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1724                             uint8_t          port,
1725                             uint8_t          fw_sb_id,
1726                             uint8_t          sb_index,
1727                             uint8_t          ticks)
1728 {
1729     uint32_t addr =
1730         (BAR_CSTRORM_INTMEM +
1731          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1732 
1733     REG_WR8(sc, addr, ticks);
1734 
1735     BLOGD(sc, DBG_LOAD,
1736           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1737           port, fw_sb_id, sb_index, ticks);
1738 }
1739 
1740 static void
1741 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1742                             uint8_t          port,
1743                             uint16_t         fw_sb_id,
1744                             uint8_t          sb_index,
1745                             uint8_t          disable)
1746 {
1747     uint32_t enable_flag =
1748         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1749     uint32_t addr =
1750         (BAR_CSTRORM_INTMEM +
1751          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1752     uint8_t flags;
1753 
1754     /* clear and set */
1755     flags = REG_RD8(sc, addr);
1756     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1757     flags |= enable_flag;
1758     REG_WR8(sc, addr, flags);
1759 
1760     BLOGD(sc, DBG_LOAD,
1761           "port %d fw_sb_id %d sb_index %d disable %d\n",
1762           port, fw_sb_id, sb_index, disable);
1763 }
1764 
1765 void
1766 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1767                              uint8_t          fw_sb_id,
1768                              uint8_t          sb_index,
1769                              uint8_t          disable,
1770                              uint16_t         usec)
1771 {
1772     int port = SC_PORT(sc);
1773     uint8_t ticks = (usec / 4); /* XXX ??? */
1774 
1775     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1776 
1777     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1778     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1779 }
1780 
1781 void
1782 elink_cb_udelay(struct bxe_softc *sc,
1783                 uint32_t         usecs)
1784 {
1785     DELAY(usecs);
1786 }
1787 
1788 uint32_t
1789 elink_cb_reg_read(struct bxe_softc *sc,
1790                   uint32_t         reg_addr)
1791 {
1792     return (REG_RD(sc, reg_addr));
1793 }
1794 
1795 void
1796 elink_cb_reg_write(struct bxe_softc *sc,
1797                    uint32_t         reg_addr,
1798                    uint32_t         val)
1799 {
1800     REG_WR(sc, reg_addr, val);
1801 }
1802 
1803 void
1804 elink_cb_reg_wb_write(struct bxe_softc *sc,
1805                       uint32_t         offset,
1806                       uint32_t         *wb_write,
1807                       uint16_t         len)
1808 {
1809     REG_WR_DMAE(sc, offset, wb_write, len);
1810 }
1811 
1812 void
1813 elink_cb_reg_wb_read(struct bxe_softc *sc,
1814                      uint32_t         offset,
1815                      uint32_t         *wb_write,
1816                      uint16_t         len)
1817 {
1818     REG_RD_DMAE(sc, offset, wb_write, len);
1819 }
1820 
1821 uint8_t
1822 elink_cb_path_id(struct bxe_softc *sc)
1823 {
1824     return (SC_PATH(sc));
1825 }
1826 
1827 void
1828 elink_cb_event_log(struct bxe_softc     *sc,
1829                    const elink_log_id_t elink_log_id,
1830                    ...)
1831 {
1832     /* XXX */
1833     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1834 }
1835 
1836 static int
1837 bxe_set_spio(struct bxe_softc *sc,
1838              int              spio,
1839              uint32_t         mode)
1840 {
1841     uint32_t spio_reg;
1842 
1843     /* Only 2 SPIOs are configurable */
1844     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1845         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1846         return (-1);
1847     }
1848 
1849     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1850 
1851     /* read SPIO and mask except the float bits */
1852     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1853 
1854     switch (mode) {
1855     case MISC_SPIO_OUTPUT_LOW:
1856         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1857         /* clear FLOAT and set CLR */
1858         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1859         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1860         break;
1861 
1862     case MISC_SPIO_OUTPUT_HIGH:
1863         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1864         /* clear FLOAT and set SET */
1865         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1866         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1867         break;
1868 
1869     case MISC_SPIO_INPUT_HI_Z:
1870         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1871         /* set FLOAT */
1872         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1873         break;
1874 
1875     default:
1876         break;
1877     }
1878 
1879     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1880     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1881 
1882     return (0);
1883 }
1884 
1885 static int
1886 bxe_gpio_read(struct bxe_softc *sc,
1887               int              gpio_num,
1888               uint8_t          port)
1889 {
1890     /* The GPIO should be swapped if swap register is set and active */
1891     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1892                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1893     int gpio_shift = (gpio_num +
1894                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1895     uint32_t gpio_mask = (1 << gpio_shift);
1896     uint32_t gpio_reg;
1897 
1898     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1899         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1900             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1901             gpio_mask);
1902         return (-1);
1903     }
1904 
1905     /* read GPIO value */
1906     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1907 
1908     /* get the requested pin value */
1909     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1910 }
1911 
1912 static int
1913 bxe_gpio_write(struct bxe_softc *sc,
1914                int              gpio_num,
1915                uint32_t         mode,
1916                uint8_t          port)
1917 {
1918     /* The GPIO should be swapped if swap register is set and active */
1919     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1920                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1921     int gpio_shift = (gpio_num +
1922                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1923     uint32_t gpio_mask = (1 << gpio_shift);
1924     uint32_t gpio_reg;
1925 
1926     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1927         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1928             " gpio_shift %d gpio_mask 0x%x\n",
1929             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1930         return (-1);
1931     }
1932 
1933     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1934 
1935     /* read GPIO and mask except the float bits */
1936     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1937 
1938     switch (mode) {
1939     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1940         BLOGD(sc, DBG_PHY,
1941               "Set GPIO %d (shift %d) -> output low\n",
1942               gpio_num, gpio_shift);
1943         /* clear FLOAT and set CLR */
1944         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1945         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1946         break;
1947 
1948     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1949         BLOGD(sc, DBG_PHY,
1950               "Set GPIO %d (shift %d) -> output high\n",
1951               gpio_num, gpio_shift);
1952         /* clear FLOAT and set SET */
1953         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1954         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1955         break;
1956 
1957     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1958         BLOGD(sc, DBG_PHY,
1959               "Set GPIO %d (shift %d) -> input\n",
1960               gpio_num, gpio_shift);
1961         /* set FLOAT */
1962         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1963         break;
1964 
1965     default:
1966         break;
1967     }
1968 
1969     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1970     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1971 
1972     return (0);
1973 }
1974 
1975 static int
1976 bxe_gpio_mult_write(struct bxe_softc *sc,
1977                     uint8_t          pins,
1978                     uint32_t         mode)
1979 {
1980     uint32_t gpio_reg;
1981 
1982     /* any port swapping should be handled by caller */
1983 
1984     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1985 
1986     /* read GPIO and mask except the float bits */
1987     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1988     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1989     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1990     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1991 
1992     switch (mode) {
1993     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1994         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1995         /* set CLR */
1996         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1997         break;
1998 
1999     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2000         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2001         /* set SET */
2002         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2003         break;
2004 
2005     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2006         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2007         /* set FLOAT */
2008         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2009         break;
2010 
2011     default:
2012         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2013             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2014         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2015         return (-1);
2016     }
2017 
2018     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2019     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2020 
2021     return (0);
2022 }
2023 
2024 static int
2025 bxe_gpio_int_write(struct bxe_softc *sc,
2026                    int              gpio_num,
2027                    uint32_t         mode,
2028                    uint8_t          port)
2029 {
2030     /* The GPIO should be swapped if swap register is set and active */
2031     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2032                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2033     int gpio_shift = (gpio_num +
2034                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2035     uint32_t gpio_mask = (1 << gpio_shift);
2036     uint32_t gpio_reg;
2037 
2038     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2039         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2040             " gpio_shift %d gpio_mask 0x%x\n",
2041             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2042         return (-1);
2043     }
2044 
2045     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2046 
2047     /* read GPIO int */
2048     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2049 
2050     switch (mode) {
2051     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2052         BLOGD(sc, DBG_PHY,
2053               "Clear GPIO INT %d (shift %d) -> output low\n",
2054               gpio_num, gpio_shift);
2055         /* clear SET and set CLR */
2056         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2057         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2058         break;
2059 
2060     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2061         BLOGD(sc, DBG_PHY,
2062               "Set GPIO INT %d (shift %d) -> output high\n",
2063               gpio_num, gpio_shift);
2064         /* clear CLR and set SET */
2065         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2066         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2067         break;
2068 
2069     default:
2070         break;
2071     }
2072 
2073     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2074     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2075 
2076     return (0);
2077 }
2078 
2079 uint32_t
2080 elink_cb_gpio_read(struct bxe_softc *sc,
2081                    uint16_t         gpio_num,
2082                    uint8_t          port)
2083 {
2084     return (bxe_gpio_read(sc, gpio_num, port));
2085 }
2086 
2087 uint8_t
2088 elink_cb_gpio_write(struct bxe_softc *sc,
2089                     uint16_t         gpio_num,
2090                     uint8_t          mode, /* 0=low 1=high */
2091                     uint8_t          port)
2092 {
2093     return (bxe_gpio_write(sc, gpio_num, mode, port));
2094 }
2095 
2096 uint8_t
2097 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2098                          uint8_t          pins,
2099                          uint8_t          mode) /* 0=low 1=high */
2100 {
2101     return (bxe_gpio_mult_write(sc, pins, mode));
2102 }
2103 
2104 uint8_t
2105 elink_cb_gpio_int_write(struct bxe_softc *sc,
2106                         uint16_t         gpio_num,
2107                         uint8_t          mode, /* 0=low 1=high */
2108                         uint8_t          port)
2109 {
2110     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2111 }
2112 
2113 void
2114 elink_cb_notify_link_changed(struct bxe_softc *sc)
2115 {
2116     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2117                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2118 }
2119 
2120 /* send the MCP a request, block until there is a reply */
2121 uint32_t
2122 elink_cb_fw_command(struct bxe_softc *sc,
2123                     uint32_t         command,
2124                     uint32_t         param)
2125 {
2126     int mb_idx = SC_FW_MB_IDX(sc);
2127     uint32_t seq;
2128     uint32_t rc = 0;
2129     uint32_t cnt = 1;
2130     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2131 
2132     BXE_FWMB_LOCK(sc);
2133 
2134     seq = ++sc->fw_seq;
2135     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2136     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2137 
2138     BLOGD(sc, DBG_PHY,
2139           "wrote command 0x%08x to FW MB param 0x%08x\n",
2140           (command | seq), param);
2141 
2142     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2143     do {
2144         DELAY(delay * 1000);
2145         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2146     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2147 
2148     BLOGD(sc, DBG_PHY,
2149           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2150           cnt*delay, rc, seq);
2151 
2152     /* is this a reply to our command? */
2153     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2154         rc &= FW_MSG_CODE_MASK;
2155     } else {
2156         /* Ruh-roh! */
2157         BLOGE(sc, "FW failed to respond!\n");
2158         // XXX bxe_fw_dump(sc);
2159         rc = 0;
2160     }
2161 
2162     BXE_FWMB_UNLOCK(sc);
2163     return (rc);
2164 }
2165 
2166 static uint32_t
2167 bxe_fw_command(struct bxe_softc *sc,
2168                uint32_t         command,
2169                uint32_t         param)
2170 {
2171     return (elink_cb_fw_command(sc, command, param));
2172 }
2173 
2174 static void
2175 __storm_memset_dma_mapping(struct bxe_softc *sc,
2176                            uint32_t         addr,
2177                            bus_addr_t       mapping)
2178 {
2179     REG_WR(sc, addr, U64_LO(mapping));
2180     REG_WR(sc, (addr + 4), U64_HI(mapping));
2181 }
2182 
2183 static void
2184 storm_memset_spq_addr(struct bxe_softc *sc,
2185                       bus_addr_t       mapping,
2186                       uint16_t         abs_fid)
2187 {
2188     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2189                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2190     __storm_memset_dma_mapping(sc, addr, mapping);
2191 }
2192 
2193 static void
2194 storm_memset_vf_to_pf(struct bxe_softc *sc,
2195                       uint16_t         abs_fid,
2196                       uint16_t         pf_id)
2197 {
2198     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2199     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2200     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2201     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2202 }
2203 
2204 static void
2205 storm_memset_func_en(struct bxe_softc *sc,
2206                      uint16_t         abs_fid,
2207                      uint8_t          enable)
2208 {
2209     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2210     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2211     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2212     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2213 }
2214 
2215 static void
2216 storm_memset_eq_data(struct bxe_softc       *sc,
2217                      struct event_ring_data *eq_data,
2218                      uint16_t               pfid)
2219 {
2220     uint32_t addr;
2221     size_t size;
2222 
2223     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2224     size = sizeof(struct event_ring_data);
2225     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2226 }
2227 
2228 static void
2229 storm_memset_eq_prod(struct bxe_softc *sc,
2230                      uint16_t         eq_prod,
2231                      uint16_t         pfid)
2232 {
2233     uint32_t addr = (BAR_CSTRORM_INTMEM +
2234                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2235     REG_WR16(sc, addr, eq_prod);
2236 }
2237 
2238 /*
2239  * Post a slowpath command.
2240  *
2241  * A slowpath command is used to propagate a configuration change through
2242  * the controller in a controlled manner, allowing each STORM processor and
2243  * other H/W blocks to phase in the change.  The commands sent on the
2244  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2245  * completion of the ramrod will occur in different ways.  Here's a
2246  * breakdown of ramrods and how they complete:
2247  *
2248  * RAMROD_CMD_ID_ETH_PORT_SETUP
2249  *   Used to setup the leading connection on a port.  Completes on the
2250  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2251  *
2252  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2253  *   Used to setup an additional connection on a port.  Completes on the
2254  *   RCQ of the multi-queue/RSS connection being initialized.
2255  *
2256  * RAMROD_CMD_ID_ETH_STAT_QUERY
2257  *   Used to force the storm processors to update the statistics database
2258  *   in host memory.  This ramrod is send on the leading connection CID and
2259  *   completes as an index increment of the CSTORM on the default status
2260  *   block.
2261  *
2262  * RAMROD_CMD_ID_ETH_UPDATE
2263  *   Used to update the state of the leading connection, usually to udpate
2264  *   the RSS indirection table.  Completes on the RCQ of the leading
2265  *   connection. (Not currently used under FreeBSD until OS support becomes
2266  *   available.)
2267  *
2268  * RAMROD_CMD_ID_ETH_HALT
2269  *   Used when tearing down a connection prior to driver unload.  Completes
2270  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2271  *   use this on the leading connection.
2272  *
2273  * RAMROD_CMD_ID_ETH_SET_MAC
2274  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2275  *   the RCQ of the leading connection.
2276  *
2277  * RAMROD_CMD_ID_ETH_CFC_DEL
2278  *   Used when tearing down a conneciton prior to driver unload.  Completes
2279  *   on the RCQ of the leading connection (since the current connection
2280  *   has been completely removed from controller memory).
2281  *
2282  * RAMROD_CMD_ID_ETH_PORT_DEL
2283  *   Used to tear down the leading connection prior to driver unload,
2284  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2285  *   default status block.
2286  *
2287  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2288  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2289  *   RSS connection that is being offloaded.  (Not currently used under
2290  *   FreeBSD.)
2291  *
2292  * There can only be one command pending per function.
2293  *
2294  * Returns:
2295  *   0 = Success, !0 = Failure.
2296  */
2297 
2298 /* must be called under the spq lock */
2299 static inline
2300 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2301 {
2302     struct eth_spe *next_spe = sc->spq_prod_bd;
2303 
2304     if (sc->spq_prod_bd == sc->spq_last_bd) {
2305         /* wrap back to the first eth_spq */
2306         sc->spq_prod_bd = sc->spq;
2307         sc->spq_prod_idx = 0;
2308     } else {
2309         sc->spq_prod_bd++;
2310         sc->spq_prod_idx++;
2311     }
2312 
2313     return (next_spe);
2314 }
2315 
2316 /* must be called under the spq lock */
2317 static inline
2318 void bxe_sp_prod_update(struct bxe_softc *sc)
2319 {
2320     int func = SC_FUNC(sc);
2321 
2322     /*
2323      * Make sure that BD data is updated before writing the producer.
2324      * BD data is written to the memory, the producer is read from the
2325      * memory, thus we need a full memory barrier to ensure the ordering.
2326      */
2327     mb();
2328 
2329     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2330              sc->spq_prod_idx);
2331 
2332     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2333                       BUS_SPACE_BARRIER_WRITE);
2334 }
2335 
2336 /**
2337  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2338  *
2339  * @cmd:      command to check
2340  * @cmd_type: command type
2341  */
2342 static inline
2343 int bxe_is_contextless_ramrod(int cmd,
2344                               int cmd_type)
2345 {
2346     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2347         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2348         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2349         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2350         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2351         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2352         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2353         return (TRUE);
2354     } else {
2355         return (FALSE);
2356     }
2357 }
2358 
2359 /**
2360  * bxe_sp_post - place a single command on an SP ring
2361  *
2362  * @sc:         driver handle
2363  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2364  * @cid:        SW CID the command is related to
2365  * @data_hi:    command private data address (high 32 bits)
2366  * @data_lo:    command private data address (low 32 bits)
2367  * @cmd_type:   command type (e.g. NONE, ETH)
2368  *
2369  * SP data is handled as if it's always an address pair, thus data fields are
2370  * not swapped to little endian in upper functions. Instead this function swaps
2371  * data as if it's two uint32 fields.
2372  */
2373 int
2374 bxe_sp_post(struct bxe_softc *sc,
2375             int              command,
2376             int              cid,
2377             uint32_t         data_hi,
2378             uint32_t         data_lo,
2379             int              cmd_type)
2380 {
2381     struct eth_spe *spe;
2382     uint16_t type;
2383     int common;
2384 
2385     common = bxe_is_contextless_ramrod(command, cmd_type);
2386 
2387     BXE_SP_LOCK(sc);
2388 
2389     if (common) {
2390         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2391             BLOGE(sc, "EQ ring is full!\n");
2392             BXE_SP_UNLOCK(sc);
2393             return (-1);
2394         }
2395     } else {
2396         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2397             BLOGE(sc, "SPQ ring is full!\n");
2398             BXE_SP_UNLOCK(sc);
2399             return (-1);
2400         }
2401     }
2402 
2403     spe = bxe_sp_get_next(sc);
2404 
2405     /* CID needs port number to be encoded int it */
2406     spe->hdr.conn_and_cmd_data =
2407         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2408 
2409     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2410 
2411     /* TBD: Check if it works for VFs */
2412     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2413              SPE_HDR_T_FUNCTION_ID);
2414 
2415     spe->hdr.type = htole16(type);
2416 
2417     spe->data.update_data_addr.hi = htole32(data_hi);
2418     spe->data.update_data_addr.lo = htole32(data_lo);
2419 
2420     /*
2421      * It's ok if the actual decrement is issued towards the memory
2422      * somewhere between the lock and unlock. Thus no more explict
2423      * memory barrier is needed.
2424      */
2425     if (common) {
2426         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2427     } else {
2428         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2429     }
2430 
2431     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2432     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2433           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2434     BLOGD(sc, DBG_SP,
2435           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2436           sc->spq_prod_idx,
2437           (uint32_t)U64_HI(sc->spq_dma.paddr),
2438           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2439           command,
2440           common,
2441           HW_CID(sc, cid),
2442           data_hi,
2443           data_lo,
2444           type,
2445           atomic_load_acq_long(&sc->cq_spq_left),
2446           atomic_load_acq_long(&sc->eq_spq_left));
2447 
2448     bxe_sp_prod_update(sc);
2449 
2450     BXE_SP_UNLOCK(sc);
2451     return (0);
2452 }
2453 
2454 /**
2455  * bxe_debug_print_ind_table - prints the indirection table configuration.
2456  *
2457  * @sc: driver hanlde
2458  * @p:  pointer to rss configuration
2459  */
2460 
2461 /*
2462  * FreeBSD Device probe function.
2463  *
2464  * Compares the device found to the driver's list of supported devices and
2465  * reports back to the bsd loader whether this is the right driver for the device.
2466  * This is the driver entry function called from the "kldload" command.
2467  *
2468  * Returns:
2469  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2470  */
2471 static int
2472 bxe_probe(device_t dev)
2473 {
2474     struct bxe_device_type *t;
2475     char *descbuf;
2476     uint16_t did, sdid, svid, vid;
2477 
2478     /* Find our device structure */
2479     t = bxe_devs;
2480 
2481     /* Get the data for the device to be probed. */
2482     vid  = pci_get_vendor(dev);
2483     did  = pci_get_device(dev);
2484     svid = pci_get_subvendor(dev);
2485     sdid = pci_get_subdevice(dev);
2486 
2487     /* Look through the list of known devices for a match. */
2488     while (t->bxe_name != NULL) {
2489         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2490             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2491             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2492             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2493             if (descbuf == NULL)
2494                 return (ENOMEM);
2495 
2496             /* Print out the device identity. */
2497             snprintf(descbuf, BXE_DEVDESC_MAX,
2498                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2499                      (((pci_read_config(dev, PCIR_REVID, 4) &
2500                         0xf0) >> 4) + 'A'),
2501                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2502                      BXE_DRIVER_VERSION);
2503 
2504             device_set_desc_copy(dev, descbuf);
2505             free(descbuf, M_TEMP);
2506             return (BUS_PROBE_DEFAULT);
2507         }
2508         t++;
2509     }
2510 
2511     return (ENXIO);
2512 }
2513 
2514 static void
2515 bxe_init_mutexes(struct bxe_softc *sc)
2516 {
2517 #ifdef BXE_CORE_LOCK_SX
2518     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2519              "bxe%d_core_lock", sc->unit);
2520     sx_init(&sc->core_sx, sc->core_sx_name);
2521 #else
2522     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2523              "bxe%d_core_lock", sc->unit);
2524     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2525 #endif
2526 
2527     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2528              "bxe%d_sp_lock", sc->unit);
2529     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2530 
2531     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2532              "bxe%d_dmae_lock", sc->unit);
2533     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2534 
2535     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2536              "bxe%d_phy_lock", sc->unit);
2537     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2538 
2539     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2540              "bxe%d_fwmb_lock", sc->unit);
2541     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2542 
2543     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2544              "bxe%d_print_lock", sc->unit);
2545     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2546 
2547     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2548              "bxe%d_stats_lock", sc->unit);
2549     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2550 
2551     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2552              "bxe%d_mcast_lock", sc->unit);
2553     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2554 }
2555 
2556 static void
2557 bxe_release_mutexes(struct bxe_softc *sc)
2558 {
2559 #ifdef BXE_CORE_LOCK_SX
2560     sx_destroy(&sc->core_sx);
2561 #else
2562     if (mtx_initialized(&sc->core_mtx)) {
2563         mtx_destroy(&sc->core_mtx);
2564     }
2565 #endif
2566 
2567     if (mtx_initialized(&sc->sp_mtx)) {
2568         mtx_destroy(&sc->sp_mtx);
2569     }
2570 
2571     if (mtx_initialized(&sc->dmae_mtx)) {
2572         mtx_destroy(&sc->dmae_mtx);
2573     }
2574 
2575     if (mtx_initialized(&sc->port.phy_mtx)) {
2576         mtx_destroy(&sc->port.phy_mtx);
2577     }
2578 
2579     if (mtx_initialized(&sc->fwmb_mtx)) {
2580         mtx_destroy(&sc->fwmb_mtx);
2581     }
2582 
2583     if (mtx_initialized(&sc->print_mtx)) {
2584         mtx_destroy(&sc->print_mtx);
2585     }
2586 
2587     if (mtx_initialized(&sc->stats_mtx)) {
2588         mtx_destroy(&sc->stats_mtx);
2589     }
2590 
2591     if (mtx_initialized(&sc->mcast_mtx)) {
2592         mtx_destroy(&sc->mcast_mtx);
2593     }
2594 }
2595 
2596 static void
2597 bxe_tx_disable(struct bxe_softc* sc)
2598 {
2599     if_t ifp = sc->ifp;
2600 
2601     /* tell the stack the driver is stopped and TX queue is full */
2602     if (ifp !=  NULL) {
2603         if_setdrvflags(ifp, 0);
2604     }
2605 }
2606 
2607 static void
2608 bxe_drv_pulse(struct bxe_softc *sc)
2609 {
2610     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2611              sc->fw_drv_pulse_wr_seq);
2612 }
2613 
2614 static inline uint16_t
2615 bxe_tx_avail(struct bxe_softc *sc,
2616              struct bxe_fastpath *fp)
2617 {
2618     int16_t  used;
2619     uint16_t prod;
2620     uint16_t cons;
2621 
2622     prod = fp->tx_bd_prod;
2623     cons = fp->tx_bd_cons;
2624 
2625     used = SUB_S16(prod, cons);
2626 
2627     return (int16_t)(sc->tx_ring_size) - used;
2628 }
2629 
2630 static inline int
2631 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2632 {
2633     uint16_t hw_cons;
2634 
2635     mb(); /* status block fields can change */
2636     hw_cons = le16toh(*fp->tx_cons_sb);
2637     return (hw_cons != fp->tx_pkt_cons);
2638 }
2639 
2640 static inline uint8_t
2641 bxe_has_tx_work(struct bxe_fastpath *fp)
2642 {
2643     /* expand this for multi-cos if ever supported */
2644     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2645 }
2646 
2647 static inline int
2648 bxe_has_rx_work(struct bxe_fastpath *fp)
2649 {
2650     uint16_t rx_cq_cons_sb;
2651 
2652     mb(); /* status block fields can change */
2653     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2654     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2655         rx_cq_cons_sb++;
2656     return (fp->rx_cq_cons != rx_cq_cons_sb);
2657 }
2658 
2659 static void
2660 bxe_sp_event(struct bxe_softc    *sc,
2661              struct bxe_fastpath *fp,
2662              union eth_rx_cqe    *rr_cqe)
2663 {
2664     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2665     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2666     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2667     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2668 
2669     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2670           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2671 
2672     switch (command) {
2673     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2674         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2675         drv_cmd = ECORE_Q_CMD_UPDATE;
2676         break;
2677 
2678     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2679         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2680         drv_cmd = ECORE_Q_CMD_SETUP;
2681         break;
2682 
2683     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2684         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2685         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2686         break;
2687 
2688     case (RAMROD_CMD_ID_ETH_HALT):
2689         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2690         drv_cmd = ECORE_Q_CMD_HALT;
2691         break;
2692 
2693     case (RAMROD_CMD_ID_ETH_TERMINATE):
2694         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2695         drv_cmd = ECORE_Q_CMD_TERMINATE;
2696         break;
2697 
2698     case (RAMROD_CMD_ID_ETH_EMPTY):
2699         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2700         drv_cmd = ECORE_Q_CMD_EMPTY;
2701         break;
2702 
2703     default:
2704         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2705               command, fp->index);
2706         return;
2707     }
2708 
2709     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2710         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2711         /*
2712          * q_obj->complete_cmd() failure means that this was
2713          * an unexpected completion.
2714          *
2715          * In this case we don't want to increase the sc->spq_left
2716          * because apparently we haven't sent this command the first
2717          * place.
2718          */
2719         // bxe_panic(sc, ("Unexpected SP completion\n"));
2720         return;
2721     }
2722 
2723     atomic_add_acq_long(&sc->cq_spq_left, 1);
2724 
2725     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2726           atomic_load_acq_long(&sc->cq_spq_left));
2727 }
2728 
2729 /*
2730  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2731  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2732  * the current aggregation queue as in-progress.
2733  */
2734 static void
2735 bxe_tpa_start(struct bxe_softc            *sc,
2736               struct bxe_fastpath         *fp,
2737               uint16_t                    queue,
2738               uint16_t                    cons,
2739               uint16_t                    prod,
2740               struct eth_fast_path_rx_cqe *cqe)
2741 {
2742     struct bxe_sw_rx_bd tmp_bd;
2743     struct bxe_sw_rx_bd *rx_buf;
2744     struct eth_rx_bd *rx_bd;
2745     int max_agg_queues;
2746     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2747     uint16_t index;
2748 
2749     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2750                        "cons=%d prod=%d\n",
2751           fp->index, queue, cons, prod);
2752 
2753     max_agg_queues = MAX_AGG_QS(sc);
2754 
2755     KASSERT((queue < max_agg_queues),
2756             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2757              fp->index, queue, max_agg_queues));
2758 
2759     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2760             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2761              fp->index, queue));
2762 
2763     /* copy the existing mbuf and mapping from the TPA pool */
2764     tmp_bd = tpa_info->bd;
2765 
2766     if (tmp_bd.m == NULL) {
2767         uint32_t *tmp;
2768 
2769         tmp = (uint32_t *)cqe;
2770 
2771         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2772               fp->index, queue, cons, prod);
2773         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2774             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2775 
2776         /* XXX Error handling? */
2777         return;
2778     }
2779 
2780     /* change the TPA queue to the start state */
2781     tpa_info->state            = BXE_TPA_STATE_START;
2782     tpa_info->placement_offset = cqe->placement_offset;
2783     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2784     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2785     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2786 
2787     fp->rx_tpa_queue_used |= (1 << queue);
2788 
2789     /*
2790      * If all the buffer descriptors are filled with mbufs then fill in
2791      * the current consumer index with a new BD. Else if a maximum Rx
2792      * buffer limit is imposed then fill in the next producer index.
2793      */
2794     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2795                 prod : cons;
2796 
2797     /* move the received mbuf and mapping to TPA pool */
2798     tpa_info->bd = fp->rx_mbuf_chain[cons];
2799 
2800     /* release any existing RX BD mbuf mappings */
2801     if (cons != index) {
2802         rx_buf = &fp->rx_mbuf_chain[cons];
2803 
2804         if (rx_buf->m_map != NULL) {
2805             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2806                             BUS_DMASYNC_POSTREAD);
2807             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2808         }
2809 
2810         /*
2811          * We get here when the maximum number of rx buffers is less than
2812          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2813          * it out here without concern of a memory leak.
2814          */
2815         fp->rx_mbuf_chain[cons].m = NULL;
2816     }
2817 
2818     /* update the Rx SW BD with the mbuf info from the TPA pool */
2819     fp->rx_mbuf_chain[index] = tmp_bd;
2820 
2821     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2822     rx_bd = &fp->rx_chain[index];
2823     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2824     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2825 }
2826 
2827 /*
2828  * When a TPA aggregation is completed, loop through the individual mbufs
2829  * of the aggregation, combining them into a single mbuf which will be sent
2830  * up the stack. Refill all freed SGEs with mbufs as we go along.
2831  */
2832 static int
2833 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2834                    struct bxe_fastpath       *fp,
2835                    struct bxe_sw_tpa_info    *tpa_info,
2836                    uint16_t                  queue,
2837                    uint16_t                  pages,
2838                    struct mbuf               *m,
2839 			       struct eth_end_agg_rx_cqe *cqe,
2840                    uint16_t                  cqe_idx)
2841 {
2842     struct mbuf *m_frag;
2843     uint32_t frag_len, frag_size, i;
2844     uint16_t sge_idx;
2845     int rc = 0;
2846     int j;
2847 
2848     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2849 
2850     BLOGD(sc, DBG_LRO,
2851           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2852           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2853 
2854     /* make sure the aggregated frame is not too big to handle */
2855     if (pages > 8 * PAGES_PER_SGE) {
2856 
2857         uint32_t *tmp = (uint32_t *)cqe;
2858 
2859         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2860                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2861               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2862               tpa_info->len_on_bd, frag_size);
2863 
2864         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2865             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2866 
2867         bxe_panic(sc, ("sge page count error\n"));
2868         return (EINVAL);
2869     }
2870 
2871     /*
2872      * Scan through the scatter gather list pulling individual mbufs into a
2873      * single mbuf for the host stack.
2874      */
2875     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2876         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2877 
2878         /*
2879          * Firmware gives the indices of the SGE as if the ring is an array
2880          * (meaning that the "next" element will consume 2 indices).
2881          */
2882         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2883 
2884         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2885                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2886               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2887 
2888         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2889 
2890         /* allocate a new mbuf for the SGE */
2891         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2892         if (rc) {
2893             /* Leave all remaining SGEs in the ring! */
2894             return (rc);
2895         }
2896 
2897         /* update the fragment length */
2898         m_frag->m_len = frag_len;
2899 
2900         /* concatenate the fragment to the head mbuf */
2901         m_cat(m, m_frag);
2902         fp->eth_q_stats.mbuf_alloc_sge--;
2903 
2904         /* update the TPA mbuf size and remaining fragment size */
2905         m->m_pkthdr.len += frag_len;
2906         frag_size -= frag_len;
2907     }
2908 
2909     BLOGD(sc, DBG_LRO,
2910           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2911           fp->index, queue, frag_size);
2912 
2913     return (rc);
2914 }
2915 
2916 static inline void
2917 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2918 {
2919     int i, j;
2920 
2921     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2922         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2923 
2924         for (j = 0; j < 2; j++) {
2925             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2926             idx--;
2927         }
2928     }
2929 }
2930 
2931 static inline void
2932 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2933 {
2934     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2935     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2936 
2937     /*
2938      * Clear the two last indices in the page to 1. These are the indices that
2939      * correspond to the "next" element, hence will never be indicated and
2940      * should be removed from the calculations.
2941      */
2942     bxe_clear_sge_mask_next_elems(fp);
2943 }
2944 
2945 static inline void
2946 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2947                         uint16_t            idx)
2948 {
2949     uint16_t last_max = fp->last_max_sge;
2950 
2951     if (SUB_S16(idx, last_max) > 0) {
2952         fp->last_max_sge = idx;
2953     }
2954 }
2955 
2956 static inline void
2957 bxe_update_sge_prod(struct bxe_softc          *sc,
2958                     struct bxe_fastpath       *fp,
2959                     uint16_t                  sge_len,
2960                     union eth_sgl_or_raw_data *cqe)
2961 {
2962     uint16_t last_max, last_elem, first_elem;
2963     uint16_t delta = 0;
2964     uint16_t i;
2965 
2966     if (!sge_len) {
2967         return;
2968     }
2969 
2970     /* first mark all used pages */
2971     for (i = 0; i < sge_len; i++) {
2972         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2973                             RX_SGE(le16toh(cqe->sgl[i])));
2974     }
2975 
2976     BLOGD(sc, DBG_LRO,
2977           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2978           fp->index, sge_len - 1,
2979           le16toh(cqe->sgl[sge_len - 1]));
2980 
2981     /* assume that the last SGE index is the biggest */
2982     bxe_update_last_max_sge(fp,
2983                             le16toh(cqe->sgl[sge_len - 1]));
2984 
2985     last_max = RX_SGE(fp->last_max_sge);
2986     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2987     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2988 
2989     /* if ring is not full */
2990     if (last_elem + 1 != first_elem) {
2991         last_elem++;
2992     }
2993 
2994     /* now update the prod */
2995     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2996         if (__predict_true(fp->sge_mask[i])) {
2997             break;
2998         }
2999 
3000         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3001         delta += BIT_VEC64_ELEM_SZ;
3002     }
3003 
3004     if (delta > 0) {
3005         fp->rx_sge_prod += delta;
3006         /* clear page-end entries */
3007         bxe_clear_sge_mask_next_elems(fp);
3008     }
3009 
3010     BLOGD(sc, DBG_LRO,
3011           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3012           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3013 }
3014 
3015 /*
3016  * The aggregation on the current TPA queue has completed. Pull the individual
3017  * mbuf fragments together into a single mbuf, perform all necessary checksum
3018  * calculations, and send the resuting mbuf to the stack.
3019  */
3020 static void
3021 bxe_tpa_stop(struct bxe_softc          *sc,
3022              struct bxe_fastpath       *fp,
3023              struct bxe_sw_tpa_info    *tpa_info,
3024              uint16_t                  queue,
3025              uint16_t                  pages,
3026 			 struct eth_end_agg_rx_cqe *cqe,
3027              uint16_t                  cqe_idx)
3028 {
3029     if_t ifp = sc->ifp;
3030     struct mbuf *m;
3031     int rc = 0;
3032 
3033     BLOGD(sc, DBG_LRO,
3034           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3035           fp->index, queue, tpa_info->placement_offset,
3036           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3037 
3038     m = tpa_info->bd.m;
3039 
3040     /* allocate a replacement before modifying existing mbuf */
3041     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3042     if (rc) {
3043         /* drop the frame and log an error */
3044         fp->eth_q_stats.rx_soft_errors++;
3045         goto bxe_tpa_stop_exit;
3046     }
3047 
3048     /* we have a replacement, fixup the current mbuf */
3049     m_adj(m, tpa_info->placement_offset);
3050     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3051 
3052     /* mark the checksums valid (taken care of by the firmware) */
3053     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3054     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3055     m->m_pkthdr.csum_data = 0xffff;
3056     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3057                                CSUM_IP_VALID   |
3058                                CSUM_DATA_VALID |
3059                                CSUM_PSEUDO_HDR);
3060 
3061     /* aggregate all of the SGEs into a single mbuf */
3062     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3063     if (rc) {
3064         /* drop the packet and log an error */
3065         fp->eth_q_stats.rx_soft_errors++;
3066         m_freem(m);
3067     } else {
3068         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3069             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3070             m->m_flags |= M_VLANTAG;
3071         }
3072 
3073         /* assign packet to this interface interface */
3074         if_setrcvif(m, ifp);
3075 
3076 #if __FreeBSD_version >= 800000
3077         /* specify what RSS queue was used for this flow */
3078         m->m_pkthdr.flowid = fp->index;
3079         BXE_SET_FLOWID(m);
3080 #endif
3081 
3082         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3083         fp->eth_q_stats.rx_tpa_pkts++;
3084 
3085         /* pass the frame to the stack */
3086         if_input(ifp, m);
3087     }
3088 
3089     /* we passed an mbuf up the stack or dropped the frame */
3090     fp->eth_q_stats.mbuf_alloc_tpa--;
3091 
3092 bxe_tpa_stop_exit:
3093 
3094     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3095     fp->rx_tpa_queue_used &= ~(1 << queue);
3096 }
3097 
3098 static uint8_t
3099 bxe_service_rxsgl(
3100                  struct bxe_fastpath *fp,
3101                  uint16_t len,
3102                  uint16_t lenonbd,
3103                  struct mbuf *m,
3104                  struct eth_fast_path_rx_cqe *cqe_fp)
3105 {
3106     struct mbuf *m_frag;
3107     uint16_t frags, frag_len;
3108     uint16_t sge_idx = 0;
3109     uint16_t j;
3110     uint8_t i, rc = 0;
3111     uint32_t frag_size;
3112 
3113     /* adjust the mbuf */
3114     m->m_len = lenonbd;
3115 
3116     frag_size =  len - lenonbd;
3117     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3118 
3119     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3120         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3121 
3122         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3123         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3124         m_frag->m_len = frag_len;
3125 
3126        /* allocate a new mbuf for the SGE */
3127         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3128         if (rc) {
3129             /* Leave all remaining SGEs in the ring! */
3130             return (rc);
3131         }
3132         fp->eth_q_stats.mbuf_alloc_sge--;
3133 
3134         /* concatenate the fragment to the head mbuf */
3135         m_cat(m, m_frag);
3136 
3137         frag_size -= frag_len;
3138     }
3139 
3140     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3141 
3142     return rc;
3143 }
3144 
3145 static uint8_t
3146 bxe_rxeof(struct bxe_softc    *sc,
3147           struct bxe_fastpath *fp)
3148 {
3149     if_t ifp = sc->ifp;
3150     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3151     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3152     int rx_pkts = 0;
3153     int rc = 0;
3154 
3155     BXE_FP_RX_LOCK(fp);
3156 
3157     /* CQ "next element" is of the size of the regular element */
3158     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3159     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3160         hw_cq_cons++;
3161     }
3162 
3163     bd_cons = fp->rx_bd_cons;
3164     bd_prod = fp->rx_bd_prod;
3165     bd_prod_fw = bd_prod;
3166     sw_cq_cons = fp->rx_cq_cons;
3167     sw_cq_prod = fp->rx_cq_prod;
3168 
3169     /*
3170      * Memory barrier necessary as speculative reads of the rx
3171      * buffer can be ahead of the index in the status block
3172      */
3173     rmb();
3174 
3175     BLOGD(sc, DBG_RX,
3176           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3177           fp->index, hw_cq_cons, sw_cq_cons);
3178 
3179     while (sw_cq_cons != hw_cq_cons) {
3180         struct bxe_sw_rx_bd *rx_buf = NULL;
3181         union eth_rx_cqe *cqe;
3182         struct eth_fast_path_rx_cqe *cqe_fp;
3183         uint8_t cqe_fp_flags;
3184         enum eth_rx_cqe_type cqe_fp_type;
3185         uint16_t len, lenonbd,  pad;
3186         struct mbuf *m = NULL;
3187 
3188         comp_ring_cons = RCQ(sw_cq_cons);
3189         bd_prod = RX_BD(bd_prod);
3190         bd_cons = RX_BD(bd_cons);
3191 
3192         cqe          = &fp->rcq_chain[comp_ring_cons];
3193         cqe_fp       = &cqe->fast_path_cqe;
3194         cqe_fp_flags = cqe_fp->type_error_flags;
3195         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3196 
3197         BLOGD(sc, DBG_RX,
3198               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3199               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3200               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3201               fp->index,
3202               hw_cq_cons,
3203               sw_cq_cons,
3204               bd_prod,
3205               bd_cons,
3206               CQE_TYPE(cqe_fp_flags),
3207               cqe_fp_flags,
3208               cqe_fp->status_flags,
3209               le32toh(cqe_fp->rss_hash_result),
3210               le16toh(cqe_fp->vlan_tag),
3211               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3212               le16toh(cqe_fp->len_on_bd));
3213 
3214         /* is this a slowpath msg? */
3215         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3216             bxe_sp_event(sc, fp, cqe);
3217             goto next_cqe;
3218         }
3219 
3220         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3221 
3222         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3223             struct bxe_sw_tpa_info *tpa_info;
3224             uint16_t frag_size, pages;
3225             uint8_t queue;
3226 
3227             if (CQE_TYPE_START(cqe_fp_type)) {
3228                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3229                               bd_cons, bd_prod, cqe_fp);
3230                 m = NULL; /* packet not ready yet */
3231                 goto next_rx;
3232             }
3233 
3234             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3235                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3236 
3237             queue = cqe->end_agg_cqe.queue_index;
3238             tpa_info = &fp->rx_tpa_info[queue];
3239 
3240             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3241                   fp->index, queue);
3242 
3243             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3244                          tpa_info->len_on_bd);
3245             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3246 
3247             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3248                          &cqe->end_agg_cqe, comp_ring_cons);
3249 
3250             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3251 
3252             goto next_cqe;
3253         }
3254 
3255         /* non TPA */
3256 
3257         /* is this an error packet? */
3258         if (__predict_false(cqe_fp_flags &
3259                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3260             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3261             fp->eth_q_stats.rx_soft_errors++;
3262             goto next_rx;
3263         }
3264 
3265         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3266         lenonbd = le16toh(cqe_fp->len_on_bd);
3267         pad = cqe_fp->placement_offset;
3268 
3269         m = rx_buf->m;
3270 
3271         if (__predict_false(m == NULL)) {
3272             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3273                   bd_cons, fp->index);
3274             goto next_rx;
3275         }
3276 
3277         /* XXX double copy if packet length under a threshold */
3278 
3279         /*
3280          * If all the buffer descriptors are filled with mbufs then fill in
3281          * the current consumer index with a new BD. Else if a maximum Rx
3282          * buffer limit is imposed then fill in the next producer index.
3283          */
3284         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3285                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3286                                       bd_prod : bd_cons);
3287         if (rc != 0) {
3288 
3289             /* we simply reuse the received mbuf and don't post it to the stack */
3290             m = NULL;
3291 
3292             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3293                   fp->index, rc);
3294             fp->eth_q_stats.rx_soft_errors++;
3295 
3296             if (sc->max_rx_bufs != RX_BD_USABLE) {
3297                 /* copy this consumer index to the producer index */
3298                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3299                        sizeof(struct bxe_sw_rx_bd));
3300                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3301             }
3302 
3303             goto next_rx;
3304         }
3305 
3306         /* current mbuf was detached from the bd */
3307         fp->eth_q_stats.mbuf_alloc_rx--;
3308 
3309         /* we allocated a replacement mbuf, fixup the current one */
3310         m_adj(m, pad);
3311         m->m_pkthdr.len = m->m_len = len;
3312 
3313         if ((len > 60) && (len > lenonbd)) {
3314             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3315             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3316             if (rc)
3317                 break;
3318             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3319         } else if (lenonbd < len) {
3320             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3321         }
3322 
3323         /* assign packet to this interface interface */
3324 	if_setrcvif(m, ifp);
3325 
3326         /* assume no hardware checksum has complated */
3327         m->m_pkthdr.csum_flags = 0;
3328 
3329         /* validate checksum if offload enabled */
3330         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3331             /* check for a valid IP frame */
3332             if (!(cqe->fast_path_cqe.status_flags &
3333                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3334                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3335                 if (__predict_false(cqe_fp_flags &
3336                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3337                     fp->eth_q_stats.rx_hw_csum_errors++;
3338                 } else {
3339                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3340                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3341                 }
3342             }
3343 
3344             /* check for a valid TCP/UDP frame */
3345             if (!(cqe->fast_path_cqe.status_flags &
3346                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3347                 if (__predict_false(cqe_fp_flags &
3348                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3349                     fp->eth_q_stats.rx_hw_csum_errors++;
3350                 } else {
3351                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3352                     m->m_pkthdr.csum_data = 0xFFFF;
3353                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3354                                                CSUM_PSEUDO_HDR);
3355                 }
3356             }
3357         }
3358 
3359         /* if there is a VLAN tag then flag that info */
3360         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3361             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3362             m->m_flags |= M_VLANTAG;
3363         }
3364 
3365 #if __FreeBSD_version >= 800000
3366         /* specify what RSS queue was used for this flow */
3367         m->m_pkthdr.flowid = fp->index;
3368         BXE_SET_FLOWID(m);
3369 #endif
3370 
3371 next_rx:
3372 
3373         bd_cons    = RX_BD_NEXT(bd_cons);
3374         bd_prod    = RX_BD_NEXT(bd_prod);
3375         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3376 
3377         /* pass the frame to the stack */
3378         if (__predict_true(m != NULL)) {
3379             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3380             rx_pkts++;
3381             if_input(ifp, m);
3382         }
3383 
3384 next_cqe:
3385 
3386         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3387         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3388 
3389         /* limit spinning on the queue */
3390         if (rc != 0)
3391             break;
3392 
3393         if (rx_pkts == sc->rx_budget) {
3394             fp->eth_q_stats.rx_budget_reached++;
3395             break;
3396         }
3397     } /* while work to do */
3398 
3399     fp->rx_bd_cons = bd_cons;
3400     fp->rx_bd_prod = bd_prod_fw;
3401     fp->rx_cq_cons = sw_cq_cons;
3402     fp->rx_cq_prod = sw_cq_prod;
3403 
3404     /* Update producers */
3405     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3406 
3407     fp->eth_q_stats.rx_pkts += rx_pkts;
3408     fp->eth_q_stats.rx_calls++;
3409 
3410     BXE_FP_RX_UNLOCK(fp);
3411 
3412     return (sw_cq_cons != hw_cq_cons);
3413 }
3414 
3415 static uint16_t
3416 bxe_free_tx_pkt(struct bxe_softc    *sc,
3417                 struct bxe_fastpath *fp,
3418                 uint16_t            idx)
3419 {
3420     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3421     struct eth_tx_start_bd *tx_start_bd;
3422     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3423     uint16_t new_cons;
3424     int nbd;
3425 
3426     /* unmap the mbuf from non-paged memory */
3427     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3428 
3429     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3430     nbd = le16toh(tx_start_bd->nbd) - 1;
3431 
3432     new_cons = (tx_buf->first_bd + nbd);
3433 
3434     /* free the mbuf */
3435     if (__predict_true(tx_buf->m != NULL)) {
3436         m_freem(tx_buf->m);
3437         fp->eth_q_stats.mbuf_alloc_tx--;
3438     } else {
3439         fp->eth_q_stats.tx_chain_lost_mbuf++;
3440     }
3441 
3442     tx_buf->m = NULL;
3443     tx_buf->first_bd = 0;
3444 
3445     return (new_cons);
3446 }
3447 
3448 /* transmit timeout watchdog */
3449 static int
3450 bxe_watchdog(struct bxe_softc    *sc,
3451              struct bxe_fastpath *fp)
3452 {
3453     BXE_FP_TX_LOCK(fp);
3454 
3455     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3456         BXE_FP_TX_UNLOCK(fp);
3457         return (0);
3458     }
3459 
3460     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3461     if(sc->trigger_grcdump) {
3462          /* taking grcdump */
3463          bxe_grc_dump(sc);
3464     }
3465 
3466     BXE_FP_TX_UNLOCK(fp);
3467 
3468     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3469     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3470 
3471     return (-1);
3472 }
3473 
3474 /* processes transmit completions */
3475 static uint8_t
3476 bxe_txeof(struct bxe_softc    *sc,
3477           struct bxe_fastpath *fp)
3478 {
3479     if_t ifp = sc->ifp;
3480     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3481     uint16_t tx_bd_avail;
3482 
3483     BXE_FP_TX_LOCK_ASSERT(fp);
3484 
3485     bd_cons = fp->tx_bd_cons;
3486     hw_cons = le16toh(*fp->tx_cons_sb);
3487     sw_cons = fp->tx_pkt_cons;
3488 
3489     while (sw_cons != hw_cons) {
3490         pkt_cons = TX_BD(sw_cons);
3491 
3492         BLOGD(sc, DBG_TX,
3493               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3494               fp->index, hw_cons, sw_cons, pkt_cons);
3495 
3496         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3497 
3498         sw_cons++;
3499     }
3500 
3501     fp->tx_pkt_cons = sw_cons;
3502     fp->tx_bd_cons  = bd_cons;
3503 
3504     BLOGD(sc, DBG_TX,
3505           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3506           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3507 
3508     mb();
3509 
3510     tx_bd_avail = bxe_tx_avail(sc, fp);
3511 
3512     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3513         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3514     } else {
3515         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3516     }
3517 
3518     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3519         /* reset the watchdog timer if there are pending transmits */
3520         fp->watchdog_timer = BXE_TX_TIMEOUT;
3521         return (TRUE);
3522     } else {
3523         /* clear watchdog when there are no pending transmits */
3524         fp->watchdog_timer = 0;
3525         return (FALSE);
3526     }
3527 }
3528 
3529 static void
3530 bxe_drain_tx_queues(struct bxe_softc *sc)
3531 {
3532     struct bxe_fastpath *fp;
3533     int i, count;
3534 
3535     /* wait until all TX fastpath tasks have completed */
3536     for (i = 0; i < sc->num_queues; i++) {
3537         fp = &sc->fp[i];
3538 
3539         count = 1000;
3540 
3541         while (bxe_has_tx_work(fp)) {
3542 
3543             BXE_FP_TX_LOCK(fp);
3544             bxe_txeof(sc, fp);
3545             BXE_FP_TX_UNLOCK(fp);
3546 
3547             if (count == 0) {
3548                 BLOGE(sc, "Timeout waiting for fp[%d] "
3549                           "transmits to complete!\n", i);
3550                 bxe_panic(sc, ("tx drain failure\n"));
3551                 return;
3552             }
3553 
3554             count--;
3555             DELAY(1000);
3556             rmb();
3557         }
3558     }
3559 
3560     return;
3561 }
3562 
3563 static int
3564 bxe_del_all_macs(struct bxe_softc          *sc,
3565                  struct ecore_vlan_mac_obj *mac_obj,
3566                  int                       mac_type,
3567                  uint8_t                   wait_for_comp)
3568 {
3569     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3570     int rc;
3571 
3572     /* wait for completion of requested */
3573     if (wait_for_comp) {
3574         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3575     }
3576 
3577     /* Set the mac type of addresses we want to clear */
3578     bxe_set_bit(mac_type, &vlan_mac_flags);
3579 
3580     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3581     if (rc < 0) {
3582         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3583             rc, mac_type, wait_for_comp);
3584     }
3585 
3586     return (rc);
3587 }
3588 
3589 static int
3590 bxe_fill_accept_flags(struct bxe_softc *sc,
3591                       uint32_t         rx_mode,
3592                       unsigned long    *rx_accept_flags,
3593                       unsigned long    *tx_accept_flags)
3594 {
3595     /* Clear the flags first */
3596     *rx_accept_flags = 0;
3597     *tx_accept_flags = 0;
3598 
3599     switch (rx_mode) {
3600     case BXE_RX_MODE_NONE:
3601         /*
3602          * 'drop all' supersedes any accept flags that may have been
3603          * passed to the function.
3604          */
3605         break;
3606 
3607     case BXE_RX_MODE_NORMAL:
3608         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3609         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3610         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3611 
3612         /* internal switching mode */
3613         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3614         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3615         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3616 
3617         break;
3618 
3619     case BXE_RX_MODE_ALLMULTI:
3620         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3621         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3622         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3623 
3624         /* internal switching mode */
3625         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3626         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3627         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3628 
3629         break;
3630 
3631     case BXE_RX_MODE_PROMISC:
3632         /*
3633          * According to deffinition of SI mode, iface in promisc mode
3634          * should receive matched and unmatched (in resolution of port)
3635          * unicast packets.
3636          */
3637         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3638         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3639         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3640         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3641 
3642         /* internal switching mode */
3643         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3644         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3645 
3646         if (IS_MF_SI(sc)) {
3647             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3648         } else {
3649             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3650         }
3651 
3652         break;
3653 
3654     default:
3655         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3656         return (-1);
3657     }
3658 
3659     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3660     if (rx_mode != BXE_RX_MODE_NONE) {
3661         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3662         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3663     }
3664 
3665     return (0);
3666 }
3667 
3668 static int
3669 bxe_set_q_rx_mode(struct bxe_softc *sc,
3670                   uint8_t          cl_id,
3671                   unsigned long    rx_mode_flags,
3672                   unsigned long    rx_accept_flags,
3673                   unsigned long    tx_accept_flags,
3674                   unsigned long    ramrod_flags)
3675 {
3676     struct ecore_rx_mode_ramrod_params ramrod_param;
3677     int rc;
3678 
3679     memset(&ramrod_param, 0, sizeof(ramrod_param));
3680 
3681     /* Prepare ramrod parameters */
3682     ramrod_param.cid = 0;
3683     ramrod_param.cl_id = cl_id;
3684     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3685     ramrod_param.func_id = SC_FUNC(sc);
3686 
3687     ramrod_param.pstate = &sc->sp_state;
3688     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3689 
3690     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3691     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3692 
3693     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3694 
3695     ramrod_param.ramrod_flags = ramrod_flags;
3696     ramrod_param.rx_mode_flags = rx_mode_flags;
3697 
3698     ramrod_param.rx_accept_flags = rx_accept_flags;
3699     ramrod_param.tx_accept_flags = tx_accept_flags;
3700 
3701     rc = ecore_config_rx_mode(sc, &ramrod_param);
3702     if (rc < 0) {
3703         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3704             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3705             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3706             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3707             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3708         return (rc);
3709     }
3710 
3711     return (0);
3712 }
3713 
3714 static int
3715 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3716 {
3717     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3718     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3719     int rc;
3720 
3721     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3722                                &tx_accept_flags);
3723     if (rc) {
3724         return (rc);
3725     }
3726 
3727     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3728     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3729 
3730     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3731     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3732                               rx_accept_flags, tx_accept_flags,
3733                               ramrod_flags));
3734 }
3735 
3736 /* returns the "mcp load_code" according to global load_count array */
3737 static int
3738 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3739 {
3740     int path = SC_PATH(sc);
3741     int port = SC_PORT(sc);
3742 
3743     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3744           path, load_count[path][0], load_count[path][1],
3745           load_count[path][2]);
3746     load_count[path][0]++;
3747     load_count[path][1 + port]++;
3748     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3749           path, load_count[path][0], load_count[path][1],
3750           load_count[path][2]);
3751     if (load_count[path][0] == 1) {
3752         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3753     } else if (load_count[path][1 + port] == 1) {
3754         return (FW_MSG_CODE_DRV_LOAD_PORT);
3755     } else {
3756         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3757     }
3758 }
3759 
3760 /* returns the "mcp load_code" according to global load_count array */
3761 static int
3762 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3763 {
3764     int port = SC_PORT(sc);
3765     int path = SC_PATH(sc);
3766 
3767     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3768           path, load_count[path][0], load_count[path][1],
3769           load_count[path][2]);
3770     load_count[path][0]--;
3771     load_count[path][1 + port]--;
3772     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3773           path, load_count[path][0], load_count[path][1],
3774           load_count[path][2]);
3775     if (load_count[path][0] == 0) {
3776         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3777     } else if (load_count[path][1 + port] == 0) {
3778         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3779     } else {
3780         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3781     }
3782 }
3783 
3784 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3785 static uint32_t
3786 bxe_send_unload_req(struct bxe_softc *sc,
3787                     int              unload_mode)
3788 {
3789     uint32_t reset_code = 0;
3790 
3791     /* Select the UNLOAD request mode */
3792     if (unload_mode == UNLOAD_NORMAL) {
3793         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3794     } else {
3795         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3796     }
3797 
3798     /* Send the request to the MCP */
3799     if (!BXE_NOMCP(sc)) {
3800         reset_code = bxe_fw_command(sc, reset_code, 0);
3801     } else {
3802         reset_code = bxe_nic_unload_no_mcp(sc);
3803     }
3804 
3805     return (reset_code);
3806 }
3807 
3808 /* send UNLOAD_DONE command to the MCP */
3809 static void
3810 bxe_send_unload_done(struct bxe_softc *sc,
3811                      uint8_t          keep_link)
3812 {
3813     uint32_t reset_param =
3814         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3815 
3816     /* Report UNLOAD_DONE to MCP */
3817     if (!BXE_NOMCP(sc)) {
3818         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3819     }
3820 }
3821 
3822 static int
3823 bxe_func_wait_started(struct bxe_softc *sc)
3824 {
3825     int tout = 50;
3826 
3827     if (!sc->port.pmf) {
3828         return (0);
3829     }
3830 
3831     /*
3832      * (assumption: No Attention from MCP at this stage)
3833      * PMF probably in the middle of TX disable/enable transaction
3834      * 1. Sync IRS for default SB
3835      * 2. Sync SP queue - this guarantees us that attention handling started
3836      * 3. Wait, that TX disable/enable transaction completes
3837      *
3838      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3839      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3840      * received completion for the transaction the state is TX_STOPPED.
3841      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3842      * transaction.
3843      */
3844 
3845     /* XXX make sure default SB ISR is done */
3846     /* need a way to synchronize an irq (intr_mtx?) */
3847 
3848     /* XXX flush any work queues */
3849 
3850     while (ecore_func_get_state(sc, &sc->func_obj) !=
3851            ECORE_F_STATE_STARTED && tout--) {
3852         DELAY(20000);
3853     }
3854 
3855     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3856         /*
3857          * Failed to complete the transaction in a "good way"
3858          * Force both transactions with CLR bit.
3859          */
3860         struct ecore_func_state_params func_params = { NULL };
3861 
3862         BLOGE(sc, "Unexpected function state! "
3863                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3864 
3865         func_params.f_obj = &sc->func_obj;
3866         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3867 
3868         /* STARTED-->TX_STOPPED */
3869         func_params.cmd = ECORE_F_CMD_TX_STOP;
3870         ecore_func_state_change(sc, &func_params);
3871 
3872         /* TX_STOPPED-->STARTED */
3873         func_params.cmd = ECORE_F_CMD_TX_START;
3874         return (ecore_func_state_change(sc, &func_params));
3875     }
3876 
3877     return (0);
3878 }
3879 
3880 static int
3881 bxe_stop_queue(struct bxe_softc *sc,
3882                int              index)
3883 {
3884     struct bxe_fastpath *fp = &sc->fp[index];
3885     struct ecore_queue_state_params q_params = { NULL };
3886     int rc;
3887 
3888     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3889 
3890     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3891     /* We want to wait for completion in this context */
3892     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3893 
3894     /* Stop the primary connection: */
3895 
3896     /* ...halt the connection */
3897     q_params.cmd = ECORE_Q_CMD_HALT;
3898     rc = ecore_queue_state_change(sc, &q_params);
3899     if (rc) {
3900         return (rc);
3901     }
3902 
3903     /* ...terminate the connection */
3904     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3905     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3906     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3907     rc = ecore_queue_state_change(sc, &q_params);
3908     if (rc) {
3909         return (rc);
3910     }
3911 
3912     /* ...delete cfc entry */
3913     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3914     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3915     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3916     return (ecore_queue_state_change(sc, &q_params));
3917 }
3918 
3919 /* wait for the outstanding SP commands */
3920 static inline uint8_t
3921 bxe_wait_sp_comp(struct bxe_softc *sc,
3922                  unsigned long    mask)
3923 {
3924     unsigned long tmp;
3925     int tout = 5000; /* wait for 5 secs tops */
3926 
3927     while (tout--) {
3928         mb();
3929         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3930             return (TRUE);
3931         }
3932 
3933         DELAY(1000);
3934     }
3935 
3936     mb();
3937 
3938     tmp = atomic_load_acq_long(&sc->sp_state);
3939     if (tmp & mask) {
3940         BLOGE(sc, "Filtering completion timed out: "
3941                   "sp_state 0x%lx, mask 0x%lx\n",
3942               tmp, mask);
3943         return (FALSE);
3944     }
3945 
3946     return (FALSE);
3947 }
3948 
3949 static int
3950 bxe_func_stop(struct bxe_softc *sc)
3951 {
3952     struct ecore_func_state_params func_params = { NULL };
3953     int rc;
3954 
3955     /* prepare parameters for function state transitions */
3956     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3957     func_params.f_obj = &sc->func_obj;
3958     func_params.cmd = ECORE_F_CMD_STOP;
3959 
3960     /*
3961      * Try to stop the function the 'good way'. If it fails (in case
3962      * of a parity error during bxe_chip_cleanup()) and we are
3963      * not in a debug mode, perform a state transaction in order to
3964      * enable further HW_RESET transaction.
3965      */
3966     rc = ecore_func_state_change(sc, &func_params);
3967     if (rc) {
3968         BLOGE(sc, "FUNC_STOP ramrod failed. "
3969                   "Running a dry transaction (%d)\n", rc);
3970         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3971         return (ecore_func_state_change(sc, &func_params));
3972     }
3973 
3974     return (0);
3975 }
3976 
3977 static int
3978 bxe_reset_hw(struct bxe_softc *sc,
3979              uint32_t         load_code)
3980 {
3981     struct ecore_func_state_params func_params = { NULL };
3982 
3983     /* Prepare parameters for function state transitions */
3984     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3985 
3986     func_params.f_obj = &sc->func_obj;
3987     func_params.cmd = ECORE_F_CMD_HW_RESET;
3988 
3989     func_params.params.hw_init.load_phase = load_code;
3990 
3991     return (ecore_func_state_change(sc, &func_params));
3992 }
3993 
3994 static void
3995 bxe_int_disable_sync(struct bxe_softc *sc,
3996                      int              disable_hw)
3997 {
3998     if (disable_hw) {
3999         /* prevent the HW from sending interrupts */
4000         bxe_int_disable(sc);
4001     }
4002 
4003     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4004     /* make sure all ISRs are done */
4005 
4006     /* XXX make sure sp_task is not running */
4007     /* cancel and flush work queues */
4008 }
4009 
4010 static void
4011 bxe_chip_cleanup(struct bxe_softc *sc,
4012                  uint32_t         unload_mode,
4013                  uint8_t          keep_link)
4014 {
4015     int port = SC_PORT(sc);
4016     struct ecore_mcast_ramrod_params rparam = { NULL };
4017     uint32_t reset_code;
4018     int i, rc = 0;
4019 
4020     bxe_drain_tx_queues(sc);
4021 
4022     /* give HW time to discard old tx messages */
4023     DELAY(1000);
4024 
4025     /* Clean all ETH MACs */
4026     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4027     if (rc < 0) {
4028         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4029     }
4030 
4031     /* Clean up UC list  */
4032     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4033     if (rc < 0) {
4034         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4035     }
4036 
4037     /* Disable LLH */
4038     if (!CHIP_IS_E1(sc)) {
4039         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4040     }
4041 
4042     /* Set "drop all" to stop Rx */
4043 
4044     /*
4045      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4046      * a race between the completion code and this code.
4047      */
4048     BXE_MCAST_LOCK(sc);
4049 
4050     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4051         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4052     } else {
4053         bxe_set_storm_rx_mode(sc);
4054     }
4055 
4056     /* Clean up multicast configuration */
4057     rparam.mcast_obj = &sc->mcast_obj;
4058     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4059     if (rc < 0) {
4060         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4061     }
4062 
4063     BXE_MCAST_UNLOCK(sc);
4064 
4065     // XXX bxe_iov_chip_cleanup(sc);
4066 
4067     /*
4068      * Send the UNLOAD_REQUEST to the MCP. This will return if
4069      * this function should perform FUNCTION, PORT, or COMMON HW
4070      * reset.
4071      */
4072     reset_code = bxe_send_unload_req(sc, unload_mode);
4073 
4074     /*
4075      * (assumption: No Attention from MCP at this stage)
4076      * PMF probably in the middle of TX disable/enable transaction
4077      */
4078     rc = bxe_func_wait_started(sc);
4079     if (rc) {
4080         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4081     }
4082 
4083     /*
4084      * Close multi and leading connections
4085      * Completions for ramrods are collected in a synchronous way
4086      */
4087     for (i = 0; i < sc->num_queues; i++) {
4088         if (bxe_stop_queue(sc, i)) {
4089             goto unload_error;
4090         }
4091     }
4092 
4093     /*
4094      * If SP settings didn't get completed so far - something
4095      * very wrong has happen.
4096      */
4097     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4098         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4099     }
4100 
4101 unload_error:
4102 
4103     rc = bxe_func_stop(sc);
4104     if (rc) {
4105         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4106     }
4107 
4108     /* disable HW interrupts */
4109     bxe_int_disable_sync(sc, TRUE);
4110 
4111     /* detach interrupts */
4112     bxe_interrupt_detach(sc);
4113 
4114     /* Reset the chip */
4115     rc = bxe_reset_hw(sc, reset_code);
4116     if (rc) {
4117         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4118     }
4119 
4120     /* Report UNLOAD_DONE to MCP */
4121     bxe_send_unload_done(sc, keep_link);
4122 }
4123 
4124 static void
4125 bxe_disable_close_the_gate(struct bxe_softc *sc)
4126 {
4127     uint32_t val;
4128     int port = SC_PORT(sc);
4129 
4130     BLOGD(sc, DBG_LOAD,
4131           "Disabling 'close the gates'\n");
4132 
4133     if (CHIP_IS_E1(sc)) {
4134         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4135                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4136         val = REG_RD(sc, addr);
4137         val &= ~(0x300);
4138         REG_WR(sc, addr, val);
4139     } else {
4140         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4141         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4142                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4143         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4144     }
4145 }
4146 
4147 /*
4148  * Cleans the object that have internal lists without sending
4149  * ramrods. Should be run when interrutps are disabled.
4150  */
4151 static void
4152 bxe_squeeze_objects(struct bxe_softc *sc)
4153 {
4154     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4155     struct ecore_mcast_ramrod_params rparam = { NULL };
4156     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4157     int rc;
4158 
4159     /* Cleanup MACs' object first... */
4160 
4161     /* Wait for completion of requested */
4162     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4163     /* Perform a dry cleanup */
4164     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4165 
4166     /* Clean ETH primary MAC */
4167     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4168     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4169                              &ramrod_flags);
4170     if (rc != 0) {
4171         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4172     }
4173 
4174     /* Cleanup UC list */
4175     vlan_mac_flags = 0;
4176     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4177     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4178                              &ramrod_flags);
4179     if (rc != 0) {
4180         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4181     }
4182 
4183     /* Now clean mcast object... */
4184 
4185     rparam.mcast_obj = &sc->mcast_obj;
4186     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4187 
4188     /* Add a DEL command... */
4189     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4190     if (rc < 0) {
4191         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4192     }
4193 
4194     /* now wait until all pending commands are cleared */
4195 
4196     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4197     while (rc != 0) {
4198         if (rc < 0) {
4199             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4200             return;
4201         }
4202 
4203         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4204     }
4205 }
4206 
4207 /* stop the controller */
4208 static __noinline int
4209 bxe_nic_unload(struct bxe_softc *sc,
4210                uint32_t         unload_mode,
4211                uint8_t          keep_link)
4212 {
4213     uint8_t global = FALSE;
4214     uint32_t val;
4215     int i;
4216 
4217     BXE_CORE_LOCK_ASSERT(sc);
4218 
4219     if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4220 
4221     for (i = 0; i < sc->num_queues; i++) {
4222         struct bxe_fastpath *fp;
4223 
4224         fp = &sc->fp[i];
4225         BXE_FP_TX_LOCK(fp);
4226         BXE_FP_TX_UNLOCK(fp);
4227     }
4228 
4229     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4230 
4231     /* mark driver as unloaded in shmem2 */
4232     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4233         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4234         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4235                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4236     }
4237 
4238     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4239         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4240         /*
4241          * We can get here if the driver has been unloaded
4242          * during parity error recovery and is either waiting for a
4243          * leader to complete or for other functions to unload and
4244          * then ifconfig down has been issued. In this case we want to
4245          * unload and let other functions to complete a recovery
4246          * process.
4247          */
4248         sc->recovery_state = BXE_RECOVERY_DONE;
4249         sc->is_leader = 0;
4250         bxe_release_leader_lock(sc);
4251         mb();
4252 
4253         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4254         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4255             " state = 0x%x\n", sc->recovery_state, sc->state);
4256         return (-1);
4257     }
4258 
4259     /*
4260      * Nothing to do during unload if previous bxe_nic_load()
4261      * did not completed successfully - all resourses are released.
4262      */
4263     if ((sc->state == BXE_STATE_CLOSED) ||
4264         (sc->state == BXE_STATE_ERROR)) {
4265         return (0);
4266     }
4267 
4268     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4269     mb();
4270 
4271     /* stop tx */
4272     bxe_tx_disable(sc);
4273 
4274     sc->rx_mode = BXE_RX_MODE_NONE;
4275     /* XXX set rx mode ??? */
4276 
4277     if (IS_PF(sc) && !sc->grcdump_done) {
4278         /* set ALWAYS_ALIVE bit in shmem */
4279         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4280 
4281         bxe_drv_pulse(sc);
4282 
4283         bxe_stats_handle(sc, STATS_EVENT_STOP);
4284         bxe_save_statistics(sc);
4285     }
4286 
4287     /* wait till consumers catch up with producers in all queues */
4288     bxe_drain_tx_queues(sc);
4289 
4290     /* if VF indicate to PF this function is going down (PF will delete sp
4291      * elements and clear initializations
4292      */
4293     if (IS_VF(sc)) {
4294         ; /* bxe_vfpf_close_vf(sc); */
4295     } else if (unload_mode != UNLOAD_RECOVERY) {
4296         /* if this is a normal/close unload need to clean up chip */
4297         if (!sc->grcdump_done)
4298             bxe_chip_cleanup(sc, unload_mode, keep_link);
4299     } else {
4300         /* Send the UNLOAD_REQUEST to the MCP */
4301         bxe_send_unload_req(sc, unload_mode);
4302 
4303         /*
4304          * Prevent transactions to host from the functions on the
4305          * engine that doesn't reset global blocks in case of global
4306          * attention once gloabl blocks are reset and gates are opened
4307          * (the engine which leader will perform the recovery
4308          * last).
4309          */
4310         if (!CHIP_IS_E1x(sc)) {
4311             bxe_pf_disable(sc);
4312         }
4313 
4314         /* disable HW interrupts */
4315         bxe_int_disable_sync(sc, TRUE);
4316 
4317         /* detach interrupts */
4318         bxe_interrupt_detach(sc);
4319 
4320         /* Report UNLOAD_DONE to MCP */
4321         bxe_send_unload_done(sc, FALSE);
4322     }
4323 
4324     /*
4325      * At this stage no more interrupts will arrive so we may safely clean
4326      * the queue'able objects here in case they failed to get cleaned so far.
4327      */
4328     if (IS_PF(sc)) {
4329         bxe_squeeze_objects(sc);
4330     }
4331 
4332     /* There should be no more pending SP commands at this stage */
4333     sc->sp_state = 0;
4334 
4335     sc->port.pmf = 0;
4336 
4337     bxe_free_fp_buffers(sc);
4338 
4339     if (IS_PF(sc)) {
4340         bxe_free_mem(sc);
4341     }
4342 
4343     bxe_free_fw_stats_mem(sc);
4344 
4345     sc->state = BXE_STATE_CLOSED;
4346 
4347     /*
4348      * Check if there are pending parity attentions. If there are - set
4349      * RECOVERY_IN_PROGRESS.
4350      */
4351     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4352         bxe_set_reset_in_progress(sc);
4353 
4354         /* Set RESET_IS_GLOBAL if needed */
4355         if (global) {
4356             bxe_set_reset_global(sc);
4357         }
4358     }
4359 
4360     /*
4361      * The last driver must disable a "close the gate" if there is no
4362      * parity attention or "process kill" pending.
4363      */
4364     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4365         bxe_reset_is_done(sc, SC_PATH(sc))) {
4366         bxe_disable_close_the_gate(sc);
4367     }
4368 
4369     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4370 
4371     return (0);
4372 }
4373 
4374 /*
4375  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4376  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4377  */
4378 static int
4379 bxe_ifmedia_update(struct ifnet  *ifp)
4380 {
4381     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4382     struct ifmedia *ifm;
4383 
4384     ifm = &sc->ifmedia;
4385 
4386     /* We only support Ethernet media type. */
4387     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4388         return (EINVAL);
4389     }
4390 
4391     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4392     case IFM_AUTO:
4393          break;
4394     case IFM_10G_CX4:
4395     case IFM_10G_SR:
4396     case IFM_10G_T:
4397     case IFM_10G_TWINAX:
4398     default:
4399         /* We don't support changing the media type. */
4400         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4401               IFM_SUBTYPE(ifm->ifm_media));
4402         return (EINVAL);
4403     }
4404 
4405     return (0);
4406 }
4407 
4408 /*
4409  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4410  */
4411 static void
4412 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4413 {
4414     struct bxe_softc *sc = if_getsoftc(ifp);
4415 
4416     /* Report link down if the driver isn't running. */
4417     if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4418         ifmr->ifm_active |= IFM_NONE;
4419         return;
4420     }
4421 
4422     /* Setup the default interface info. */
4423     ifmr->ifm_status = IFM_AVALID;
4424     ifmr->ifm_active = IFM_ETHER;
4425 
4426     if (sc->link_vars.link_up) {
4427         ifmr->ifm_status |= IFM_ACTIVE;
4428     } else {
4429         ifmr->ifm_active |= IFM_NONE;
4430         return;
4431     }
4432 
4433     ifmr->ifm_active |= sc->media;
4434 
4435     if (sc->link_vars.duplex == DUPLEX_FULL) {
4436         ifmr->ifm_active |= IFM_FDX;
4437     } else {
4438         ifmr->ifm_active |= IFM_HDX;
4439     }
4440 }
4441 
4442 static void
4443 bxe_handle_chip_tq(void *context,
4444                    int  pending)
4445 {
4446     struct bxe_softc *sc = (struct bxe_softc *)context;
4447     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4448 
4449     switch (work)
4450     {
4451 
4452     case CHIP_TQ_REINIT:
4453         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4454             /* restart the interface */
4455             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4456             bxe_periodic_stop(sc);
4457             BXE_CORE_LOCK(sc);
4458             bxe_stop_locked(sc);
4459             bxe_init_locked(sc);
4460             BXE_CORE_UNLOCK(sc);
4461         }
4462         break;
4463 
4464     default:
4465         break;
4466     }
4467 }
4468 
4469 /*
4470  * Handles any IOCTL calls from the operating system.
4471  *
4472  * Returns:
4473  *   0 = Success, >0 Failure
4474  */
4475 static int
4476 bxe_ioctl(if_t ifp,
4477           u_long       command,
4478           caddr_t      data)
4479 {
4480     struct bxe_softc *sc = if_getsoftc(ifp);
4481     struct ifreq *ifr = (struct ifreq *)data;
4482     int mask = 0;
4483     int reinit = 0;
4484     int error = 0;
4485 
4486     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4487     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4488 
4489     switch (command)
4490     {
4491     case SIOCSIFMTU:
4492         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4493               ifr->ifr_mtu);
4494 
4495         if (sc->mtu == ifr->ifr_mtu) {
4496             /* nothing to change */
4497             break;
4498         }
4499 
4500         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4501             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4502                   ifr->ifr_mtu, mtu_min, mtu_max);
4503             error = EINVAL;
4504             break;
4505         }
4506 
4507         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4508                              (unsigned long)ifr->ifr_mtu);
4509 	/*
4510         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4511                               (unsigned long)ifr->ifr_mtu);
4512 	XXX - Not sure why it needs to be atomic
4513 	*/
4514 	if_setmtu(ifp, ifr->ifr_mtu);
4515         reinit = 1;
4516         break;
4517 
4518     case SIOCSIFFLAGS:
4519         /* toggle the interface state up or down */
4520         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4521 
4522 	BXE_CORE_LOCK(sc);
4523         /* check if the interface is up */
4524         if (if_getflags(ifp) & IFF_UP) {
4525             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4526                 /* set the receive mode flags */
4527                 bxe_set_rx_mode(sc);
4528             } else if(sc->state != BXE_STATE_DISABLED) {
4529 		bxe_init_locked(sc);
4530             }
4531         } else {
4532             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4533 		bxe_periodic_stop(sc);
4534 		bxe_stop_locked(sc);
4535             }
4536         }
4537 	BXE_CORE_UNLOCK(sc);
4538 
4539         break;
4540 
4541     case SIOCADDMULTI:
4542     case SIOCDELMULTI:
4543         /* add/delete multicast addresses */
4544         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4545 
4546         /* check if the interface is up */
4547         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4548             /* set the receive mode flags */
4549 	    BXE_CORE_LOCK(sc);
4550             bxe_set_rx_mode(sc);
4551 	    BXE_CORE_UNLOCK(sc);
4552         }
4553 
4554         break;
4555 
4556     case SIOCSIFCAP:
4557         /* find out which capabilities have changed */
4558         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4559 
4560         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4561               mask);
4562 
4563         /* toggle the LRO capabilites enable flag */
4564         if (mask & IFCAP_LRO) {
4565 	    if_togglecapenable(ifp, IFCAP_LRO);
4566             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4567                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4568             reinit = 1;
4569         }
4570 
4571         /* toggle the TXCSUM checksum capabilites enable flag */
4572         if (mask & IFCAP_TXCSUM) {
4573 	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4574             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4575                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4576             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4577                 if_sethwassistbits(ifp, (CSUM_IP      |
4578                                     CSUM_TCP      |
4579                                     CSUM_UDP      |
4580                                     CSUM_TSO      |
4581                                     CSUM_TCP_IPV6 |
4582                                     CSUM_UDP_IPV6), 0);
4583             } else {
4584 		if_clearhwassist(ifp); /* XXX */
4585             }
4586         }
4587 
4588         /* toggle the RXCSUM checksum capabilities enable flag */
4589         if (mask & IFCAP_RXCSUM) {
4590 	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4591             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4592                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4593             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4594                 if_sethwassistbits(ifp, (CSUM_IP      |
4595                                     CSUM_TCP      |
4596                                     CSUM_UDP      |
4597                                     CSUM_TSO      |
4598                                     CSUM_TCP_IPV6 |
4599                                     CSUM_UDP_IPV6), 0);
4600             } else {
4601 		if_clearhwassist(ifp); /* XXX */
4602             }
4603         }
4604 
4605         /* toggle TSO4 capabilities enabled flag */
4606         if (mask & IFCAP_TSO4) {
4607             if_togglecapenable(ifp, IFCAP_TSO4);
4608             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4609                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4610         }
4611 
4612         /* toggle TSO6 capabilities enabled flag */
4613         if (mask & IFCAP_TSO6) {
4614 	    if_togglecapenable(ifp, IFCAP_TSO6);
4615             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4616                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4617         }
4618 
4619         /* toggle VLAN_HWTSO capabilities enabled flag */
4620         if (mask & IFCAP_VLAN_HWTSO) {
4621 
4622 	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4623             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4624                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4625         }
4626 
4627         /* toggle VLAN_HWCSUM capabilities enabled flag */
4628         if (mask & IFCAP_VLAN_HWCSUM) {
4629             /* XXX investigate this... */
4630             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4631             error = EINVAL;
4632         }
4633 
4634         /* toggle VLAN_MTU capabilities enable flag */
4635         if (mask & IFCAP_VLAN_MTU) {
4636             /* XXX investigate this... */
4637             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4638             error = EINVAL;
4639         }
4640 
4641         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4642         if (mask & IFCAP_VLAN_HWTAGGING) {
4643             /* XXX investigate this... */
4644             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4645             error = EINVAL;
4646         }
4647 
4648         /* toggle VLAN_HWFILTER capabilities enabled flag */
4649         if (mask & IFCAP_VLAN_HWFILTER) {
4650             /* XXX investigate this... */
4651             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4652             error = EINVAL;
4653         }
4654 
4655         /* XXX not yet...
4656          * IFCAP_WOL_MAGIC
4657          */
4658 
4659         break;
4660 
4661     case SIOCSIFMEDIA:
4662     case SIOCGIFMEDIA:
4663         /* set/get interface media */
4664         BLOGD(sc, DBG_IOCTL,
4665               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4666               (command & 0xff));
4667         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4668         break;
4669 
4670     default:
4671         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4672               (command & 0xff));
4673         error = ether_ioctl(ifp, command, data);
4674         break;
4675     }
4676 
4677     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4678         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4679               "Re-initializing hardware from IOCTL change\n");
4680 	bxe_periodic_stop(sc);
4681 	BXE_CORE_LOCK(sc);
4682 	bxe_stop_locked(sc);
4683 	bxe_init_locked(sc);
4684 	BXE_CORE_UNLOCK(sc);
4685     }
4686 
4687     return (error);
4688 }
4689 
4690 static __noinline void
4691 bxe_dump_mbuf(struct bxe_softc *sc,
4692               struct mbuf      *m,
4693               uint8_t          contents)
4694 {
4695     char * type;
4696     int i = 0;
4697 
4698     if (!(sc->debug & DBG_MBUF)) {
4699         return;
4700     }
4701 
4702     if (m == NULL) {
4703         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4704         return;
4705     }
4706 
4707     while (m) {
4708 
4709 #if __FreeBSD_version >= 1000000
4710         BLOGD(sc, DBG_MBUF,
4711               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4712               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4713 
4714         if (m->m_flags & M_PKTHDR) {
4715              BLOGD(sc, DBG_MBUF,
4716                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4717                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4718                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4719         }
4720 #else
4721         BLOGD(sc, DBG_MBUF,
4722               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4723               i, m, m->m_len, m->m_flags,
4724               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4725 
4726         if (m->m_flags & M_PKTHDR) {
4727              BLOGD(sc, DBG_MBUF,
4728                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4729                    i, m->m_pkthdr.len, m->m_flags,
4730                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4731                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4732                    "\22M_PROMISC\23M_NOFREE",
4733                    (int)m->m_pkthdr.csum_flags,
4734                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4735                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4736                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4737                    "\14CSUM_PSEUDO_HDR");
4738         }
4739 #endif /* #if __FreeBSD_version >= 1000000 */
4740 
4741         if (m->m_flags & M_EXT) {
4742             switch (m->m_ext.ext_type) {
4743             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4744             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4745             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4746             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4747             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4748             case EXT_PACKET:     type = "EXT_PACKET";     break;
4749             case EXT_MBUF:       type = "EXT_MBUF";       break;
4750             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4751             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4752             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4753             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4754             default:             type = "UNKNOWN";        break;
4755             }
4756 
4757             BLOGD(sc, DBG_MBUF,
4758                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4759                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4760         }
4761 
4762         if (contents) {
4763             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4764         }
4765 
4766         m = m->m_next;
4767         i++;
4768     }
4769 }
4770 
4771 /*
4772  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4773  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4774  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4775  * The headers comes in a separate bd in FreeBSD so 13-3=10.
4776  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4777  */
4778 static int
4779 bxe_chktso_window(struct bxe_softc  *sc,
4780                   int               nsegs,
4781                   bus_dma_segment_t *segs,
4782                   struct mbuf       *m)
4783 {
4784     uint32_t num_wnds, wnd_size, wnd_sum;
4785     int32_t frag_idx, wnd_idx;
4786     unsigned short lso_mss;
4787     int defrag;
4788 
4789     defrag = 0;
4790     wnd_sum = 0;
4791     wnd_size = 10;
4792     num_wnds = nsegs - wnd_size;
4793     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4794 
4795     /*
4796      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4797      * first window sum of data while skipping the first assuming it is the
4798      * header in FreeBSD.
4799      */
4800     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4801         wnd_sum += htole16(segs[frag_idx].ds_len);
4802     }
4803 
4804     /* check the first 10 bd window size */
4805     if (wnd_sum < lso_mss) {
4806         return (1);
4807     }
4808 
4809     /* run through the windows */
4810     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4811         /* subtract the first mbuf->m_len of the last wndw(-header) */
4812         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4813         /* add the next mbuf len to the len of our new window */
4814         wnd_sum += htole16(segs[frag_idx].ds_len);
4815         if (wnd_sum < lso_mss) {
4816             return (1);
4817         }
4818     }
4819 
4820     return (0);
4821 }
4822 
4823 static uint8_t
4824 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4825                     struct mbuf         *m,
4826                     uint32_t            *parsing_data)
4827 {
4828     struct ether_vlan_header *eh = NULL;
4829     struct ip *ip4 = NULL;
4830     struct ip6_hdr *ip6 = NULL;
4831     caddr_t ip = NULL;
4832     struct tcphdr *th = NULL;
4833     int e_hlen, ip_hlen, l4_off;
4834     uint16_t proto;
4835 
4836     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4837         /* no L4 checksum offload needed */
4838         return (0);
4839     }
4840 
4841     /* get the Ethernet header */
4842     eh = mtod(m, struct ether_vlan_header *);
4843 
4844     /* handle VLAN encapsulation if present */
4845     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4846         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4847         proto  = ntohs(eh->evl_proto);
4848     } else {
4849         e_hlen = ETHER_HDR_LEN;
4850         proto  = ntohs(eh->evl_encap_proto);
4851     }
4852 
4853     switch (proto) {
4854     case ETHERTYPE_IP:
4855         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4856         ip4 = (m->m_len < sizeof(struct ip)) ?
4857                   (struct ip *)m->m_next->m_data :
4858                   (struct ip *)(m->m_data + e_hlen);
4859         /* ip_hl is number of 32-bit words */
4860         ip_hlen = (ip4->ip_hl << 2);
4861         ip = (caddr_t)ip4;
4862         break;
4863     case ETHERTYPE_IPV6:
4864         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4865         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4866                   (struct ip6_hdr *)m->m_next->m_data :
4867                   (struct ip6_hdr *)(m->m_data + e_hlen);
4868         /* XXX cannot support offload with IPv6 extensions */
4869         ip_hlen = sizeof(struct ip6_hdr);
4870         ip = (caddr_t)ip6;
4871         break;
4872     default:
4873         /* We can't offload in this case... */
4874         /* XXX error stat ??? */
4875         return (0);
4876     }
4877 
4878     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4879     l4_off = (e_hlen + ip_hlen);
4880 
4881     *parsing_data |=
4882         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4883          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4884 
4885     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4886                                   CSUM_TSO |
4887                                   CSUM_TCP_IPV6)) {
4888         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4889         th = (struct tcphdr *)(ip + ip_hlen);
4890         /* th_off is number of 32-bit words */
4891         *parsing_data |= ((th->th_off <<
4892                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4893                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4894         return (l4_off + (th->th_off << 2)); /* entire header length */
4895     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4896                                          CSUM_UDP_IPV6)) {
4897         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4898         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4899     } else {
4900         /* XXX error stat ??? */
4901         return (0);
4902     }
4903 }
4904 
4905 static uint8_t
4906 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4907                  struct mbuf                *m,
4908                  struct eth_tx_parse_bd_e1x *pbd)
4909 {
4910     struct ether_vlan_header *eh = NULL;
4911     struct ip *ip4 = NULL;
4912     struct ip6_hdr *ip6 = NULL;
4913     caddr_t ip = NULL;
4914     struct tcphdr *th = NULL;
4915     struct udphdr *uh = NULL;
4916     int e_hlen, ip_hlen;
4917     uint16_t proto;
4918     uint8_t hlen;
4919     uint16_t tmp_csum;
4920     uint32_t *tmp_uh;
4921 
4922     /* get the Ethernet header */
4923     eh = mtod(m, struct ether_vlan_header *);
4924 
4925     /* handle VLAN encapsulation if present */
4926     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4927         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4928         proto  = ntohs(eh->evl_proto);
4929     } else {
4930         e_hlen = ETHER_HDR_LEN;
4931         proto  = ntohs(eh->evl_encap_proto);
4932     }
4933 
4934     switch (proto) {
4935     case ETHERTYPE_IP:
4936         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4937         ip4 = (m->m_len < sizeof(struct ip)) ?
4938                   (struct ip *)m->m_next->m_data :
4939                   (struct ip *)(m->m_data + e_hlen);
4940         /* ip_hl is number of 32-bit words */
4941         ip_hlen = (ip4->ip_hl << 1);
4942         ip = (caddr_t)ip4;
4943         break;
4944     case ETHERTYPE_IPV6:
4945         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4946         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4947                   (struct ip6_hdr *)m->m_next->m_data :
4948                   (struct ip6_hdr *)(m->m_data + e_hlen);
4949         /* XXX cannot support offload with IPv6 extensions */
4950         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4951         ip = (caddr_t)ip6;
4952         break;
4953     default:
4954         /* We can't offload in this case... */
4955         /* XXX error stat ??? */
4956         return (0);
4957     }
4958 
4959     hlen = (e_hlen >> 1);
4960 
4961     /* note that rest of global_data is indirectly zeroed here */
4962     if (m->m_flags & M_VLANTAG) {
4963         pbd->global_data =
4964             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4965     } else {
4966         pbd->global_data = htole16(hlen);
4967     }
4968 
4969     pbd->ip_hlen_w = ip_hlen;
4970 
4971     hlen += pbd->ip_hlen_w;
4972 
4973     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4974 
4975     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4976                                   CSUM_TSO |
4977                                   CSUM_TCP_IPV6)) {
4978         th = (struct tcphdr *)(ip + (ip_hlen << 1));
4979         /* th_off is number of 32-bit words */
4980         hlen += (uint16_t)(th->th_off << 1);
4981     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4982                                          CSUM_UDP_IPV6)) {
4983         uh = (struct udphdr *)(ip + (ip_hlen << 1));
4984         hlen += (sizeof(struct udphdr) / 2);
4985     } else {
4986         /* valid case as only CSUM_IP was set */
4987         return (0);
4988     }
4989 
4990     pbd->total_hlen_w = htole16(hlen);
4991 
4992     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4993                                   CSUM_TSO |
4994                                   CSUM_TCP_IPV6)) {
4995         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4996         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
4997     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4998                                          CSUM_UDP_IPV6)) {
4999         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5000 
5001         /*
5002          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5003          * checksums and does not know anything about the UDP header and where
5004          * the checksum field is located. It only knows about TCP. Therefore
5005          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5006          * offload. Since the checksum field offset for TCP is 16 bytes and
5007          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5008          * bytes less than the start of the UDP header. This allows the
5009          * hardware to write the checksum in the correct spot. But the
5010          * hardware will compute a checksum which includes the last 10 bytes
5011          * of the IP header. To correct this we tweak the stack computed
5012          * pseudo checksum by folding in the calculation of the inverse
5013          * checksum for those final 10 bytes of the IP header. This allows
5014          * the correct checksum to be computed by the hardware.
5015          */
5016 
5017         /* set pointer 10 bytes before UDP header */
5018         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5019 
5020         /* calculate a pseudo header checksum over the first 10 bytes */
5021         tmp_csum = in_pseudo(*tmp_uh,
5022                              *(tmp_uh + 1),
5023                              *(uint16_t *)(tmp_uh + 2));
5024 
5025         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5026     }
5027 
5028     return (hlen * 2); /* entire header length, number of bytes */
5029 }
5030 
5031 static void
5032 bxe_set_pbd_lso_e2(struct mbuf *m,
5033                    uint32_t    *parsing_data)
5034 {
5035     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5036                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5037                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5038 
5039     /* XXX test for IPv6 with extension header... */
5040 }
5041 
5042 static void
5043 bxe_set_pbd_lso(struct mbuf                *m,
5044                 struct eth_tx_parse_bd_e1x *pbd)
5045 {
5046     struct ether_vlan_header *eh = NULL;
5047     struct ip *ip = NULL;
5048     struct tcphdr *th = NULL;
5049     int e_hlen;
5050 
5051     /* get the Ethernet header */
5052     eh = mtod(m, struct ether_vlan_header *);
5053 
5054     /* handle VLAN encapsulation if present */
5055     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5056                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5057 
5058     /* get the IP and TCP header, with LSO entire header in first mbuf */
5059     /* XXX assuming IPv4 */
5060     ip = (struct ip *)(m->m_data + e_hlen);
5061     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5062 
5063     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5064     pbd->tcp_send_seq = ntohl(th->th_seq);
5065     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5066 
5067 #if 1
5068         /* XXX IPv4 */
5069         pbd->ip_id = ntohs(ip->ip_id);
5070         pbd->tcp_pseudo_csum =
5071             ntohs(in_pseudo(ip->ip_src.s_addr,
5072                             ip->ip_dst.s_addr,
5073                             htons(IPPROTO_TCP)));
5074 #else
5075         /* XXX IPv6 */
5076         pbd->tcp_pseudo_csum =
5077             ntohs(in_pseudo(&ip6->ip6_src,
5078                             &ip6->ip6_dst,
5079                             htons(IPPROTO_TCP)));
5080 #endif
5081 
5082     pbd->global_data |=
5083         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5084 }
5085 
5086 /*
5087  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5088  * visible to the controller.
5089  *
5090  * If an mbuf is submitted to this routine and cannot be given to the
5091  * controller (e.g. it has too many fragments) then the function may free
5092  * the mbuf and return to the caller.
5093  *
5094  * Returns:
5095  *   0 = Success, !0 = Failure
5096  *   Note the side effect that an mbuf may be freed if it causes a problem.
5097  */
5098 static int
5099 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5100 {
5101     bus_dma_segment_t segs[32];
5102     struct mbuf *m0;
5103     struct bxe_sw_tx_bd *tx_buf;
5104     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5105     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5106     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5107     struct eth_tx_bd *tx_data_bd;
5108     struct eth_tx_bd *tx_total_pkt_size_bd;
5109     struct eth_tx_start_bd *tx_start_bd;
5110     uint16_t bd_prod, pkt_prod, total_pkt_size;
5111     uint8_t mac_type;
5112     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5113     struct bxe_softc *sc;
5114     uint16_t tx_bd_avail;
5115     struct ether_vlan_header *eh;
5116     uint32_t pbd_e2_parsing_data = 0;
5117     uint8_t hlen = 0;
5118     int tmp_bd;
5119     int i;
5120 
5121     sc = fp->sc;
5122 
5123 #if __FreeBSD_version >= 800000
5124     M_ASSERTPKTHDR(*m_head);
5125 #endif /* #if __FreeBSD_version >= 800000 */
5126 
5127     m0 = *m_head;
5128     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5129     tx_start_bd = NULL;
5130     tx_data_bd = NULL;
5131     tx_total_pkt_size_bd = NULL;
5132 
5133     /* get the H/W pointer for packets and BDs */
5134     pkt_prod = fp->tx_pkt_prod;
5135     bd_prod = fp->tx_bd_prod;
5136 
5137     mac_type = UNICAST_ADDRESS;
5138 
5139     /* map the mbuf into the next open DMAable memory */
5140     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5141     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5142                                     tx_buf->m_map, m0,
5143                                     segs, &nsegs, BUS_DMA_NOWAIT);
5144 
5145     /* mapping errors */
5146     if(__predict_false(error != 0)) {
5147         fp->eth_q_stats.tx_dma_mapping_failure++;
5148         if (error == ENOMEM) {
5149             /* resource issue, try again later */
5150             rc = ENOMEM;
5151         } else if (error == EFBIG) {
5152             /* possibly recoverable with defragmentation */
5153             fp->eth_q_stats.mbuf_defrag_attempts++;
5154             m0 = m_defrag(*m_head, M_NOWAIT);
5155             if (m0 == NULL) {
5156                 fp->eth_q_stats.mbuf_defrag_failures++;
5157                 rc = ENOBUFS;
5158             } else {
5159                 /* defrag successful, try mapping again */
5160                 *m_head = m0;
5161                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5162                                                 tx_buf->m_map, m0,
5163                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5164                 if (error) {
5165                     fp->eth_q_stats.tx_dma_mapping_failure++;
5166                     rc = error;
5167                 }
5168             }
5169         } else {
5170             /* unknown, unrecoverable mapping error */
5171             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5172             bxe_dump_mbuf(sc, m0, FALSE);
5173             rc = error;
5174         }
5175 
5176         goto bxe_tx_encap_continue;
5177     }
5178 
5179     tx_bd_avail = bxe_tx_avail(sc, fp);
5180 
5181     /* make sure there is enough room in the send queue */
5182     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5183         /* Recoverable, try again later. */
5184         fp->eth_q_stats.tx_hw_queue_full++;
5185         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5186         rc = ENOMEM;
5187         goto bxe_tx_encap_continue;
5188     }
5189 
5190     /* capture the current H/W TX chain high watermark */
5191     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5192                         (TX_BD_USABLE - tx_bd_avail))) {
5193         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5194     }
5195 
5196     /* make sure it fits in the packet window */
5197     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5198         /*
5199          * The mbuf may be to big for the controller to handle. If the frame
5200          * is a TSO frame we'll need to do an additional check.
5201          */
5202         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5203             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5204                 goto bxe_tx_encap_continue; /* OK to send */
5205             } else {
5206                 fp->eth_q_stats.tx_window_violation_tso++;
5207             }
5208         } else {
5209             fp->eth_q_stats.tx_window_violation_std++;
5210         }
5211 
5212         /* lets try to defragment this mbuf and remap it */
5213         fp->eth_q_stats.mbuf_defrag_attempts++;
5214         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5215 
5216         m0 = m_defrag(*m_head, M_NOWAIT);
5217         if (m0 == NULL) {
5218             fp->eth_q_stats.mbuf_defrag_failures++;
5219             /* Ugh, just drop the frame... :( */
5220             rc = ENOBUFS;
5221         } else {
5222             /* defrag successful, try mapping again */
5223             *m_head = m0;
5224             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5225                                             tx_buf->m_map, m0,
5226                                             segs, &nsegs, BUS_DMA_NOWAIT);
5227             if (error) {
5228                 fp->eth_q_stats.tx_dma_mapping_failure++;
5229                 /* No sense in trying to defrag/copy chain, drop it. :( */
5230                 rc = error;
5231             }
5232             else {
5233                 /* if the chain is still too long then drop it */
5234                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5235                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5236                     rc = ENODEV;
5237                 }
5238             }
5239         }
5240     }
5241 
5242 bxe_tx_encap_continue:
5243 
5244     /* Check for errors */
5245     if (rc) {
5246         if (rc == ENOMEM) {
5247             /* recoverable try again later  */
5248         } else {
5249             fp->eth_q_stats.tx_soft_errors++;
5250             fp->eth_q_stats.mbuf_alloc_tx--;
5251             m_freem(*m_head);
5252             *m_head = NULL;
5253         }
5254 
5255         return (rc);
5256     }
5257 
5258     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5259     if (m0->m_flags & M_BCAST) {
5260         mac_type = BROADCAST_ADDRESS;
5261     } else if (m0->m_flags & M_MCAST) {
5262         mac_type = MULTICAST_ADDRESS;
5263     }
5264 
5265     /* store the mbuf into the mbuf ring */
5266     tx_buf->m        = m0;
5267     tx_buf->first_bd = fp->tx_bd_prod;
5268     tx_buf->flags    = 0;
5269 
5270     /* prepare the first transmit (start) BD for the mbuf */
5271     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5272 
5273     BLOGD(sc, DBG_TX,
5274           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5275           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5276 
5277     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5278     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5279     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5280     total_pkt_size += tx_start_bd->nbytes;
5281     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5282 
5283     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5284 
5285     /* all frames have at least Start BD + Parsing BD */
5286     nbds = nsegs + 1;
5287     tx_start_bd->nbd = htole16(nbds);
5288 
5289     if (m0->m_flags & M_VLANTAG) {
5290         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5291         tx_start_bd->bd_flags.as_bitfield |=
5292             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5293     } else {
5294         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5295         if (IS_VF(sc)) {
5296             /* map ethernet header to find type and header length */
5297             eh = mtod(m0, struct ether_vlan_header *);
5298             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5299         } else {
5300             /* used by FW for packet accounting */
5301             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5302         }
5303     }
5304 
5305     /*
5306      * add a parsing BD from the chain. The parsing BD is always added
5307      * though it is only used for TSO and chksum
5308      */
5309     bd_prod = TX_BD_NEXT(bd_prod);
5310 
5311     if (m0->m_pkthdr.csum_flags) {
5312         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5313             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5314             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5315         }
5316 
5317         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5318             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5319                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5320         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5321             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5322                                                   ETH_TX_BD_FLAGS_IS_UDP |
5323                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5324         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5325                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5326             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5327         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5328             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5329                                                   ETH_TX_BD_FLAGS_IS_UDP);
5330         }
5331     }
5332 
5333     if (!CHIP_IS_E1x(sc)) {
5334         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5335         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5336 
5337         if (m0->m_pkthdr.csum_flags) {
5338             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5339         }
5340 
5341         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5342                  mac_type);
5343     } else {
5344         uint16_t global_data = 0;
5345 
5346         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5347         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5348 
5349         if (m0->m_pkthdr.csum_flags) {
5350             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5351         }
5352 
5353         SET_FLAG(global_data,
5354                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5355         pbd_e1x->global_data |= htole16(global_data);
5356     }
5357 
5358     /* setup the parsing BD with TSO specific info */
5359     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5360         fp->eth_q_stats.tx_ofld_frames_lso++;
5361         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5362 
5363         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5364             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5365 
5366             /* split the first BD into header/data making the fw job easy */
5367             nbds++;
5368             tx_start_bd->nbd = htole16(nbds);
5369             tx_start_bd->nbytes = htole16(hlen);
5370 
5371             bd_prod = TX_BD_NEXT(bd_prod);
5372 
5373             /* new transmit BD after the tx_parse_bd */
5374             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5375             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5376             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5377             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5378             if (tx_total_pkt_size_bd == NULL) {
5379                 tx_total_pkt_size_bd = tx_data_bd;
5380             }
5381 
5382             BLOGD(sc, DBG_TX,
5383                   "TSO split header size is %d (%x:%x) nbds %d\n",
5384                   le16toh(tx_start_bd->nbytes),
5385                   le32toh(tx_start_bd->addr_hi),
5386                   le32toh(tx_start_bd->addr_lo),
5387                   nbds);
5388         }
5389 
5390         if (!CHIP_IS_E1x(sc)) {
5391             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5392         } else {
5393             bxe_set_pbd_lso(m0, pbd_e1x);
5394         }
5395     }
5396 
5397     if (pbd_e2_parsing_data) {
5398         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5399     }
5400 
5401     /* prepare remaining BDs, start tx bd contains first seg/frag */
5402     for (i = 1; i < nsegs ; i++) {
5403         bd_prod = TX_BD_NEXT(bd_prod);
5404         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5405         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5406         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5407         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5408         if (tx_total_pkt_size_bd == NULL) {
5409             tx_total_pkt_size_bd = tx_data_bd;
5410         }
5411         total_pkt_size += tx_data_bd->nbytes;
5412     }
5413 
5414     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5415 
5416     if (tx_total_pkt_size_bd != NULL) {
5417         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5418     }
5419 
5420     if (__predict_false(sc->debug & DBG_TX)) {
5421         tmp_bd = tx_buf->first_bd;
5422         for (i = 0; i < nbds; i++)
5423         {
5424             if (i == 0) {
5425                 BLOGD(sc, DBG_TX,
5426                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5427                       "bd_flags=0x%x hdr_nbds=%d\n",
5428                       tx_start_bd,
5429                       tmp_bd,
5430                       le16toh(tx_start_bd->nbd),
5431                       le16toh(tx_start_bd->vlan_or_ethertype),
5432                       tx_start_bd->bd_flags.as_bitfield,
5433                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5434             } else if (i == 1) {
5435                 if (pbd_e1x) {
5436                     BLOGD(sc, DBG_TX,
5437                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5438                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5439                           "tcp_seq=%u total_hlen_w=%u\n",
5440                           pbd_e1x,
5441                           tmp_bd,
5442                           pbd_e1x->global_data,
5443                           pbd_e1x->ip_hlen_w,
5444                           pbd_e1x->ip_id,
5445                           pbd_e1x->lso_mss,
5446                           pbd_e1x->tcp_flags,
5447                           pbd_e1x->tcp_pseudo_csum,
5448                           pbd_e1x->tcp_send_seq,
5449                           le16toh(pbd_e1x->total_hlen_w));
5450                 } else { /* if (pbd_e2) */
5451                     BLOGD(sc, DBG_TX,
5452                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5453                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5454                           pbd_e2,
5455                           tmp_bd,
5456                           pbd_e2->data.mac_addr.dst_hi,
5457                           pbd_e2->data.mac_addr.dst_mid,
5458                           pbd_e2->data.mac_addr.dst_lo,
5459                           pbd_e2->data.mac_addr.src_hi,
5460                           pbd_e2->data.mac_addr.src_mid,
5461                           pbd_e2->data.mac_addr.src_lo,
5462                           pbd_e2->parsing_data);
5463                 }
5464             }
5465 
5466             if (i != 1) { /* skip parse db as it doesn't hold data */
5467                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5468                 BLOGD(sc, DBG_TX,
5469                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5470                       tx_data_bd,
5471                       tmp_bd,
5472                       le16toh(tx_data_bd->nbytes),
5473                       le32toh(tx_data_bd->addr_hi),
5474                       le32toh(tx_data_bd->addr_lo));
5475             }
5476 
5477             tmp_bd = TX_BD_NEXT(tmp_bd);
5478         }
5479     }
5480 
5481     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5482 
5483     /* update TX BD producer index value for next TX */
5484     bd_prod = TX_BD_NEXT(bd_prod);
5485 
5486     /*
5487      * If the chain of tx_bd's describing this frame is adjacent to or spans
5488      * an eth_tx_next_bd element then we need to increment the nbds value.
5489      */
5490     if (TX_BD_IDX(bd_prod) < nbds) {
5491         nbds++;
5492     }
5493 
5494     /* don't allow reordering of writes for nbd and packets */
5495     mb();
5496 
5497     fp->tx_db.data.prod += nbds;
5498 
5499     /* producer points to the next free tx_bd at this point */
5500     fp->tx_pkt_prod++;
5501     fp->tx_bd_prod = bd_prod;
5502 
5503     DOORBELL(sc, fp->index, fp->tx_db.raw);
5504 
5505     fp->eth_q_stats.tx_pkts++;
5506 
5507     /* Prevent speculative reads from getting ahead of the status block. */
5508     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5509                       0, 0, BUS_SPACE_BARRIER_READ);
5510 
5511     /* Prevent speculative reads from getting ahead of the doorbell. */
5512     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5513                       0, 0, BUS_SPACE_BARRIER_READ);
5514 
5515     return (0);
5516 }
5517 
5518 static void
5519 bxe_tx_start_locked(struct bxe_softc *sc,
5520                     if_t ifp,
5521                     struct bxe_fastpath *fp)
5522 {
5523     struct mbuf *m = NULL;
5524     int tx_count = 0;
5525     uint16_t tx_bd_avail;
5526 
5527     BXE_FP_TX_LOCK_ASSERT(fp);
5528 
5529     /* keep adding entries while there are frames to send */
5530     while (!if_sendq_empty(ifp)) {
5531 
5532         /*
5533          * check for any frames to send
5534          * dequeue can still be NULL even if queue is not empty
5535          */
5536         m = if_dequeue(ifp);
5537         if (__predict_false(m == NULL)) {
5538             break;
5539         }
5540 
5541         /* the mbuf now belongs to us */
5542         fp->eth_q_stats.mbuf_alloc_tx++;
5543 
5544         /*
5545          * Put the frame into the transmit ring. If we don't have room,
5546          * place the mbuf back at the head of the TX queue, set the
5547          * OACTIVE flag, and wait for the NIC to drain the chain.
5548          */
5549         if (__predict_false(bxe_tx_encap(fp, &m))) {
5550             fp->eth_q_stats.tx_encap_failures++;
5551             if (m != NULL) {
5552                 /* mark the TX queue as full and return the frame */
5553                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5554 		if_sendq_prepend(ifp, m);
5555                 fp->eth_q_stats.mbuf_alloc_tx--;
5556                 fp->eth_q_stats.tx_queue_xoff++;
5557             }
5558 
5559             /* stop looking for more work */
5560             break;
5561         }
5562 
5563         /* the frame was enqueued successfully */
5564         tx_count++;
5565 
5566         /* send a copy of the frame to any BPF listeners. */
5567         if_etherbpfmtap(ifp, m);
5568 
5569         tx_bd_avail = bxe_tx_avail(sc, fp);
5570 
5571         /* handle any completions if we're running low */
5572         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5573             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5574             bxe_txeof(sc, fp);
5575             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5576                 break;
5577             }
5578         }
5579     }
5580 
5581     /* all TX packets were dequeued and/or the tx ring is full */
5582     if (tx_count > 0) {
5583         /* reset the TX watchdog timeout timer */
5584         fp->watchdog_timer = BXE_TX_TIMEOUT;
5585     }
5586 }
5587 
5588 /* Legacy (non-RSS) dispatch routine */
5589 static void
5590 bxe_tx_start(if_t ifp)
5591 {
5592     struct bxe_softc *sc;
5593     struct bxe_fastpath *fp;
5594 
5595     sc = if_getsoftc(ifp);
5596 
5597     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5598         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5599         return;
5600     }
5601 
5602     if (!sc->link_vars.link_up) {
5603         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5604         return;
5605     }
5606 
5607     fp = &sc->fp[0];
5608 
5609     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5610         fp->eth_q_stats.tx_queue_full_return++;
5611         return;
5612     }
5613 
5614     BXE_FP_TX_LOCK(fp);
5615     bxe_tx_start_locked(sc, ifp, fp);
5616     BXE_FP_TX_UNLOCK(fp);
5617 }
5618 
5619 #if __FreeBSD_version >= 800000
5620 
5621 static int
5622 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5623                        if_t                ifp,
5624                        struct bxe_fastpath *fp,
5625                        struct mbuf         *m)
5626 {
5627     struct buf_ring *tx_br = fp->tx_br;
5628     struct mbuf *next;
5629     int depth, rc, tx_count;
5630     uint16_t tx_bd_avail;
5631 
5632     rc = tx_count = 0;
5633 
5634     BXE_FP_TX_LOCK_ASSERT(fp);
5635 
5636     if (!tx_br) {
5637         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5638         return (EINVAL);
5639     }
5640 
5641     if (m != NULL) {
5642         rc = drbr_enqueue(ifp, tx_br, m);
5643         if (rc != 0) {
5644             fp->eth_q_stats.tx_soft_errors++;
5645             goto bxe_tx_mq_start_locked_exit;
5646         }
5647     }
5648 
5649     if (!sc->link_vars.link_up ||
5650         (if_getdrvflags(ifp) &
5651         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5652         fp->eth_q_stats.tx_request_link_down_failures++;
5653         goto bxe_tx_mq_start_locked_exit;
5654     }
5655 
5656     /* fetch the depth of the driver queue */
5657     depth = drbr_inuse_drv(ifp, tx_br);
5658     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5659         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5660     }
5661 
5662     /* keep adding entries while there are frames to send */
5663     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5664         /* handle any completions if we're running low */
5665         tx_bd_avail = bxe_tx_avail(sc, fp);
5666         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5667             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5668             bxe_txeof(sc, fp);
5669             tx_bd_avail = bxe_tx_avail(sc, fp);
5670             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5671                 fp->eth_q_stats.bd_avail_too_less_failures++;
5672                 m_freem(next);
5673                 drbr_advance(ifp, tx_br);
5674                 rc = ENOBUFS;
5675                 break;
5676             }
5677         }
5678 
5679         /* the mbuf now belongs to us */
5680         fp->eth_q_stats.mbuf_alloc_tx++;
5681 
5682         /*
5683          * Put the frame into the transmit ring. If we don't have room,
5684          * place the mbuf back at the head of the TX queue, set the
5685          * OACTIVE flag, and wait for the NIC to drain the chain.
5686          */
5687         rc = bxe_tx_encap(fp, &next);
5688         if (__predict_false(rc != 0)) {
5689             fp->eth_q_stats.tx_encap_failures++;
5690             if (next != NULL) {
5691                 /* mark the TX queue as full and save the frame */
5692                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5693                 drbr_putback(ifp, tx_br, next);
5694                 fp->eth_q_stats.mbuf_alloc_tx--;
5695                 fp->eth_q_stats.tx_frames_deferred++;
5696             } else
5697                 drbr_advance(ifp, tx_br);
5698 
5699             /* stop looking for more work */
5700             break;
5701         }
5702 
5703         /* the transmit frame was enqueued successfully */
5704         tx_count++;
5705 
5706         /* send a copy of the frame to any BPF listeners */
5707         BPF_MTAP(ifp, next);
5708 
5709         drbr_advance(ifp, tx_br);
5710     }
5711 
5712     /* all TX packets were dequeued and/or the tx ring is full */
5713     if (tx_count > 0) {
5714         /* reset the TX watchdog timeout timer */
5715         fp->watchdog_timer = BXE_TX_TIMEOUT;
5716     }
5717 
5718 bxe_tx_mq_start_locked_exit:
5719     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5720     if (!drbr_empty(ifp, tx_br)) {
5721         fp->eth_q_stats.tx_mq_not_empty++;
5722         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5723     }
5724 
5725     return (rc);
5726 }
5727 
5728 static void
5729 bxe_tx_mq_start_deferred(void *arg,
5730                          int pending)
5731 {
5732     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5733     struct bxe_softc *sc = fp->sc;
5734 #if __FreeBSD_version >= 800000
5735     if_t ifp = sc->ifp;
5736 #else
5737     struct ifnet *ifp = sc->ifnet;
5738 #endif /* #if __FreeBSD_version >= 800000 */
5739 
5740     BXE_FP_TX_LOCK(fp);
5741     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5742     BXE_FP_TX_UNLOCK(fp);
5743 }
5744 
5745 /* Multiqueue (TSS) dispatch routine. */
5746 static int
5747 bxe_tx_mq_start(struct ifnet *ifp,
5748                 struct mbuf  *m)
5749 {
5750     struct bxe_softc *sc = if_getsoftc(ifp);
5751     struct bxe_fastpath *fp;
5752     int fp_index, rc;
5753 
5754     fp_index = 0; /* default is the first queue */
5755 
5756     /* check if flowid is set */
5757 
5758     if (BXE_VALID_FLOWID(m))
5759         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5760 
5761     fp = &sc->fp[fp_index];
5762 
5763     if (BXE_FP_TX_TRYLOCK(fp)) {
5764         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5765         BXE_FP_TX_UNLOCK(fp);
5766     } else {
5767         rc = drbr_enqueue(ifp, fp->tx_br, m);
5768         taskqueue_enqueue(fp->tq, &fp->tx_task);
5769     }
5770 
5771     return (rc);
5772 }
5773 
5774 static void
5775 bxe_mq_flush(struct ifnet *ifp)
5776 {
5777     struct bxe_softc *sc = if_getsoftc(ifp);
5778     struct bxe_fastpath *fp;
5779     struct mbuf *m;
5780     int i;
5781 
5782     for (i = 0; i < sc->num_queues; i++) {
5783         fp = &sc->fp[i];
5784 
5785         if (fp->state != BXE_FP_STATE_OPEN) {
5786             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5787                   fp->index, fp->state);
5788             continue;
5789         }
5790 
5791         if (fp->tx_br != NULL) {
5792             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5793             BXE_FP_TX_LOCK(fp);
5794             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5795                 m_freem(m);
5796             }
5797             BXE_FP_TX_UNLOCK(fp);
5798         }
5799     }
5800 
5801     if_qflush(ifp);
5802 }
5803 
5804 #endif /* FreeBSD_version >= 800000 */
5805 
5806 static uint16_t
5807 bxe_cid_ilt_lines(struct bxe_softc *sc)
5808 {
5809     if (IS_SRIOV(sc)) {
5810         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5811     }
5812     return (L2_ILT_LINES(sc));
5813 }
5814 
5815 static void
5816 bxe_ilt_set_info(struct bxe_softc *sc)
5817 {
5818     struct ilt_client_info *ilt_client;
5819     struct ecore_ilt *ilt = sc->ilt;
5820     uint16_t line = 0;
5821 
5822     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5823     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5824 
5825     /* CDU */
5826     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5827     ilt_client->client_num = ILT_CLIENT_CDU;
5828     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5829     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5830     ilt_client->start = line;
5831     line += bxe_cid_ilt_lines(sc);
5832 
5833     if (CNIC_SUPPORT(sc)) {
5834         line += CNIC_ILT_LINES;
5835     }
5836 
5837     ilt_client->end = (line - 1);
5838 
5839     BLOGD(sc, DBG_LOAD,
5840           "ilt client[CDU]: start %d, end %d, "
5841           "psz 0x%x, flags 0x%x, hw psz %d\n",
5842           ilt_client->start, ilt_client->end,
5843           ilt_client->page_size,
5844           ilt_client->flags,
5845           ilog2(ilt_client->page_size >> 12));
5846 
5847     /* QM */
5848     if (QM_INIT(sc->qm_cid_count)) {
5849         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5850         ilt_client->client_num = ILT_CLIENT_QM;
5851         ilt_client->page_size = QM_ILT_PAGE_SZ;
5852         ilt_client->flags = 0;
5853         ilt_client->start = line;
5854 
5855         /* 4 bytes for each cid */
5856         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5857                              QM_ILT_PAGE_SZ);
5858 
5859         ilt_client->end = (line - 1);
5860 
5861         BLOGD(sc, DBG_LOAD,
5862               "ilt client[QM]: start %d, end %d, "
5863               "psz 0x%x, flags 0x%x, hw psz %d\n",
5864               ilt_client->start, ilt_client->end,
5865               ilt_client->page_size, ilt_client->flags,
5866               ilog2(ilt_client->page_size >> 12));
5867     }
5868 
5869     if (CNIC_SUPPORT(sc)) {
5870         /* SRC */
5871         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5872         ilt_client->client_num = ILT_CLIENT_SRC;
5873         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5874         ilt_client->flags = 0;
5875         ilt_client->start = line;
5876         line += SRC_ILT_LINES;
5877         ilt_client->end = (line - 1);
5878 
5879         BLOGD(sc, DBG_LOAD,
5880               "ilt client[SRC]: start %d, end %d, "
5881               "psz 0x%x, flags 0x%x, hw psz %d\n",
5882               ilt_client->start, ilt_client->end,
5883               ilt_client->page_size, ilt_client->flags,
5884               ilog2(ilt_client->page_size >> 12));
5885 
5886         /* TM */
5887         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5888         ilt_client->client_num = ILT_CLIENT_TM;
5889         ilt_client->page_size = TM_ILT_PAGE_SZ;
5890         ilt_client->flags = 0;
5891         ilt_client->start = line;
5892         line += TM_ILT_LINES;
5893         ilt_client->end = (line - 1);
5894 
5895         BLOGD(sc, DBG_LOAD,
5896               "ilt client[TM]: start %d, end %d, "
5897               "psz 0x%x, flags 0x%x, hw psz %d\n",
5898               ilt_client->start, ilt_client->end,
5899               ilt_client->page_size, ilt_client->flags,
5900               ilog2(ilt_client->page_size >> 12));
5901     }
5902 
5903     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5904 }
5905 
5906 static void
5907 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5908 {
5909     int i;
5910     uint32_t rx_buf_size;
5911 
5912     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5913 
5914     for (i = 0; i < sc->num_queues; i++) {
5915         if(rx_buf_size <= MCLBYTES){
5916             sc->fp[i].rx_buf_size = rx_buf_size;
5917             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5918         }else if (rx_buf_size <= MJUMPAGESIZE){
5919             sc->fp[i].rx_buf_size = rx_buf_size;
5920             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5921         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5922             sc->fp[i].rx_buf_size = MCLBYTES;
5923             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5924         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5925             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5926             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5927         }else {
5928             sc->fp[i].rx_buf_size = MCLBYTES;
5929             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5930         }
5931     }
5932 }
5933 
5934 static int
5935 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5936 {
5937     int rc = 0;
5938 
5939     if ((sc->ilt =
5940          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5941                                     M_BXE_ILT,
5942                                     (M_NOWAIT | M_ZERO))) == NULL) {
5943         rc = 1;
5944     }
5945 
5946     return (rc);
5947 }
5948 
5949 static int
5950 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5951 {
5952     int rc = 0;
5953 
5954     if ((sc->ilt->lines =
5955          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
5956                                     M_BXE_ILT,
5957                                     (M_NOWAIT | M_ZERO))) == NULL) {
5958         rc = 1;
5959     }
5960 
5961     return (rc);
5962 }
5963 
5964 static void
5965 bxe_free_ilt_mem(struct bxe_softc *sc)
5966 {
5967     if (sc->ilt != NULL) {
5968         free(sc->ilt, M_BXE_ILT);
5969         sc->ilt = NULL;
5970     }
5971 }
5972 
5973 static void
5974 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
5975 {
5976     if (sc->ilt->lines != NULL) {
5977         free(sc->ilt->lines, M_BXE_ILT);
5978         sc->ilt->lines = NULL;
5979     }
5980 }
5981 
5982 static void
5983 bxe_free_mem(struct bxe_softc *sc)
5984 {
5985     int i;
5986 
5987     for (i = 0; i < L2_ILT_LINES(sc); i++) {
5988         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
5989         sc->context[i].vcxt = NULL;
5990         sc->context[i].size = 0;
5991     }
5992 
5993     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
5994 
5995     bxe_free_ilt_lines_mem(sc);
5996 
5997 }
5998 
5999 static int
6000 bxe_alloc_mem(struct bxe_softc *sc)
6001 {
6002     int context_size;
6003     int allocated;
6004     int i;
6005 
6006     /*
6007      * Allocate memory for CDU context:
6008      * This memory is allocated separately and not in the generic ILT
6009      * functions because CDU differs in few aspects:
6010      * 1. There can be multiple entities allocating memory for context -
6011      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6012      * its own ILT lines.
6013      * 2. Since CDU page-size is not a single 4KB page (which is the case
6014      * for the other ILT clients), to be efficient we want to support
6015      * allocation of sub-page-size in the last entry.
6016      * 3. Context pointers are used by the driver to pass to FW / update
6017      * the context (for the other ILT clients the pointers are used just to
6018      * free the memory during unload).
6019      */
6020     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6021     for (i = 0, allocated = 0; allocated < context_size; i++) {
6022         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6023                                   (context_size - allocated));
6024 
6025         if (bxe_dma_alloc(sc, sc->context[i].size,
6026                           &sc->context[i].vcxt_dma,
6027                           "cdu context") != 0) {
6028             bxe_free_mem(sc);
6029             return (-1);
6030         }
6031 
6032         sc->context[i].vcxt =
6033             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6034 
6035         allocated += sc->context[i].size;
6036     }
6037 
6038     bxe_alloc_ilt_lines_mem(sc);
6039 
6040     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6041           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6042     {
6043         for (i = 0; i < 4; i++) {
6044             BLOGD(sc, DBG_LOAD,
6045                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6046                   i,
6047                   sc->ilt->clients[i].page_size,
6048                   sc->ilt->clients[i].start,
6049                   sc->ilt->clients[i].end,
6050                   sc->ilt->clients[i].client_num,
6051                   sc->ilt->clients[i].flags);
6052         }
6053     }
6054     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6055         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6056         bxe_free_mem(sc);
6057         return (-1);
6058     }
6059 
6060     return (0);
6061 }
6062 
6063 static void
6064 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6065 {
6066     struct bxe_softc *sc;
6067     int i;
6068 
6069     sc = fp->sc;
6070 
6071     if (fp->rx_mbuf_tag == NULL) {
6072         return;
6073     }
6074 
6075     /* free all mbufs and unload all maps */
6076     for (i = 0; i < RX_BD_TOTAL; i++) {
6077         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6078             bus_dmamap_sync(fp->rx_mbuf_tag,
6079                             fp->rx_mbuf_chain[i].m_map,
6080                             BUS_DMASYNC_POSTREAD);
6081             bus_dmamap_unload(fp->rx_mbuf_tag,
6082                               fp->rx_mbuf_chain[i].m_map);
6083         }
6084 
6085         if (fp->rx_mbuf_chain[i].m != NULL) {
6086             m_freem(fp->rx_mbuf_chain[i].m);
6087             fp->rx_mbuf_chain[i].m = NULL;
6088             fp->eth_q_stats.mbuf_alloc_rx--;
6089         }
6090     }
6091 }
6092 
6093 static void
6094 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6095 {
6096     struct bxe_softc *sc;
6097     int i, max_agg_queues;
6098 
6099     sc = fp->sc;
6100 
6101     if (fp->rx_mbuf_tag == NULL) {
6102         return;
6103     }
6104 
6105     max_agg_queues = MAX_AGG_QS(sc);
6106 
6107     /* release all mbufs and unload all DMA maps in the TPA pool */
6108     for (i = 0; i < max_agg_queues; i++) {
6109         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6110             bus_dmamap_sync(fp->rx_mbuf_tag,
6111                             fp->rx_tpa_info[i].bd.m_map,
6112                             BUS_DMASYNC_POSTREAD);
6113             bus_dmamap_unload(fp->rx_mbuf_tag,
6114                               fp->rx_tpa_info[i].bd.m_map);
6115         }
6116 
6117         if (fp->rx_tpa_info[i].bd.m != NULL) {
6118             m_freem(fp->rx_tpa_info[i].bd.m);
6119             fp->rx_tpa_info[i].bd.m = NULL;
6120             fp->eth_q_stats.mbuf_alloc_tpa--;
6121         }
6122     }
6123 }
6124 
6125 static void
6126 bxe_free_sge_chain(struct bxe_fastpath *fp)
6127 {
6128     struct bxe_softc *sc;
6129     int i;
6130 
6131     sc = fp->sc;
6132 
6133     if (fp->rx_sge_mbuf_tag == NULL) {
6134         return;
6135     }
6136 
6137     /* rree all mbufs and unload all maps */
6138     for (i = 0; i < RX_SGE_TOTAL; i++) {
6139         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6140             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6141                             fp->rx_sge_mbuf_chain[i].m_map,
6142                             BUS_DMASYNC_POSTREAD);
6143             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6144                               fp->rx_sge_mbuf_chain[i].m_map);
6145         }
6146 
6147         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6148             m_freem(fp->rx_sge_mbuf_chain[i].m);
6149             fp->rx_sge_mbuf_chain[i].m = NULL;
6150             fp->eth_q_stats.mbuf_alloc_sge--;
6151         }
6152     }
6153 }
6154 
6155 static void
6156 bxe_free_fp_buffers(struct bxe_softc *sc)
6157 {
6158     struct bxe_fastpath *fp;
6159     int i;
6160 
6161     for (i = 0; i < sc->num_queues; i++) {
6162         fp = &sc->fp[i];
6163 
6164 #if __FreeBSD_version >= 800000
6165         if (fp->tx_br != NULL) {
6166             /* just in case bxe_mq_flush() wasn't called */
6167             if (mtx_initialized(&fp->tx_mtx)) {
6168                 struct mbuf *m;
6169 
6170                 BXE_FP_TX_LOCK(fp);
6171                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6172                     m_freem(m);
6173                 BXE_FP_TX_UNLOCK(fp);
6174             }
6175         }
6176 #endif
6177 
6178         /* free all RX buffers */
6179         bxe_free_rx_bd_chain(fp);
6180         bxe_free_tpa_pool(fp);
6181         bxe_free_sge_chain(fp);
6182 
6183         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6184             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6185                   fp->eth_q_stats.mbuf_alloc_rx);
6186         }
6187 
6188         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6189             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6190                   fp->eth_q_stats.mbuf_alloc_sge);
6191         }
6192 
6193         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6194             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6195                   fp->eth_q_stats.mbuf_alloc_tpa);
6196         }
6197 
6198         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6199             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6200                   fp->eth_q_stats.mbuf_alloc_tx);
6201         }
6202 
6203         /* XXX verify all mbufs were reclaimed */
6204     }
6205 }
6206 
6207 static int
6208 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6209                      uint16_t            prev_index,
6210                      uint16_t            index)
6211 {
6212     struct bxe_sw_rx_bd *rx_buf;
6213     struct eth_rx_bd *rx_bd;
6214     bus_dma_segment_t segs[1];
6215     bus_dmamap_t map;
6216     struct mbuf *m;
6217     int nsegs, rc;
6218 
6219     rc = 0;
6220 
6221     /* allocate the new RX BD mbuf */
6222     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6223     if (__predict_false(m == NULL)) {
6224         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6225         return (ENOBUFS);
6226     }
6227 
6228     fp->eth_q_stats.mbuf_alloc_rx++;
6229 
6230     /* initialize the mbuf buffer length */
6231     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6232 
6233     /* map the mbuf into non-paged pool */
6234     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6235                                  fp->rx_mbuf_spare_map,
6236                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6237     if (__predict_false(rc != 0)) {
6238         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6239         m_freem(m);
6240         fp->eth_q_stats.mbuf_alloc_rx--;
6241         return (rc);
6242     }
6243 
6244     /* all mbufs must map to a single segment */
6245     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6246 
6247     /* release any existing RX BD mbuf mappings */
6248 
6249     if (prev_index != index) {
6250         rx_buf = &fp->rx_mbuf_chain[prev_index];
6251 
6252         if (rx_buf->m_map != NULL) {
6253             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6254                             BUS_DMASYNC_POSTREAD);
6255             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6256         }
6257 
6258         /*
6259          * We only get here from bxe_rxeof() when the maximum number
6260          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6261          * holds the mbuf in the prev_index so it's OK to NULL it out
6262          * here without concern of a memory leak.
6263          */
6264         fp->rx_mbuf_chain[prev_index].m = NULL;
6265     }
6266 
6267     rx_buf = &fp->rx_mbuf_chain[index];
6268 
6269     if (rx_buf->m_map != NULL) {
6270         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6271                         BUS_DMASYNC_POSTREAD);
6272         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6273     }
6274 
6275     /* save the mbuf and mapping info for a future packet */
6276     map = (prev_index != index) ?
6277               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6278     rx_buf->m_map = fp->rx_mbuf_spare_map;
6279     fp->rx_mbuf_spare_map = map;
6280     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6281                     BUS_DMASYNC_PREREAD);
6282     rx_buf->m = m;
6283 
6284     rx_bd = &fp->rx_chain[index];
6285     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6286     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6287 
6288     return (rc);
6289 }
6290 
6291 static int
6292 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6293                       int                 queue)
6294 {
6295     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6296     bus_dma_segment_t segs[1];
6297     bus_dmamap_t map;
6298     struct mbuf *m;
6299     int nsegs;
6300     int rc = 0;
6301 
6302     /* allocate the new TPA mbuf */
6303     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6304     if (__predict_false(m == NULL)) {
6305         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6306         return (ENOBUFS);
6307     }
6308 
6309     fp->eth_q_stats.mbuf_alloc_tpa++;
6310 
6311     /* initialize the mbuf buffer length */
6312     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6313 
6314     /* map the mbuf into non-paged pool */
6315     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6316                                  fp->rx_tpa_info_mbuf_spare_map,
6317                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6318     if (__predict_false(rc != 0)) {
6319         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6320         m_free(m);
6321         fp->eth_q_stats.mbuf_alloc_tpa--;
6322         return (rc);
6323     }
6324 
6325     /* all mbufs must map to a single segment */
6326     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6327 
6328     /* release any existing TPA mbuf mapping */
6329     if (tpa_info->bd.m_map != NULL) {
6330         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6331                         BUS_DMASYNC_POSTREAD);
6332         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6333     }
6334 
6335     /* save the mbuf and mapping info for the TPA mbuf */
6336     map = tpa_info->bd.m_map;
6337     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6338     fp->rx_tpa_info_mbuf_spare_map = map;
6339     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6340                     BUS_DMASYNC_PREREAD);
6341     tpa_info->bd.m = m;
6342     tpa_info->seg = segs[0];
6343 
6344     return (rc);
6345 }
6346 
6347 /*
6348  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6349  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6350  * chain.
6351  */
6352 static int
6353 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6354                       uint16_t            index)
6355 {
6356     struct bxe_sw_rx_bd *sge_buf;
6357     struct eth_rx_sge *sge;
6358     bus_dma_segment_t segs[1];
6359     bus_dmamap_t map;
6360     struct mbuf *m;
6361     int nsegs;
6362     int rc = 0;
6363 
6364     /* allocate a new SGE mbuf */
6365     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6366     if (__predict_false(m == NULL)) {
6367         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6368         return (ENOMEM);
6369     }
6370 
6371     fp->eth_q_stats.mbuf_alloc_sge++;
6372 
6373     /* initialize the mbuf buffer length */
6374     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6375 
6376     /* map the SGE mbuf into non-paged pool */
6377     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6378                                  fp->rx_sge_mbuf_spare_map,
6379                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6380     if (__predict_false(rc != 0)) {
6381         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6382         m_freem(m);
6383         fp->eth_q_stats.mbuf_alloc_sge--;
6384         return (rc);
6385     }
6386 
6387     /* all mbufs must map to a single segment */
6388     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6389 
6390     sge_buf = &fp->rx_sge_mbuf_chain[index];
6391 
6392     /* release any existing SGE mbuf mapping */
6393     if (sge_buf->m_map != NULL) {
6394         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6395                         BUS_DMASYNC_POSTREAD);
6396         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6397     }
6398 
6399     /* save the mbuf and mapping info for a future packet */
6400     map = sge_buf->m_map;
6401     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6402     fp->rx_sge_mbuf_spare_map = map;
6403     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6404                     BUS_DMASYNC_PREREAD);
6405     sge_buf->m = m;
6406 
6407     sge = &fp->rx_sge_chain[index];
6408     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6409     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6410 
6411     return (rc);
6412 }
6413 
6414 static __noinline int
6415 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6416 {
6417     struct bxe_fastpath *fp;
6418     int i, j, rc = 0;
6419     int ring_prod, cqe_ring_prod;
6420     int max_agg_queues;
6421 
6422     for (i = 0; i < sc->num_queues; i++) {
6423         fp = &sc->fp[i];
6424 
6425         ring_prod = cqe_ring_prod = 0;
6426         fp->rx_bd_cons = 0;
6427         fp->rx_cq_cons = 0;
6428 
6429         /* allocate buffers for the RX BDs in RX BD chain */
6430         for (j = 0; j < sc->max_rx_bufs; j++) {
6431             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6432             if (rc != 0) {
6433                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6434                       i, rc);
6435                 goto bxe_alloc_fp_buffers_error;
6436             }
6437 
6438             ring_prod     = RX_BD_NEXT(ring_prod);
6439             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6440         }
6441 
6442         fp->rx_bd_prod = ring_prod;
6443         fp->rx_cq_prod = cqe_ring_prod;
6444         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6445 
6446         max_agg_queues = MAX_AGG_QS(sc);
6447 
6448         fp->tpa_enable = TRUE;
6449 
6450         /* fill the TPA pool */
6451         for (j = 0; j < max_agg_queues; j++) {
6452             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6453             if (rc != 0) {
6454                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6455                           i, j);
6456                 fp->tpa_enable = FALSE;
6457                 goto bxe_alloc_fp_buffers_error;
6458             }
6459 
6460             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6461         }
6462 
6463         if (fp->tpa_enable) {
6464             /* fill the RX SGE chain */
6465             ring_prod = 0;
6466             for (j = 0; j < RX_SGE_USABLE; j++) {
6467                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6468                 if (rc != 0) {
6469                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6470                               i, ring_prod);
6471                     fp->tpa_enable = FALSE;
6472                     ring_prod = 0;
6473                     goto bxe_alloc_fp_buffers_error;
6474                 }
6475 
6476                 ring_prod = RX_SGE_NEXT(ring_prod);
6477             }
6478 
6479             fp->rx_sge_prod = ring_prod;
6480         }
6481     }
6482 
6483     return (0);
6484 
6485 bxe_alloc_fp_buffers_error:
6486 
6487     /* unwind what was already allocated */
6488     bxe_free_rx_bd_chain(fp);
6489     bxe_free_tpa_pool(fp);
6490     bxe_free_sge_chain(fp);
6491 
6492     return (ENOBUFS);
6493 }
6494 
6495 static void
6496 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6497 {
6498     bxe_dma_free(sc, &sc->fw_stats_dma);
6499 
6500     sc->fw_stats_num = 0;
6501 
6502     sc->fw_stats_req_size = 0;
6503     sc->fw_stats_req = NULL;
6504     sc->fw_stats_req_mapping = 0;
6505 
6506     sc->fw_stats_data_size = 0;
6507     sc->fw_stats_data = NULL;
6508     sc->fw_stats_data_mapping = 0;
6509 }
6510 
6511 static int
6512 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6513 {
6514     uint8_t num_queue_stats;
6515     int num_groups;
6516 
6517     /* number of queues for statistics is number of eth queues */
6518     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6519 
6520     /*
6521      * Total number of FW statistics requests =
6522      *   1 for port stats + 1 for PF stats + num of queues
6523      */
6524     sc->fw_stats_num = (2 + num_queue_stats);
6525 
6526     /*
6527      * Request is built from stats_query_header and an array of
6528      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6529      * rules. The real number or requests is configured in the
6530      * stats_query_header.
6531      */
6532     num_groups =
6533         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6534          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6535 
6536     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6537           sc->fw_stats_num, num_groups);
6538 
6539     sc->fw_stats_req_size =
6540         (sizeof(struct stats_query_header) +
6541          (num_groups * sizeof(struct stats_query_cmd_group)));
6542 
6543     /*
6544      * Data for statistics requests + stats_counter.
6545      * stats_counter holds per-STORM counters that are incremented when
6546      * STORM has finished with the current request. Memory for FCoE
6547      * offloaded statistics are counted anyway, even if they will not be sent.
6548      * VF stats are not accounted for here as the data of VF stats is stored
6549      * in memory allocated by the VF, not here.
6550      */
6551     sc->fw_stats_data_size =
6552         (sizeof(struct stats_counter) +
6553          sizeof(struct per_port_stats) +
6554          sizeof(struct per_pf_stats) +
6555          /* sizeof(struct fcoe_statistics_params) + */
6556          (sizeof(struct per_queue_stats) * num_queue_stats));
6557 
6558     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6559                       &sc->fw_stats_dma, "fw stats") != 0) {
6560         bxe_free_fw_stats_mem(sc);
6561         return (-1);
6562     }
6563 
6564     /* set up the shortcuts */
6565 
6566     sc->fw_stats_req =
6567         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6568     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6569 
6570     sc->fw_stats_data =
6571         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6572                                      sc->fw_stats_req_size);
6573     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6574                                  sc->fw_stats_req_size);
6575 
6576     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6577           (uintmax_t)sc->fw_stats_req_mapping);
6578 
6579     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6580           (uintmax_t)sc->fw_stats_data_mapping);
6581 
6582     return (0);
6583 }
6584 
6585 /*
6586  * Bits map:
6587  * 0-7  - Engine0 load counter.
6588  * 8-15 - Engine1 load counter.
6589  * 16   - Engine0 RESET_IN_PROGRESS bit.
6590  * 17   - Engine1 RESET_IN_PROGRESS bit.
6591  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6592  *        function on the engine
6593  * 19   - Engine1 ONE_IS_LOADED.
6594  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6595  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6596  *        for just the one belonging to its engine).
6597  */
6598 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6599 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6600 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6601 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6602 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6603 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6604 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6605 #define BXE_GLOBAL_RESET_BIT      0x00040000
6606 
6607 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6608 static void
6609 bxe_set_reset_global(struct bxe_softc *sc)
6610 {
6611     uint32_t val;
6612     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6613     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6614     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6615     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6616 }
6617 
6618 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6619 static void
6620 bxe_clear_reset_global(struct bxe_softc *sc)
6621 {
6622     uint32_t val;
6623     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6624     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6625     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6626     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6627 }
6628 
6629 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6630 static uint8_t
6631 bxe_reset_is_global(struct bxe_softc *sc)
6632 {
6633     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6634     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6635     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6636 }
6637 
6638 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6639 static void
6640 bxe_set_reset_done(struct bxe_softc *sc)
6641 {
6642     uint32_t val;
6643     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6644                                  BXE_PATH0_RST_IN_PROG_BIT;
6645 
6646     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6647 
6648     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6649     /* Clear the bit */
6650     val &= ~bit;
6651     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6652 
6653     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6654 }
6655 
6656 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6657 static void
6658 bxe_set_reset_in_progress(struct bxe_softc *sc)
6659 {
6660     uint32_t val;
6661     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6662                                  BXE_PATH0_RST_IN_PROG_BIT;
6663 
6664     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6665 
6666     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6667     /* Set the bit */
6668     val |= bit;
6669     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6670 
6671     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6672 }
6673 
6674 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6675 static uint8_t
6676 bxe_reset_is_done(struct bxe_softc *sc,
6677                   int              engine)
6678 {
6679     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6680     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6681                             BXE_PATH0_RST_IN_PROG_BIT;
6682 
6683     /* return false if bit is set */
6684     return (val & bit) ? FALSE : TRUE;
6685 }
6686 
6687 /* get the load status for an engine, should be run under rtnl lock */
6688 static uint8_t
6689 bxe_get_load_status(struct bxe_softc *sc,
6690                     int              engine)
6691 {
6692     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6693                              BXE_PATH0_LOAD_CNT_MASK;
6694     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6695                               BXE_PATH0_LOAD_CNT_SHIFT;
6696     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6697 
6698     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6699 
6700     val = ((val & mask) >> shift);
6701 
6702     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6703 
6704     return (val != 0);
6705 }
6706 
6707 /* set pf load mark */
6708 /* XXX needs to be under rtnl lock */
6709 static void
6710 bxe_set_pf_load(struct bxe_softc *sc)
6711 {
6712     uint32_t val;
6713     uint32_t val1;
6714     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6715                                   BXE_PATH0_LOAD_CNT_MASK;
6716     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6717                                    BXE_PATH0_LOAD_CNT_SHIFT;
6718 
6719     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6720 
6721     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6722     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6723 
6724     /* get the current counter value */
6725     val1 = ((val & mask) >> shift);
6726 
6727     /* set bit of this PF */
6728     val1 |= (1 << SC_ABS_FUNC(sc));
6729 
6730     /* clear the old value */
6731     val &= ~mask;
6732 
6733     /* set the new one */
6734     val |= ((val1 << shift) & mask);
6735 
6736     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6737 
6738     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6739 }
6740 
6741 /* clear pf load mark */
6742 /* XXX needs to be under rtnl lock */
6743 static uint8_t
6744 bxe_clear_pf_load(struct bxe_softc *sc)
6745 {
6746     uint32_t val1, val;
6747     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6748                                   BXE_PATH0_LOAD_CNT_MASK;
6749     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6750                                    BXE_PATH0_LOAD_CNT_SHIFT;
6751 
6752     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6753     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6754     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6755 
6756     /* get the current counter value */
6757     val1 = (val & mask) >> shift;
6758 
6759     /* clear bit of that PF */
6760     val1 &= ~(1 << SC_ABS_FUNC(sc));
6761 
6762     /* clear the old value */
6763     val &= ~mask;
6764 
6765     /* set the new one */
6766     val |= ((val1 << shift) & mask);
6767 
6768     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6769     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6770     return (val1 != 0);
6771 }
6772 
6773 /* send load requrest to mcp and analyze response */
6774 static int
6775 bxe_nic_load_request(struct bxe_softc *sc,
6776                      uint32_t         *load_code)
6777 {
6778     /* init fw_seq */
6779     sc->fw_seq =
6780         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6781          DRV_MSG_SEQ_NUMBER_MASK);
6782 
6783     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6784 
6785     /* get the current FW pulse sequence */
6786     sc->fw_drv_pulse_wr_seq =
6787         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6788          DRV_PULSE_SEQ_MASK);
6789 
6790     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6791           sc->fw_drv_pulse_wr_seq);
6792 
6793     /* load request */
6794     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6795                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6796 
6797     /* if the MCP fails to respond we must abort */
6798     if (!(*load_code)) {
6799         BLOGE(sc, "MCP response failure!\n");
6800         return (-1);
6801     }
6802 
6803     /* if MCP refused then must abort */
6804     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6805         BLOGE(sc, "MCP refused load request\n");
6806         return (-1);
6807     }
6808 
6809     return (0);
6810 }
6811 
6812 /*
6813  * Check whether another PF has already loaded FW to chip. In virtualized
6814  * environments a pf from anoth VM may have already initialized the device
6815  * including loading FW.
6816  */
6817 static int
6818 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6819                          uint32_t         load_code)
6820 {
6821     uint32_t my_fw, loaded_fw;
6822 
6823     /* is another pf loaded on this engine? */
6824     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6825         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6826         /* build my FW version dword */
6827         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6828                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6829                  (BCM_5710_FW_REVISION_VERSION << 16) +
6830                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6831 
6832         /* read loaded FW from chip */
6833         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6834         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6835               loaded_fw, my_fw);
6836 
6837         /* abort nic load if version mismatch */
6838         if (my_fw != loaded_fw) {
6839             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6840                   loaded_fw, my_fw);
6841             return (-1);
6842         }
6843     }
6844 
6845     return (0);
6846 }
6847 
6848 /* mark PMF if applicable */
6849 static void
6850 bxe_nic_load_pmf(struct bxe_softc *sc,
6851                  uint32_t         load_code)
6852 {
6853     uint32_t ncsi_oem_data_addr;
6854 
6855     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6856         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6857         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6858         /*
6859          * Barrier here for ordering between the writing to sc->port.pmf here
6860          * and reading it from the periodic task.
6861          */
6862         sc->port.pmf = 1;
6863         mb();
6864     } else {
6865         sc->port.pmf = 0;
6866     }
6867 
6868     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6869 
6870     /* XXX needed? */
6871     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6872         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6873             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6874             if (ncsi_oem_data_addr) {
6875                 REG_WR(sc,
6876                        (ncsi_oem_data_addr +
6877                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6878                        0);
6879             }
6880         }
6881     }
6882 }
6883 
6884 static void
6885 bxe_read_mf_cfg(struct bxe_softc *sc)
6886 {
6887     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6888     int abs_func;
6889     int vn;
6890 
6891     if (BXE_NOMCP(sc)) {
6892         return; /* what should be the default bvalue in this case */
6893     }
6894 
6895     /*
6896      * The formula for computing the absolute function number is...
6897      * For 2 port configuration (4 functions per port):
6898      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6899      * For 4 port configuration (2 functions per port):
6900      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6901      */
6902     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6903         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6904         if (abs_func >= E1H_FUNC_MAX) {
6905             break;
6906         }
6907         sc->devinfo.mf_info.mf_config[vn] =
6908             MFCFG_RD(sc, func_mf_config[abs_func].config);
6909     }
6910 
6911     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6912         FUNC_MF_CFG_FUNC_DISABLED) {
6913         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6914         sc->flags |= BXE_MF_FUNC_DIS;
6915     } else {
6916         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6917         sc->flags &= ~BXE_MF_FUNC_DIS;
6918     }
6919 }
6920 
6921 /* acquire split MCP access lock register */
6922 static int bxe_acquire_alr(struct bxe_softc *sc)
6923 {
6924     uint32_t j, val;
6925 
6926     for (j = 0; j < 1000; j++) {
6927         val = (1UL << 31);
6928         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6929         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6930         if (val & (1L << 31))
6931             break;
6932 
6933         DELAY(5000);
6934     }
6935 
6936     if (!(val & (1L << 31))) {
6937         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6938         return (-1);
6939     }
6940 
6941     return (0);
6942 }
6943 
6944 /* release split MCP access lock register */
6945 static void bxe_release_alr(struct bxe_softc *sc)
6946 {
6947     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6948 }
6949 
6950 static void
6951 bxe_fan_failure(struct bxe_softc *sc)
6952 {
6953     int port = SC_PORT(sc);
6954     uint32_t ext_phy_config;
6955 
6956     /* mark the failure */
6957     ext_phy_config =
6958         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
6959 
6960     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
6961     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
6962     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
6963              ext_phy_config);
6964 
6965     /* log the failure */
6966     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
6967               "the card to prevent permanent damage. "
6968               "Please contact OEM Support for assistance\n");
6969 
6970     /* XXX */
6971 #if 1
6972     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
6973 #else
6974     /*
6975      * Schedule device reset (unload)
6976      * This is due to some boards consuming sufficient power when driver is
6977      * up to overheat if fan fails.
6978      */
6979     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
6980     schedule_delayed_work(&sc->sp_rtnl_task, 0);
6981 #endif
6982 }
6983 
6984 /* this function is called upon a link interrupt */
6985 static void
6986 bxe_link_attn(struct bxe_softc *sc)
6987 {
6988     uint32_t pause_enabled = 0;
6989     struct host_port_stats *pstats;
6990     int cmng_fns;
6991     struct bxe_fastpath *fp;
6992     int i;
6993 
6994     /* Make sure that we are synced with the current statistics */
6995     bxe_stats_handle(sc, STATS_EVENT_STOP);
6996 
6997     elink_link_update(&sc->link_params, &sc->link_vars);
6998 
6999     if (sc->link_vars.link_up) {
7000 
7001         /* dropless flow control */
7002         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7003             pause_enabled = 0;
7004 
7005             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7006                 pause_enabled = 1;
7007             }
7008 
7009             REG_WR(sc,
7010                    (BAR_USTRORM_INTMEM +
7011                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7012                    pause_enabled);
7013         }
7014 
7015         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7016             pstats = BXE_SP(sc, port_stats);
7017             /* reset old mac stats */
7018             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7019         }
7020 
7021         if (sc->state == BXE_STATE_OPEN) {
7022             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7023         }
7024 
7025         /* Restart tx when the link comes back. */
7026         FOR_EACH_ETH_QUEUE(sc, i) {
7027             fp = &sc->fp[i];
7028             taskqueue_enqueue(fp->tq, &fp->tx_task);
7029         }
7030     }
7031 
7032     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7033         cmng_fns = bxe_get_cmng_fns_mode(sc);
7034 
7035         if (cmng_fns != CMNG_FNS_NONE) {
7036             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7037             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7038         } else {
7039             /* rate shaping and fairness are disabled */
7040             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7041         }
7042     }
7043 
7044     bxe_link_report_locked(sc);
7045 
7046     if (IS_MF(sc)) {
7047         ; // XXX bxe_link_sync_notify(sc);
7048     }
7049 }
7050 
7051 static void
7052 bxe_attn_int_asserted(struct bxe_softc *sc,
7053                       uint32_t         asserted)
7054 {
7055     int port = SC_PORT(sc);
7056     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7057                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7058     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7059                                         NIG_REG_MASK_INTERRUPT_PORT0;
7060     uint32_t aeu_mask;
7061     uint32_t nig_mask = 0;
7062     uint32_t reg_addr;
7063     uint32_t igu_acked;
7064     uint32_t cnt;
7065 
7066     if (sc->attn_state & asserted) {
7067         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7068     }
7069 
7070     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7071 
7072     aeu_mask = REG_RD(sc, aeu_addr);
7073 
7074     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7075           aeu_mask, asserted);
7076 
7077     aeu_mask &= ~(asserted & 0x3ff);
7078 
7079     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7080 
7081     REG_WR(sc, aeu_addr, aeu_mask);
7082 
7083     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7084 
7085     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7086     sc->attn_state |= asserted;
7087     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7088 
7089     if (asserted & ATTN_HARD_WIRED_MASK) {
7090         if (asserted & ATTN_NIG_FOR_FUNC) {
7091 
7092 	    bxe_acquire_phy_lock(sc);
7093             /* save nig interrupt mask */
7094             nig_mask = REG_RD(sc, nig_int_mask_addr);
7095 
7096             /* If nig_mask is not set, no need to call the update function */
7097             if (nig_mask) {
7098                 REG_WR(sc, nig_int_mask_addr, 0);
7099 
7100                 bxe_link_attn(sc);
7101             }
7102 
7103             /* handle unicore attn? */
7104         }
7105 
7106         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7107             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7108         }
7109 
7110         if (asserted & GPIO_2_FUNC) {
7111             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7112         }
7113 
7114         if (asserted & GPIO_3_FUNC) {
7115             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7116         }
7117 
7118         if (asserted & GPIO_4_FUNC) {
7119             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7120         }
7121 
7122         if (port == 0) {
7123             if (asserted & ATTN_GENERAL_ATTN_1) {
7124                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7125                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7126             }
7127             if (asserted & ATTN_GENERAL_ATTN_2) {
7128                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7129                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7130             }
7131             if (asserted & ATTN_GENERAL_ATTN_3) {
7132                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7133                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7134             }
7135         } else {
7136             if (asserted & ATTN_GENERAL_ATTN_4) {
7137                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7138                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7139             }
7140             if (asserted & ATTN_GENERAL_ATTN_5) {
7141                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7142                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7143             }
7144             if (asserted & ATTN_GENERAL_ATTN_6) {
7145                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7146                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7147             }
7148         }
7149     } /* hardwired */
7150 
7151     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7152         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7153     } else {
7154         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7155     }
7156 
7157     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7158           asserted,
7159           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7160     REG_WR(sc, reg_addr, asserted);
7161 
7162     /* now set back the mask */
7163     if (asserted & ATTN_NIG_FOR_FUNC) {
7164         /*
7165          * Verify that IGU ack through BAR was written before restoring
7166          * NIG mask. This loop should exit after 2-3 iterations max.
7167          */
7168         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7169             cnt = 0;
7170 
7171             do {
7172                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7173             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7174                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7175 
7176             if (!igu_acked) {
7177                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7178             }
7179 
7180             mb();
7181         }
7182 
7183         REG_WR(sc, nig_int_mask_addr, nig_mask);
7184 
7185 	bxe_release_phy_lock(sc);
7186     }
7187 }
7188 
7189 static void
7190 bxe_print_next_block(struct bxe_softc *sc,
7191                      int              idx,
7192                      const char       *blk)
7193 {
7194     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7195 }
7196 
7197 static int
7198 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7199                               uint32_t         sig,
7200                               int              par_num,
7201                               uint8_t          print)
7202 {
7203     uint32_t cur_bit = 0;
7204     int i = 0;
7205 
7206     for (i = 0; sig; i++) {
7207         cur_bit = ((uint32_t)0x1 << i);
7208         if (sig & cur_bit) {
7209             switch (cur_bit) {
7210             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7211                 if (print)
7212                     bxe_print_next_block(sc, par_num++, "BRB");
7213                 break;
7214             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7215                 if (print)
7216                     bxe_print_next_block(sc, par_num++, "PARSER");
7217                 break;
7218             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7219                 if (print)
7220                     bxe_print_next_block(sc, par_num++, "TSDM");
7221                 break;
7222             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7223                 if (print)
7224                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7225                 break;
7226             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7227                 if (print)
7228                     bxe_print_next_block(sc, par_num++, "TCM");
7229                 break;
7230             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7231                 if (print)
7232                     bxe_print_next_block(sc, par_num++, "TSEMI");
7233                 break;
7234             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7235                 if (print)
7236                     bxe_print_next_block(sc, par_num++, "XPB");
7237                 break;
7238             }
7239 
7240             /* Clear the bit */
7241             sig &= ~cur_bit;
7242         }
7243     }
7244 
7245     return (par_num);
7246 }
7247 
7248 static int
7249 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7250                               uint32_t         sig,
7251                               int              par_num,
7252                               uint8_t          *global,
7253                               uint8_t          print)
7254 {
7255     int i = 0;
7256     uint32_t cur_bit = 0;
7257     for (i = 0; sig; i++) {
7258         cur_bit = ((uint32_t)0x1 << i);
7259         if (sig & cur_bit) {
7260             switch (cur_bit) {
7261             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7262                 if (print)
7263                     bxe_print_next_block(sc, par_num++, "PBF");
7264                 break;
7265             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7266                 if (print)
7267                     bxe_print_next_block(sc, par_num++, "QM");
7268                 break;
7269             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7270                 if (print)
7271                     bxe_print_next_block(sc, par_num++, "TM");
7272                 break;
7273             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7274                 if (print)
7275                     bxe_print_next_block(sc, par_num++, "XSDM");
7276                 break;
7277             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7278                 if (print)
7279                     bxe_print_next_block(sc, par_num++, "XCM");
7280                 break;
7281             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7282                 if (print)
7283                     bxe_print_next_block(sc, par_num++, "XSEMI");
7284                 break;
7285             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7286                 if (print)
7287                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7288                 break;
7289             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7290                 if (print)
7291                     bxe_print_next_block(sc, par_num++, "NIG");
7292                 break;
7293             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7294                 if (print)
7295                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7296                 *global = TRUE;
7297                 break;
7298             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7299                 if (print)
7300                     bxe_print_next_block(sc, par_num++, "DEBUG");
7301                 break;
7302             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7303                 if (print)
7304                     bxe_print_next_block(sc, par_num++, "USDM");
7305                 break;
7306             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7307                 if (print)
7308                     bxe_print_next_block(sc, par_num++, "UCM");
7309                 break;
7310             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7311                 if (print)
7312                     bxe_print_next_block(sc, par_num++, "USEMI");
7313                 break;
7314             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7315                 if (print)
7316                     bxe_print_next_block(sc, par_num++, "UPB");
7317                 break;
7318             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7319                 if (print)
7320                     bxe_print_next_block(sc, par_num++, "CSDM");
7321                 break;
7322             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7323                 if (print)
7324                     bxe_print_next_block(sc, par_num++, "CCM");
7325                 break;
7326             }
7327 
7328             /* Clear the bit */
7329             sig &= ~cur_bit;
7330         }
7331     }
7332 
7333     return (par_num);
7334 }
7335 
7336 static int
7337 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7338                               uint32_t         sig,
7339                               int              par_num,
7340                               uint8_t          print)
7341 {
7342     uint32_t cur_bit = 0;
7343     int i = 0;
7344 
7345     for (i = 0; sig; i++) {
7346         cur_bit = ((uint32_t)0x1 << i);
7347         if (sig & cur_bit) {
7348             switch (cur_bit) {
7349             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7350                 if (print)
7351                     bxe_print_next_block(sc, par_num++, "CSEMI");
7352                 break;
7353             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7354                 if (print)
7355                     bxe_print_next_block(sc, par_num++, "PXP");
7356                 break;
7357             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7358                 if (print)
7359                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7360                 break;
7361             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7362                 if (print)
7363                     bxe_print_next_block(sc, par_num++, "CFC");
7364                 break;
7365             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7366                 if (print)
7367                     bxe_print_next_block(sc, par_num++, "CDU");
7368                 break;
7369             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7370                 if (print)
7371                     bxe_print_next_block(sc, par_num++, "DMAE");
7372                 break;
7373             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7374                 if (print)
7375                     bxe_print_next_block(sc, par_num++, "IGU");
7376                 break;
7377             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7378                 if (print)
7379                     bxe_print_next_block(sc, par_num++, "MISC");
7380                 break;
7381             }
7382 
7383             /* Clear the bit */
7384             sig &= ~cur_bit;
7385         }
7386     }
7387 
7388     return (par_num);
7389 }
7390 
7391 static int
7392 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7393                               uint32_t         sig,
7394                               int              par_num,
7395                               uint8_t          *global,
7396                               uint8_t          print)
7397 {
7398     uint32_t cur_bit = 0;
7399     int i = 0;
7400 
7401     for (i = 0; sig; i++) {
7402         cur_bit = ((uint32_t)0x1 << i);
7403         if (sig & cur_bit) {
7404             switch (cur_bit) {
7405             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7406                 if (print)
7407                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7408                 *global = TRUE;
7409                 break;
7410             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7411                 if (print)
7412                     bxe_print_next_block(sc, par_num++,
7413                               "MCP UMP RX");
7414                 *global = TRUE;
7415                 break;
7416             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7417                 if (print)
7418                     bxe_print_next_block(sc, par_num++,
7419                               "MCP UMP TX");
7420                 *global = TRUE;
7421                 break;
7422             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7423                 if (print)
7424                     bxe_print_next_block(sc, par_num++,
7425                               "MCP SCPAD");
7426                 *global = TRUE;
7427                 break;
7428             }
7429 
7430             /* Clear the bit */
7431             sig &= ~cur_bit;
7432         }
7433     }
7434 
7435     return (par_num);
7436 }
7437 
7438 static int
7439 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7440                               uint32_t         sig,
7441                               int              par_num,
7442                               uint8_t          print)
7443 {
7444     uint32_t cur_bit = 0;
7445     int i = 0;
7446 
7447     for (i = 0; sig; i++) {
7448         cur_bit = ((uint32_t)0x1 << i);
7449         if (sig & cur_bit) {
7450             switch (cur_bit) {
7451             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7452                 if (print)
7453                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7454                 break;
7455             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7456                 if (print)
7457                     bxe_print_next_block(sc, par_num++, "ATC");
7458                 break;
7459             }
7460 
7461             /* Clear the bit */
7462             sig &= ~cur_bit;
7463         }
7464     }
7465 
7466     return (par_num);
7467 }
7468 
7469 static uint8_t
7470 bxe_parity_attn(struct bxe_softc *sc,
7471                 uint8_t          *global,
7472                 uint8_t          print,
7473                 uint32_t         *sig)
7474 {
7475     int par_num = 0;
7476 
7477     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7478         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7479         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7480         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7481         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7482         BLOGE(sc, "Parity error: HW block parity attention:\n"
7483                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7484               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7485               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7486               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7487               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7488               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7489 
7490         if (print)
7491             BLOGI(sc, "Parity errors detected in blocks: ");
7492 
7493         par_num =
7494             bxe_check_blocks_with_parity0(sc, sig[0] &
7495                                           HW_PRTY_ASSERT_SET_0,
7496                                           par_num, print);
7497         par_num =
7498             bxe_check_blocks_with_parity1(sc, sig[1] &
7499                                           HW_PRTY_ASSERT_SET_1,
7500                                           par_num, global, print);
7501         par_num =
7502             bxe_check_blocks_with_parity2(sc, sig[2] &
7503                                           HW_PRTY_ASSERT_SET_2,
7504                                           par_num, print);
7505         par_num =
7506             bxe_check_blocks_with_parity3(sc, sig[3] &
7507                                           HW_PRTY_ASSERT_SET_3,
7508                                           par_num, global, print);
7509         par_num =
7510             bxe_check_blocks_with_parity4(sc, sig[4] &
7511                                           HW_PRTY_ASSERT_SET_4,
7512                                           par_num, print);
7513 
7514         if (print)
7515             BLOGI(sc, "\n");
7516 
7517         return (TRUE);
7518     }
7519 
7520     return (FALSE);
7521 }
7522 
7523 static uint8_t
7524 bxe_chk_parity_attn(struct bxe_softc *sc,
7525                     uint8_t          *global,
7526                     uint8_t          print)
7527 {
7528     struct attn_route attn = { {0} };
7529     int port = SC_PORT(sc);
7530 
7531     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7532     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7533     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7534     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7535 
7536     /*
7537      * Since MCP attentions can't be disabled inside the block, we need to
7538      * read AEU registers to see whether they're currently disabled
7539      */
7540     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7541                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7542                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7543                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7544 
7545 
7546     if (!CHIP_IS_E1x(sc))
7547         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7548 
7549     return (bxe_parity_attn(sc, global, print, attn.sig));
7550 }
7551 
7552 static void
7553 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7554                          uint32_t         attn)
7555 {
7556     uint32_t val;
7557 
7558     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7559         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7560         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7561         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7562             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7563         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7564             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7565         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7566             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7567         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7568             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7569         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7570             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7571         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7572             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7573         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7574             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7575         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7576             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7577         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7578             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7579     }
7580 
7581     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7582         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7583         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7584         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7585             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7586         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7587             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7588         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7589             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7590         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7591             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7592         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7593             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7594         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7595             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7596     }
7597 
7598     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7599                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7600         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7601               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7602                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7603     }
7604 }
7605 
7606 static void
7607 bxe_e1h_disable(struct bxe_softc *sc)
7608 {
7609     int port = SC_PORT(sc);
7610 
7611     bxe_tx_disable(sc);
7612 
7613     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7614 }
7615 
7616 static void
7617 bxe_e1h_enable(struct bxe_softc *sc)
7618 {
7619     int port = SC_PORT(sc);
7620 
7621     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7622 
7623     // XXX bxe_tx_enable(sc);
7624 }
7625 
7626 /*
7627  * called due to MCP event (on pmf):
7628  *   reread new bandwidth configuration
7629  *   configure FW
7630  *   notify others function about the change
7631  */
7632 static void
7633 bxe_config_mf_bw(struct bxe_softc *sc)
7634 {
7635     if (sc->link_vars.link_up) {
7636         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7637         // XXX bxe_link_sync_notify(sc);
7638     }
7639 
7640     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7641 }
7642 
7643 static void
7644 bxe_set_mf_bw(struct bxe_softc *sc)
7645 {
7646     bxe_config_mf_bw(sc);
7647     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7648 }
7649 
7650 static void
7651 bxe_handle_eee_event(struct bxe_softc *sc)
7652 {
7653     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7654     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7655 }
7656 
7657 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7658 
7659 static void
7660 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7661 {
7662     struct eth_stats_info *ether_stat =
7663         &sc->sp->drv_info_to_mcp.ether_stat;
7664 
7665     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7666             ETH_STAT_INFO_VERSION_LEN);
7667 
7668     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7669     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7670                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7671                                           ether_stat->mac_local + MAC_PAD,
7672                                           MAC_PAD, ETH_ALEN);
7673 
7674     ether_stat->mtu_size = sc->mtu;
7675 
7676     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7677     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7678         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7679     }
7680 
7681     // XXX ether_stat->feature_flags |= ???;
7682 
7683     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7684 
7685     ether_stat->txq_size = sc->tx_ring_size;
7686     ether_stat->rxq_size = sc->rx_ring_size;
7687 }
7688 
7689 static void
7690 bxe_handle_drv_info_req(struct bxe_softc *sc)
7691 {
7692     enum drv_info_opcode op_code;
7693     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7694 
7695     /* if drv_info version supported by MFW doesn't match - send NACK */
7696     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7697         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7698         return;
7699     }
7700 
7701     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7702                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7703 
7704     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7705 
7706     switch (op_code) {
7707     case ETH_STATS_OPCODE:
7708         bxe_drv_info_ether_stat(sc);
7709         break;
7710     case FCOE_STATS_OPCODE:
7711     case ISCSI_STATS_OPCODE:
7712     default:
7713         /* if op code isn't supported - send NACK */
7714         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7715         return;
7716     }
7717 
7718     /*
7719      * If we got drv_info attn from MFW then these fields are defined in
7720      * shmem2 for sure
7721      */
7722     SHMEM2_WR(sc, drv_info_host_addr_lo,
7723               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7724     SHMEM2_WR(sc, drv_info_host_addr_hi,
7725               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7726 
7727     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7728 }
7729 
7730 static void
7731 bxe_dcc_event(struct bxe_softc *sc,
7732               uint32_t         dcc_event)
7733 {
7734     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7735 
7736     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7737         /*
7738          * This is the only place besides the function initialization
7739          * where the sc->flags can change so it is done without any
7740          * locks
7741          */
7742         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7743             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7744             sc->flags |= BXE_MF_FUNC_DIS;
7745             bxe_e1h_disable(sc);
7746         } else {
7747             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7748             sc->flags &= ~BXE_MF_FUNC_DIS;
7749             bxe_e1h_enable(sc);
7750         }
7751         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7752     }
7753 
7754     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7755         bxe_config_mf_bw(sc);
7756         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7757     }
7758 
7759     /* Report results to MCP */
7760     if (dcc_event)
7761         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7762     else
7763         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7764 }
7765 
7766 static void
7767 bxe_pmf_update(struct bxe_softc *sc)
7768 {
7769     int port = SC_PORT(sc);
7770     uint32_t val;
7771 
7772     sc->port.pmf = 1;
7773     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7774 
7775     /*
7776      * We need the mb() to ensure the ordering between the writing to
7777      * sc->port.pmf here and reading it from the bxe_periodic_task().
7778      */
7779     mb();
7780 
7781     /* queue a periodic task */
7782     // XXX schedule task...
7783 
7784     // XXX bxe_dcbx_pmf_update(sc);
7785 
7786     /* enable nig attention */
7787     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7788     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7789         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7790         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7791     } else if (!CHIP_IS_E1x(sc)) {
7792         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7793         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7794     }
7795 
7796     bxe_stats_handle(sc, STATS_EVENT_PMF);
7797 }
7798 
7799 static int
7800 bxe_mc_assert(struct bxe_softc *sc)
7801 {
7802     char last_idx;
7803     int i, rc = 0;
7804     uint32_t row0, row1, row2, row3;
7805 
7806     /* XSTORM */
7807     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7808     if (last_idx)
7809         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7810 
7811     /* print the asserts */
7812     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7813 
7814         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7815         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7816         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7817         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7818 
7819         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7820             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7821                   i, row3, row2, row1, row0);
7822             rc++;
7823         } else {
7824             break;
7825         }
7826     }
7827 
7828     /* TSTORM */
7829     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7830     if (last_idx) {
7831         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7832     }
7833 
7834     /* print the asserts */
7835     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7836 
7837         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7838         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7839         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7840         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7841 
7842         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7843             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7844                   i, row3, row2, row1, row0);
7845             rc++;
7846         } else {
7847             break;
7848         }
7849     }
7850 
7851     /* CSTORM */
7852     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7853     if (last_idx) {
7854         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7855     }
7856 
7857     /* print the asserts */
7858     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7859 
7860         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7861         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7862         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7863         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7864 
7865         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7866             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7867                   i, row3, row2, row1, row0);
7868             rc++;
7869         } else {
7870             break;
7871         }
7872     }
7873 
7874     /* USTORM */
7875     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7876     if (last_idx) {
7877         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7878     }
7879 
7880     /* print the asserts */
7881     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7882 
7883         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7884         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7885         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7886         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7887 
7888         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7889             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7890                   i, row3, row2, row1, row0);
7891             rc++;
7892         } else {
7893             break;
7894         }
7895     }
7896 
7897     return (rc);
7898 }
7899 
7900 static void
7901 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7902                          uint32_t         attn)
7903 {
7904     int func = SC_FUNC(sc);
7905     uint32_t val;
7906 
7907     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7908 
7909         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7910 
7911             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7912             bxe_read_mf_cfg(sc);
7913             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7914                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7915             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7916 
7917             if (val & DRV_STATUS_DCC_EVENT_MASK)
7918                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7919 
7920             if (val & DRV_STATUS_SET_MF_BW)
7921                 bxe_set_mf_bw(sc);
7922 
7923             if (val & DRV_STATUS_DRV_INFO_REQ)
7924                 bxe_handle_drv_info_req(sc);
7925 
7926             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7927                 bxe_pmf_update(sc);
7928 
7929             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7930                 bxe_handle_eee_event(sc);
7931 
7932             if (sc->link_vars.periodic_flags &
7933                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7934                 /* sync with link */
7935 		bxe_acquire_phy_lock(sc);
7936                 sc->link_vars.periodic_flags &=
7937                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7938 		bxe_release_phy_lock(sc);
7939                 if (IS_MF(sc))
7940                     ; // XXX bxe_link_sync_notify(sc);
7941                 bxe_link_report(sc);
7942             }
7943 
7944             /*
7945              * Always call it here: bxe_link_report() will
7946              * prevent the link indication duplication.
7947              */
7948             bxe_link_status_update(sc);
7949 
7950         } else if (attn & BXE_MC_ASSERT_BITS) {
7951 
7952             BLOGE(sc, "MC assert!\n");
7953             bxe_mc_assert(sc);
7954             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
7955             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
7956             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
7957             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
7958             bxe_panic(sc, ("MC assert!\n"));
7959 
7960         } else if (attn & BXE_MCP_ASSERT) {
7961 
7962             BLOGE(sc, "MCP assert!\n");
7963             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
7964             // XXX bxe_fw_dump(sc);
7965 
7966         } else {
7967             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
7968         }
7969     }
7970 
7971     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
7972         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
7973         if (attn & BXE_GRC_TIMEOUT) {
7974             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
7975             BLOGE(sc, "GRC time-out 0x%08x\n", val);
7976         }
7977         if (attn & BXE_GRC_RSV) {
7978             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
7979             BLOGE(sc, "GRC reserved 0x%08x\n", val);
7980         }
7981         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
7982     }
7983 }
7984 
7985 static void
7986 bxe_attn_int_deasserted2(struct bxe_softc *sc,
7987                          uint32_t         attn)
7988 {
7989     int port = SC_PORT(sc);
7990     int reg_offset;
7991     uint32_t val0, mask0, val1, mask1;
7992     uint32_t val;
7993 
7994     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
7995         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
7996         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
7997         /* CFC error attention */
7998         if (val & 0x2) {
7999             BLOGE(sc, "FATAL error from CFC\n");
8000         }
8001     }
8002 
8003     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8004         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8005         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8006         /* RQ_USDMDP_FIFO_OVERFLOW */
8007         if (val & 0x18000) {
8008             BLOGE(sc, "FATAL error from PXP\n");
8009         }
8010 
8011         if (!CHIP_IS_E1x(sc)) {
8012             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8013             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8014         }
8015     }
8016 
8017 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8018 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8019 
8020     if (attn & AEU_PXP2_HW_INT_BIT) {
8021         /*  CQ47854 workaround do not panic on
8022          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8023          */
8024         if (!CHIP_IS_E1x(sc)) {
8025             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8026             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8027             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8028             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8029             /*
8030              * If the only PXP2_EOP_ERROR_BIT is set in
8031              * STS0 and STS1 - clear it
8032              *
8033              * probably we lose additional attentions between
8034              * STS0 and STS_CLR0, in this case user will not
8035              * be notified about them
8036              */
8037             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8038                 !(val1 & mask1))
8039                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8040 
8041             /* print the register, since no one can restore it */
8042             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8043 
8044             /*
8045              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8046              * then notify
8047              */
8048             if (val0 & PXP2_EOP_ERROR_BIT) {
8049                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8050 
8051                 /*
8052                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8053                  * set then clear attention from PXP2 block without panic
8054                  */
8055                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8056                     ((val1 & mask1) == 0))
8057                     attn &= ~AEU_PXP2_HW_INT_BIT;
8058             }
8059         }
8060     }
8061 
8062     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8063         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8064                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8065 
8066         val = REG_RD(sc, reg_offset);
8067         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8068         REG_WR(sc, reg_offset, val);
8069 
8070         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8071               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8072         bxe_panic(sc, ("HW block attention set2\n"));
8073     }
8074 }
8075 
8076 static void
8077 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8078                          uint32_t         attn)
8079 {
8080     int port = SC_PORT(sc);
8081     int reg_offset;
8082     uint32_t val;
8083 
8084     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8085         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8086         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8087         /* DORQ discard attention */
8088         if (val & 0x2) {
8089             BLOGE(sc, "FATAL error from DORQ\n");
8090         }
8091     }
8092 
8093     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8094         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8095                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8096 
8097         val = REG_RD(sc, reg_offset);
8098         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8099         REG_WR(sc, reg_offset, val);
8100 
8101         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8102               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8103         bxe_panic(sc, ("HW block attention set1\n"));
8104     }
8105 }
8106 
8107 static void
8108 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8109                          uint32_t         attn)
8110 {
8111     int port = SC_PORT(sc);
8112     int reg_offset;
8113     uint32_t val;
8114 
8115     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8116                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8117 
8118     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8119         val = REG_RD(sc, reg_offset);
8120         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8121         REG_WR(sc, reg_offset, val);
8122 
8123         BLOGW(sc, "SPIO5 hw attention\n");
8124 
8125         /* Fan failure attention */
8126         elink_hw_reset_phy(&sc->link_params);
8127         bxe_fan_failure(sc);
8128     }
8129 
8130     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8131 	bxe_acquire_phy_lock(sc);
8132         elink_handle_module_detect_int(&sc->link_params);
8133 	bxe_release_phy_lock(sc);
8134     }
8135 
8136     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8137         val = REG_RD(sc, reg_offset);
8138         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8139         REG_WR(sc, reg_offset, val);
8140 
8141         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8142                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8143     }
8144 }
8145 
8146 static void
8147 bxe_attn_int_deasserted(struct bxe_softc *sc,
8148                         uint32_t         deasserted)
8149 {
8150     struct attn_route attn;
8151     struct attn_route *group_mask;
8152     int port = SC_PORT(sc);
8153     int index;
8154     uint32_t reg_addr;
8155     uint32_t val;
8156     uint32_t aeu_mask;
8157     uint8_t global = FALSE;
8158 
8159     /*
8160      * Need to take HW lock because MCP or other port might also
8161      * try to handle this event.
8162      */
8163     bxe_acquire_alr(sc);
8164 
8165     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8166         /* XXX
8167          * In case of parity errors don't handle attentions so that
8168          * other function would "see" parity errors.
8169          */
8170         sc->recovery_state = BXE_RECOVERY_INIT;
8171         // XXX schedule a recovery task...
8172         /* disable HW interrupts */
8173         bxe_int_disable(sc);
8174         bxe_release_alr(sc);
8175         return;
8176     }
8177 
8178     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8179     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8180     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8181     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8182     if (!CHIP_IS_E1x(sc)) {
8183         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8184     } else {
8185         attn.sig[4] = 0;
8186     }
8187 
8188     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8189           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8190 
8191     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8192         if (deasserted & (1 << index)) {
8193             group_mask = &sc->attn_group[index];
8194 
8195             BLOGD(sc, DBG_INTR,
8196                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8197                   group_mask->sig[0], group_mask->sig[1],
8198                   group_mask->sig[2], group_mask->sig[3],
8199                   group_mask->sig[4]);
8200 
8201             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8202             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8203             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8204             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8205             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8206         }
8207     }
8208 
8209     bxe_release_alr(sc);
8210 
8211     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8212         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8213                     COMMAND_REG_ATTN_BITS_CLR);
8214     } else {
8215         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8216     }
8217 
8218     val = ~deasserted;
8219     BLOGD(sc, DBG_INTR,
8220           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8221           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8222     REG_WR(sc, reg_addr, val);
8223 
8224     if (~sc->attn_state & deasserted) {
8225         BLOGE(sc, "IGU error\n");
8226     }
8227 
8228     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8229                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8230 
8231     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8232 
8233     aeu_mask = REG_RD(sc, reg_addr);
8234 
8235     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8236           aeu_mask, deasserted);
8237     aeu_mask |= (deasserted & 0x3ff);
8238     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8239 
8240     REG_WR(sc, reg_addr, aeu_mask);
8241     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8242 
8243     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8244     sc->attn_state &= ~deasserted;
8245     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8246 }
8247 
8248 static void
8249 bxe_attn_int(struct bxe_softc *sc)
8250 {
8251     /* read local copy of bits */
8252     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8253     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8254     uint32_t attn_state = sc->attn_state;
8255 
8256     /* look for changed bits */
8257     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8258     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8259 
8260     BLOGD(sc, DBG_INTR,
8261           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8262           attn_bits, attn_ack, asserted, deasserted);
8263 
8264     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8265         BLOGE(sc, "BAD attention state\n");
8266     }
8267 
8268     /* handle bits that were raised */
8269     if (asserted) {
8270         bxe_attn_int_asserted(sc, asserted);
8271     }
8272 
8273     if (deasserted) {
8274         bxe_attn_int_deasserted(sc, deasserted);
8275     }
8276 }
8277 
8278 static uint16_t
8279 bxe_update_dsb_idx(struct bxe_softc *sc)
8280 {
8281     struct host_sp_status_block *def_sb = sc->def_sb;
8282     uint16_t rc = 0;
8283 
8284     mb(); /* status block is written to by the chip */
8285 
8286     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8287         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8288         rc |= BXE_DEF_SB_ATT_IDX;
8289     }
8290 
8291     if (sc->def_idx != def_sb->sp_sb.running_index) {
8292         sc->def_idx = def_sb->sp_sb.running_index;
8293         rc |= BXE_DEF_SB_IDX;
8294     }
8295 
8296     mb();
8297 
8298     return (rc);
8299 }
8300 
8301 static inline struct ecore_queue_sp_obj *
8302 bxe_cid_to_q_obj(struct bxe_softc *sc,
8303                  uint32_t         cid)
8304 {
8305     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8306     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8307 }
8308 
8309 static void
8310 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8311 {
8312     struct ecore_mcast_ramrod_params rparam;
8313     int rc;
8314 
8315     memset(&rparam, 0, sizeof(rparam));
8316 
8317     rparam.mcast_obj = &sc->mcast_obj;
8318 
8319     BXE_MCAST_LOCK(sc);
8320 
8321     /* clear pending state for the last command */
8322     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8323 
8324     /* if there are pending mcast commands - send them */
8325     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8326         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8327         if (rc < 0) {
8328             BLOGD(sc, DBG_SP,
8329                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8330         }
8331     }
8332 
8333     BXE_MCAST_UNLOCK(sc);
8334 }
8335 
8336 static void
8337 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8338                               union event_ring_elem *elem)
8339 {
8340     unsigned long ramrod_flags = 0;
8341     int rc = 0;
8342     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8343     struct ecore_vlan_mac_obj *vlan_mac_obj;
8344 
8345     /* always push next commands out, don't wait here */
8346     bit_set(&ramrod_flags, RAMROD_CONT);
8347 
8348     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8349     case ECORE_FILTER_MAC_PENDING:
8350         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8351         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8352         break;
8353 
8354     case ECORE_FILTER_MCAST_PENDING:
8355         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8356         /*
8357          * This is only relevant for 57710 where multicast MACs are
8358          * configured as unicast MACs using the same ramrod.
8359          */
8360         bxe_handle_mcast_eqe(sc);
8361         return;
8362 
8363     default:
8364         BLOGE(sc, "Unsupported classification command: %d\n",
8365               elem->message.data.eth_event.echo);
8366         return;
8367     }
8368 
8369     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8370 
8371     if (rc < 0) {
8372         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8373     } else if (rc > 0) {
8374         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8375     }
8376 }
8377 
8378 static void
8379 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8380                        union event_ring_elem *elem)
8381 {
8382     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8383 
8384     /* send rx_mode command again if was requested */
8385     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8386                                &sc->sp_state)) {
8387         bxe_set_storm_rx_mode(sc);
8388     }
8389 }
8390 
8391 static void
8392 bxe_update_eq_prod(struct bxe_softc *sc,
8393                    uint16_t         prod)
8394 {
8395     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8396     wmb(); /* keep prod updates ordered */
8397 }
8398 
8399 static void
8400 bxe_eq_int(struct bxe_softc *sc)
8401 {
8402     uint16_t hw_cons, sw_cons, sw_prod;
8403     union event_ring_elem *elem;
8404     uint8_t echo;
8405     uint32_t cid;
8406     uint8_t opcode;
8407     int spqe_cnt = 0;
8408     struct ecore_queue_sp_obj *q_obj;
8409     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8410     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8411 
8412     hw_cons = le16toh(*sc->eq_cons_sb);
8413 
8414     /*
8415      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8416      * when we get to the next-page we need to adjust so the loop
8417      * condition below will be met. The next element is the size of a
8418      * regular element and hence incrementing by 1
8419      */
8420     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8421         hw_cons++;
8422     }
8423 
8424     /*
8425      * This function may never run in parallel with itself for a
8426      * specific sc and no need for a read memory barrier here.
8427      */
8428     sw_cons = sc->eq_cons;
8429     sw_prod = sc->eq_prod;
8430 
8431     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8432           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8433 
8434     for (;
8435          sw_cons != hw_cons;
8436          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8437 
8438         elem = &sc->eq[EQ_DESC(sw_cons)];
8439 
8440         /* elem CID originates from FW, actually LE */
8441         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8442         opcode = elem->message.opcode;
8443 
8444         /* handle eq element */
8445         switch (opcode) {
8446 
8447         case EVENT_RING_OPCODE_STAT_QUERY:
8448             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8449                   sc->stats_comp++);
8450             /* nothing to do with stats comp */
8451             goto next_spqe;
8452 
8453         case EVENT_RING_OPCODE_CFC_DEL:
8454             /* handle according to cid range */
8455             /* we may want to verify here that the sc state is HALTING */
8456             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8457             q_obj = bxe_cid_to_q_obj(sc, cid);
8458             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8459                 break;
8460             }
8461             goto next_spqe;
8462 
8463         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8464             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8465             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8466                 break;
8467             }
8468             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8469             goto next_spqe;
8470 
8471         case EVENT_RING_OPCODE_START_TRAFFIC:
8472             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8473             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8474                 break;
8475             }
8476             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8477             goto next_spqe;
8478 
8479         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8480             echo = elem->message.data.function_update_event.echo;
8481             if (echo == SWITCH_UPDATE) {
8482                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8483                 if (f_obj->complete_cmd(sc, f_obj,
8484                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8485                     break;
8486                 }
8487             }
8488             else {
8489                 BLOGD(sc, DBG_SP,
8490                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8491             }
8492             goto next_spqe;
8493 
8494         case EVENT_RING_OPCODE_FORWARD_SETUP:
8495             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8496             if (q_obj->complete_cmd(sc, q_obj,
8497                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8498                 break;
8499             }
8500             goto next_spqe;
8501 
8502         case EVENT_RING_OPCODE_FUNCTION_START:
8503             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8504             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8505                 break;
8506             }
8507             goto next_spqe;
8508 
8509         case EVENT_RING_OPCODE_FUNCTION_STOP:
8510             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8511             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8512                 break;
8513             }
8514             goto next_spqe;
8515         }
8516 
8517         switch (opcode | sc->state) {
8518         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8519         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8520             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8521             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8522             rss_raw->clear_pending(rss_raw);
8523             break;
8524 
8525         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8526         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8527         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8528         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8529         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8530         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8531             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8532             bxe_handle_classification_eqe(sc, elem);
8533             break;
8534 
8535         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8536         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8537         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8538             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8539             bxe_handle_mcast_eqe(sc);
8540             break;
8541 
8542         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8543         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8544         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8545             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8546             bxe_handle_rx_mode_eqe(sc, elem);
8547             break;
8548 
8549         default:
8550             /* unknown event log error and continue */
8551             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8552                   elem->message.opcode, sc->state);
8553         }
8554 
8555 next_spqe:
8556         spqe_cnt++;
8557     } /* for */
8558 
8559     mb();
8560     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8561 
8562     sc->eq_cons = sw_cons;
8563     sc->eq_prod = sw_prod;
8564 
8565     /* make sure that above mem writes were issued towards the memory */
8566     wmb();
8567 
8568     /* update producer */
8569     bxe_update_eq_prod(sc, sc->eq_prod);
8570 }
8571 
8572 static void
8573 bxe_handle_sp_tq(void *context,
8574                  int  pending)
8575 {
8576     struct bxe_softc *sc = (struct bxe_softc *)context;
8577     uint16_t status;
8578 
8579     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8580 
8581     /* what work needs to be performed? */
8582     status = bxe_update_dsb_idx(sc);
8583 
8584     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8585 
8586     /* HW attentions */
8587     if (status & BXE_DEF_SB_ATT_IDX) {
8588         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8589         bxe_attn_int(sc);
8590         status &= ~BXE_DEF_SB_ATT_IDX;
8591     }
8592 
8593     /* SP events: STAT_QUERY and others */
8594     if (status & BXE_DEF_SB_IDX) {
8595         /* handle EQ completions */
8596         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8597         bxe_eq_int(sc);
8598         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8599                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8600         status &= ~BXE_DEF_SB_IDX;
8601     }
8602 
8603     /* if status is non zero then something went wrong */
8604     if (__predict_false(status)) {
8605         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8606     }
8607 
8608     /* ack status block only if something was actually handled */
8609     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8610                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8611 
8612     /*
8613      * Must be called after the EQ processing (since eq leads to sriov
8614      * ramrod completion flows).
8615      * This flow may have been scheduled by the arrival of a ramrod
8616      * completion, or by the sriov code rescheduling itself.
8617      */
8618     // XXX bxe_iov_sp_task(sc);
8619 
8620 }
8621 
8622 static void
8623 bxe_handle_fp_tq(void *context,
8624                  int  pending)
8625 {
8626     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8627     struct bxe_softc *sc = fp->sc;
8628     uint8_t more_tx = FALSE;
8629     uint8_t more_rx = FALSE;
8630 
8631     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8632 
8633     /* XXX
8634      * IFF_DRV_RUNNING state can't be checked here since we process
8635      * slowpath events on a client queue during setup. Instead
8636      * we need to add a "process/continue" flag here that the driver
8637      * can use to tell the task here not to do anything.
8638      */
8639 
8640     /* update the fastpath index */
8641     bxe_update_fp_sb_idx(fp);
8642 
8643     /* XXX add loop here if ever support multiple tx CoS */
8644     /* fp->txdata[cos] */
8645     if (bxe_has_tx_work(fp)) {
8646         BXE_FP_TX_LOCK(fp);
8647         more_tx = bxe_txeof(sc, fp);
8648         BXE_FP_TX_UNLOCK(fp);
8649     }
8650 
8651     if (bxe_has_rx_work(fp)) {
8652         more_rx = bxe_rxeof(sc, fp);
8653     }
8654 
8655     if (more_rx /*|| more_tx*/) {
8656         /* still more work to do */
8657         taskqueue_enqueue(fp->tq, &fp->tq_task);
8658         return;
8659     }
8660 
8661     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8662                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8663 }
8664 
8665 static void
8666 bxe_task_fp(struct bxe_fastpath *fp)
8667 {
8668     struct bxe_softc *sc = fp->sc;
8669     uint8_t more_tx = FALSE;
8670     uint8_t more_rx = FALSE;
8671 
8672     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8673 
8674     /* update the fastpath index */
8675     bxe_update_fp_sb_idx(fp);
8676 
8677     /* XXX add loop here if ever support multiple tx CoS */
8678     /* fp->txdata[cos] */
8679     if (bxe_has_tx_work(fp)) {
8680         BXE_FP_TX_LOCK(fp);
8681         more_tx = bxe_txeof(sc, fp);
8682         BXE_FP_TX_UNLOCK(fp);
8683     }
8684 
8685     if (bxe_has_rx_work(fp)) {
8686         more_rx = bxe_rxeof(sc, fp);
8687     }
8688 
8689     if (more_rx /*|| more_tx*/) {
8690         /* still more work to do, bail out if this ISR and process later */
8691         taskqueue_enqueue(fp->tq, &fp->tq_task);
8692         return;
8693     }
8694 
8695     /*
8696      * Here we write the fastpath index taken before doing any tx or rx work.
8697      * It is very well possible other hw events occurred up to this point and
8698      * they were actually processed accordingly above. Since we're going to
8699      * write an older fastpath index, an interrupt is coming which we might
8700      * not do any work in.
8701      */
8702     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8703                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8704 }
8705 
8706 /*
8707  * Legacy interrupt entry point.
8708  *
8709  * Verifies that the controller generated the interrupt and
8710  * then calls a separate routine to handle the various
8711  * interrupt causes: link, RX, and TX.
8712  */
8713 static void
8714 bxe_intr_legacy(void *xsc)
8715 {
8716     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8717     struct bxe_fastpath *fp;
8718     uint16_t status, mask;
8719     int i;
8720 
8721     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8722 
8723     /*
8724      * 0 for ustorm, 1 for cstorm
8725      * the bits returned from ack_int() are 0-15
8726      * bit 0 = attention status block
8727      * bit 1 = fast path status block
8728      * a mask of 0x2 or more = tx/rx event
8729      * a mask of 1 = slow path event
8730      */
8731 
8732     status = bxe_ack_int(sc);
8733 
8734     /* the interrupt is not for us */
8735     if (__predict_false(status == 0)) {
8736         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8737         return;
8738     }
8739 
8740     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8741 
8742     FOR_EACH_ETH_QUEUE(sc, i) {
8743         fp = &sc->fp[i];
8744         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8745         if (status & mask) {
8746             /* acknowledge and disable further fastpath interrupts */
8747             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8748             bxe_task_fp(fp);
8749             status &= ~mask;
8750         }
8751     }
8752 
8753     if (__predict_false(status & 0x1)) {
8754         /* acknowledge and disable further slowpath interrupts */
8755         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8756 
8757         /* schedule slowpath handler */
8758         taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8759 
8760         status &= ~0x1;
8761     }
8762 
8763     if (__predict_false(status)) {
8764         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8765     }
8766 }
8767 
8768 /* slowpath interrupt entry point */
8769 static void
8770 bxe_intr_sp(void *xsc)
8771 {
8772     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8773 
8774     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8775 
8776     /* acknowledge and disable further slowpath interrupts */
8777     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8778 
8779     /* schedule slowpath handler */
8780     taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8781 }
8782 
8783 /* fastpath interrupt entry point */
8784 static void
8785 bxe_intr_fp(void *xfp)
8786 {
8787     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8788     struct bxe_softc *sc = fp->sc;
8789 
8790     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8791 
8792     BLOGD(sc, DBG_INTR,
8793           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8794           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8795 
8796     /* acknowledge and disable further fastpath interrupts */
8797     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8798 
8799     bxe_task_fp(fp);
8800 }
8801 
8802 /* Release all interrupts allocated by the driver. */
8803 static void
8804 bxe_interrupt_free(struct bxe_softc *sc)
8805 {
8806     int i;
8807 
8808     switch (sc->interrupt_mode) {
8809     case INTR_MODE_INTX:
8810         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8811         if (sc->intr[0].resource != NULL) {
8812             bus_release_resource(sc->dev,
8813                                  SYS_RES_IRQ,
8814                                  sc->intr[0].rid,
8815                                  sc->intr[0].resource);
8816         }
8817         break;
8818     case INTR_MODE_MSI:
8819         for (i = 0; i < sc->intr_count; i++) {
8820             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8821             if (sc->intr[i].resource && sc->intr[i].rid) {
8822                 bus_release_resource(sc->dev,
8823                                      SYS_RES_IRQ,
8824                                      sc->intr[i].rid,
8825                                      sc->intr[i].resource);
8826             }
8827         }
8828         pci_release_msi(sc->dev);
8829         break;
8830     case INTR_MODE_MSIX:
8831         for (i = 0; i < sc->intr_count; i++) {
8832             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8833             if (sc->intr[i].resource && sc->intr[i].rid) {
8834                 bus_release_resource(sc->dev,
8835                                      SYS_RES_IRQ,
8836                                      sc->intr[i].rid,
8837                                      sc->intr[i].resource);
8838             }
8839         }
8840         pci_release_msi(sc->dev);
8841         break;
8842     default:
8843         /* nothing to do as initial allocation failed */
8844         break;
8845     }
8846 }
8847 
8848 /*
8849  * This function determines and allocates the appropriate
8850  * interrupt based on system capabilites and user request.
8851  *
8852  * The user may force a particular interrupt mode, specify
8853  * the number of receive queues, specify the method for
8854  * distribuitng received frames to receive queues, or use
8855  * the default settings which will automatically select the
8856  * best supported combination.  In addition, the OS may or
8857  * may not support certain combinations of these settings.
8858  * This routine attempts to reconcile the settings requested
8859  * by the user with the capabilites available from the system
8860  * to select the optimal combination of features.
8861  *
8862  * Returns:
8863  *   0 = Success, !0 = Failure.
8864  */
8865 static int
8866 bxe_interrupt_alloc(struct bxe_softc *sc)
8867 {
8868     int msix_count = 0;
8869     int msi_count = 0;
8870     int num_requested = 0;
8871     int num_allocated = 0;
8872     int rid, i, j;
8873     int rc;
8874 
8875     /* get the number of available MSI/MSI-X interrupts from the OS */
8876     if (sc->interrupt_mode > 0) {
8877         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8878             msix_count = pci_msix_count(sc->dev);
8879         }
8880 
8881         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8882             msi_count = pci_msi_count(sc->dev);
8883         }
8884 
8885         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8886               msi_count, msix_count);
8887     }
8888 
8889     do { /* try allocating MSI-X interrupt resources (at least 2) */
8890         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8891             break;
8892         }
8893 
8894         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8895             (msix_count < 2)) {
8896             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8897             break;
8898         }
8899 
8900         /* ask for the necessary number of MSI-X vectors */
8901         num_requested = min((sc->num_queues + 1), msix_count);
8902 
8903         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8904 
8905         num_allocated = num_requested;
8906         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8907             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8908             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8909             break;
8910         }
8911 
8912         if (num_allocated < 2) { /* possible? */
8913             BLOGE(sc, "MSI-X allocation less than 2!\n");
8914             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8915             pci_release_msi(sc->dev);
8916             break;
8917         }
8918 
8919         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8920               num_requested, num_allocated);
8921 
8922         /* best effort so use the number of vectors allocated to us */
8923         sc->intr_count = num_allocated;
8924         sc->num_queues = num_allocated - 1;
8925 
8926         rid = 1; /* initial resource identifier */
8927 
8928         /* allocate the MSI-X vectors */
8929         for (i = 0; i < num_allocated; i++) {
8930             sc->intr[i].rid = (rid + i);
8931 
8932             if ((sc->intr[i].resource =
8933                  bus_alloc_resource_any(sc->dev,
8934                                         SYS_RES_IRQ,
8935                                         &sc->intr[i].rid,
8936                                         RF_ACTIVE)) == NULL) {
8937                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8938                       i, (rid + i));
8939 
8940                 for (j = (i - 1); j >= 0; j--) {
8941                     bus_release_resource(sc->dev,
8942                                          SYS_RES_IRQ,
8943                                          sc->intr[j].rid,
8944                                          sc->intr[j].resource);
8945                 }
8946 
8947                 sc->intr_count = 0;
8948                 sc->num_queues = 0;
8949                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8950                 pci_release_msi(sc->dev);
8951                 break;
8952             }
8953 
8954             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
8955         }
8956     } while (0);
8957 
8958     do { /* try allocating MSI vector resources (at least 2) */
8959         if (sc->interrupt_mode != INTR_MODE_MSI) {
8960             break;
8961         }
8962 
8963         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
8964             (msi_count < 1)) {
8965             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8966             break;
8967         }
8968 
8969         /* ask for a single MSI vector */
8970         num_requested = 1;
8971 
8972         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
8973 
8974         num_allocated = num_requested;
8975         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
8976             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
8977             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8978             break;
8979         }
8980 
8981         if (num_allocated != 1) { /* possible? */
8982             BLOGE(sc, "MSI allocation is not 1!\n");
8983             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8984             pci_release_msi(sc->dev);
8985             break;
8986         }
8987 
8988         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
8989               num_requested, num_allocated);
8990 
8991         /* best effort so use the number of vectors allocated to us */
8992         sc->intr_count = num_allocated;
8993         sc->num_queues = num_allocated;
8994 
8995         rid = 1; /* initial resource identifier */
8996 
8997         sc->intr[0].rid = rid;
8998 
8999         if ((sc->intr[0].resource =
9000              bus_alloc_resource_any(sc->dev,
9001                                     SYS_RES_IRQ,
9002                                     &sc->intr[0].rid,
9003                                     RF_ACTIVE)) == NULL) {
9004             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9005             sc->intr_count = 0;
9006             sc->num_queues = 0;
9007             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9008             pci_release_msi(sc->dev);
9009             break;
9010         }
9011 
9012         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9013     } while (0);
9014 
9015     do { /* try allocating INTx vector resources */
9016         if (sc->interrupt_mode != INTR_MODE_INTX) {
9017             break;
9018         }
9019 
9020         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9021 
9022         /* only one vector for INTx */
9023         sc->intr_count = 1;
9024         sc->num_queues = 1;
9025 
9026         rid = 0; /* initial resource identifier */
9027 
9028         sc->intr[0].rid = rid;
9029 
9030         if ((sc->intr[0].resource =
9031              bus_alloc_resource_any(sc->dev,
9032                                     SYS_RES_IRQ,
9033                                     &sc->intr[0].rid,
9034                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9035             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9036             sc->intr_count = 0;
9037             sc->num_queues = 0;
9038             sc->interrupt_mode = -1; /* Failed! */
9039             break;
9040         }
9041 
9042         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9043     } while (0);
9044 
9045     if (sc->interrupt_mode == -1) {
9046         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9047         rc = 1;
9048     } else {
9049         BLOGD(sc, DBG_LOAD,
9050               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9051               sc->interrupt_mode, sc->num_queues);
9052         rc = 0;
9053     }
9054 
9055     return (rc);
9056 }
9057 
9058 static void
9059 bxe_interrupt_detach(struct bxe_softc *sc)
9060 {
9061     struct bxe_fastpath *fp;
9062     int i;
9063 
9064     /* release interrupt resources */
9065     for (i = 0; i < sc->intr_count; i++) {
9066         if (sc->intr[i].resource && sc->intr[i].tag) {
9067             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9068             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9069         }
9070     }
9071 
9072     for (i = 0; i < sc->num_queues; i++) {
9073         fp = &sc->fp[i];
9074         if (fp->tq) {
9075             taskqueue_drain(fp->tq, &fp->tq_task);
9076             taskqueue_drain(fp->tq, &fp->tx_task);
9077             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9078                 NULL))
9079                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9080             taskqueue_free(fp->tq);
9081             fp->tq = NULL;
9082         }
9083     }
9084 
9085 
9086     if (sc->sp_tq) {
9087         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9088         taskqueue_free(sc->sp_tq);
9089         sc->sp_tq = NULL;
9090     }
9091 }
9092 
9093 /*
9094  * Enables interrupts and attach to the ISR.
9095  *
9096  * When using multiple MSI/MSI-X vectors the first vector
9097  * is used for slowpath operations while all remaining
9098  * vectors are used for fastpath operations.  If only a
9099  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9100  * ISR must look for both slowpath and fastpath completions.
9101  */
9102 static int
9103 bxe_interrupt_attach(struct bxe_softc *sc)
9104 {
9105     struct bxe_fastpath *fp;
9106     int rc = 0;
9107     int i;
9108 
9109     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9110              "bxe%d_sp_tq", sc->unit);
9111     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9112     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9113                                       taskqueue_thread_enqueue,
9114                                       &sc->sp_tq);
9115     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9116                             "%s", sc->sp_tq_name);
9117 
9118 
9119     for (i = 0; i < sc->num_queues; i++) {
9120         fp = &sc->fp[i];
9121         snprintf(fp->tq_name, sizeof(fp->tq_name),
9122                  "bxe%d_fp%d_tq", sc->unit, i);
9123         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9124         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9125         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9126                                        taskqueue_thread_enqueue,
9127                                        &fp->tq);
9128         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9129             bxe_tx_mq_start_deferred, fp);
9130         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9131                                 "%s", fp->tq_name);
9132     }
9133 
9134     /* setup interrupt handlers */
9135     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9136         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9137 
9138         /*
9139          * Setup the interrupt handler. Note that we pass the driver instance
9140          * to the interrupt handler for the slowpath.
9141          */
9142         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9143                                  (INTR_TYPE_NET | INTR_MPSAFE),
9144                                  NULL, bxe_intr_sp, sc,
9145                                  &sc->intr[0].tag)) != 0) {
9146             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9147             goto bxe_interrupt_attach_exit;
9148         }
9149 
9150         bus_describe_intr(sc->dev, sc->intr[0].resource,
9151                           sc->intr[0].tag, "sp");
9152 
9153         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9154 
9155         /* initialize the fastpath vectors (note the first was used for sp) */
9156         for (i = 0; i < sc->num_queues; i++) {
9157             fp = &sc->fp[i];
9158             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9159 
9160             /*
9161              * Setup the interrupt handler. Note that we pass the
9162              * fastpath context to the interrupt handler in this
9163              * case.
9164              */
9165             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9166                                      (INTR_TYPE_NET | INTR_MPSAFE),
9167                                      NULL, bxe_intr_fp, fp,
9168                                      &sc->intr[i + 1].tag)) != 0) {
9169                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9170                       (i + 1), rc);
9171                 goto bxe_interrupt_attach_exit;
9172             }
9173 
9174             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9175                               sc->intr[i + 1].tag, "fp%02d", i);
9176 
9177             /* bind the fastpath instance to a cpu */
9178             if (sc->num_queues > 1) {
9179                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9180             }
9181 
9182             fp->state = BXE_FP_STATE_IRQ;
9183         }
9184     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9185         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9186 
9187         /*
9188          * Setup the interrupt handler. Note that we pass the
9189          * driver instance to the interrupt handler which
9190          * will handle both the slowpath and fastpath.
9191          */
9192         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9193                                  (INTR_TYPE_NET | INTR_MPSAFE),
9194                                  NULL, bxe_intr_legacy, sc,
9195                                  &sc->intr[0].tag)) != 0) {
9196             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9197             goto bxe_interrupt_attach_exit;
9198         }
9199 
9200     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9201         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9202 
9203         /*
9204          * Setup the interrupt handler. Note that we pass the
9205          * driver instance to the interrupt handler which
9206          * will handle both the slowpath and fastpath.
9207          */
9208         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9209                                  (INTR_TYPE_NET | INTR_MPSAFE),
9210                                  NULL, bxe_intr_legacy, sc,
9211                                  &sc->intr[0].tag)) != 0) {
9212             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9213             goto bxe_interrupt_attach_exit;
9214         }
9215     }
9216 
9217 bxe_interrupt_attach_exit:
9218 
9219     return (rc);
9220 }
9221 
9222 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9223 static int  bxe_init_hw_common(struct bxe_softc *sc);
9224 static int  bxe_init_hw_port(struct bxe_softc *sc);
9225 static int  bxe_init_hw_func(struct bxe_softc *sc);
9226 static void bxe_reset_common(struct bxe_softc *sc);
9227 static void bxe_reset_port(struct bxe_softc *sc);
9228 static void bxe_reset_func(struct bxe_softc *sc);
9229 static int  bxe_gunzip_init(struct bxe_softc *sc);
9230 static void bxe_gunzip_end(struct bxe_softc *sc);
9231 static int  bxe_init_firmware(struct bxe_softc *sc);
9232 static void bxe_release_firmware(struct bxe_softc *sc);
9233 
9234 static struct
9235 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9236     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9237     .init_hw_cmn      = bxe_init_hw_common,
9238     .init_hw_port     = bxe_init_hw_port,
9239     .init_hw_func     = bxe_init_hw_func,
9240 
9241     .reset_hw_cmn     = bxe_reset_common,
9242     .reset_hw_port    = bxe_reset_port,
9243     .reset_hw_func    = bxe_reset_func,
9244 
9245     .gunzip_init      = bxe_gunzip_init,
9246     .gunzip_end       = bxe_gunzip_end,
9247 
9248     .init_fw          = bxe_init_firmware,
9249     .release_fw       = bxe_release_firmware,
9250 };
9251 
9252 static void
9253 bxe_init_func_obj(struct bxe_softc *sc)
9254 {
9255     sc->dmae_ready = 0;
9256 
9257     ecore_init_func_obj(sc,
9258                         &sc->func_obj,
9259                         BXE_SP(sc, func_rdata),
9260                         BXE_SP_MAPPING(sc, func_rdata),
9261                         BXE_SP(sc, func_afex_rdata),
9262                         BXE_SP_MAPPING(sc, func_afex_rdata),
9263                         &bxe_func_sp_drv);
9264 }
9265 
9266 static int
9267 bxe_init_hw(struct bxe_softc *sc,
9268             uint32_t         load_code)
9269 {
9270     struct ecore_func_state_params func_params = { NULL };
9271     int rc;
9272 
9273     /* prepare the parameters for function state transitions */
9274     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9275 
9276     func_params.f_obj = &sc->func_obj;
9277     func_params.cmd = ECORE_F_CMD_HW_INIT;
9278 
9279     func_params.params.hw_init.load_phase = load_code;
9280 
9281     /*
9282      * Via a plethora of function pointers, we will eventually reach
9283      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9284      */
9285     rc = ecore_func_state_change(sc, &func_params);
9286 
9287     return (rc);
9288 }
9289 
9290 static void
9291 bxe_fill(struct bxe_softc *sc,
9292          uint32_t         addr,
9293          int              fill,
9294          uint32_t         len)
9295 {
9296     uint32_t i;
9297 
9298     if (!(len % 4) && !(addr % 4)) {
9299         for (i = 0; i < len; i += 4) {
9300             REG_WR(sc, (addr + i), fill);
9301         }
9302     } else {
9303         for (i = 0; i < len; i++) {
9304             REG_WR8(sc, (addr + i), fill);
9305         }
9306     }
9307 }
9308 
9309 /* writes FP SP data to FW - data_size in dwords */
9310 static void
9311 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9312                   int              fw_sb_id,
9313                   uint32_t         *sb_data_p,
9314                   uint32_t         data_size)
9315 {
9316     int index;
9317 
9318     for (index = 0; index < data_size; index++) {
9319         REG_WR(sc,
9320                (BAR_CSTRORM_INTMEM +
9321                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9322                 (sizeof(uint32_t) * index)),
9323                *(sb_data_p + index));
9324     }
9325 }
9326 
9327 static void
9328 bxe_zero_fp_sb(struct bxe_softc *sc,
9329                int              fw_sb_id)
9330 {
9331     struct hc_status_block_data_e2 sb_data_e2;
9332     struct hc_status_block_data_e1x sb_data_e1x;
9333     uint32_t *sb_data_p;
9334     uint32_t data_size = 0;
9335 
9336     if (!CHIP_IS_E1x(sc)) {
9337         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9338         sb_data_e2.common.state = SB_DISABLED;
9339         sb_data_e2.common.p_func.vf_valid = FALSE;
9340         sb_data_p = (uint32_t *)&sb_data_e2;
9341         data_size = (sizeof(struct hc_status_block_data_e2) /
9342                      sizeof(uint32_t));
9343     } else {
9344         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9345         sb_data_e1x.common.state = SB_DISABLED;
9346         sb_data_e1x.common.p_func.vf_valid = FALSE;
9347         sb_data_p = (uint32_t *)&sb_data_e1x;
9348         data_size = (sizeof(struct hc_status_block_data_e1x) /
9349                      sizeof(uint32_t));
9350     }
9351 
9352     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9353 
9354     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9355              0, CSTORM_STATUS_BLOCK_SIZE);
9356     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9357              0, CSTORM_SYNC_BLOCK_SIZE);
9358 }
9359 
9360 static void
9361 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9362                   struct hc_sp_status_block_data *sp_sb_data)
9363 {
9364     int i;
9365 
9366     for (i = 0;
9367          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9368          i++) {
9369         REG_WR(sc,
9370                (BAR_CSTRORM_INTMEM +
9371                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9372                 (i * sizeof(uint32_t))),
9373                *((uint32_t *)sp_sb_data + i));
9374     }
9375 }
9376 
9377 static void
9378 bxe_zero_sp_sb(struct bxe_softc *sc)
9379 {
9380     struct hc_sp_status_block_data sp_sb_data;
9381 
9382     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9383 
9384     sp_sb_data.state           = SB_DISABLED;
9385     sp_sb_data.p_func.vf_valid = FALSE;
9386 
9387     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9388 
9389     bxe_fill(sc,
9390              (BAR_CSTRORM_INTMEM +
9391               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9392               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9393     bxe_fill(sc,
9394              (BAR_CSTRORM_INTMEM +
9395               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9396               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9397 }
9398 
9399 static void
9400 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9401                              int                       igu_sb_id,
9402                              int                       igu_seg_id)
9403 {
9404     hc_sm->igu_sb_id      = igu_sb_id;
9405     hc_sm->igu_seg_id     = igu_seg_id;
9406     hc_sm->timer_value    = 0xFF;
9407     hc_sm->time_to_expire = 0xFFFFFFFF;
9408 }
9409 
9410 static void
9411 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9412 {
9413     /* zero out state machine indices */
9414 
9415     /* rx indices */
9416     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9417 
9418     /* tx indices */
9419     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9420     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9421     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9422     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9423 
9424     /* map indices */
9425 
9426     /* rx indices */
9427     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9428         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9429 
9430     /* tx indices */
9431     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9432         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9433     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9434         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9435     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9436         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9437     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9438         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9439 }
9440 
9441 static void
9442 bxe_init_sb(struct bxe_softc *sc,
9443             bus_addr_t       busaddr,
9444             int              vfid,
9445             uint8_t          vf_valid,
9446             int              fw_sb_id,
9447             int              igu_sb_id)
9448 {
9449     struct hc_status_block_data_e2  sb_data_e2;
9450     struct hc_status_block_data_e1x sb_data_e1x;
9451     struct hc_status_block_sm       *hc_sm_p;
9452     uint32_t *sb_data_p;
9453     int igu_seg_id;
9454     int data_size;
9455 
9456     if (CHIP_INT_MODE_IS_BC(sc)) {
9457         igu_seg_id = HC_SEG_ACCESS_NORM;
9458     } else {
9459         igu_seg_id = IGU_SEG_ACCESS_NORM;
9460     }
9461 
9462     bxe_zero_fp_sb(sc, fw_sb_id);
9463 
9464     if (!CHIP_IS_E1x(sc)) {
9465         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9466         sb_data_e2.common.state = SB_ENABLED;
9467         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9468         sb_data_e2.common.p_func.vf_id = vfid;
9469         sb_data_e2.common.p_func.vf_valid = vf_valid;
9470         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9471         sb_data_e2.common.same_igu_sb_1b = TRUE;
9472         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9473         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9474         hc_sm_p = sb_data_e2.common.state_machine;
9475         sb_data_p = (uint32_t *)&sb_data_e2;
9476         data_size = (sizeof(struct hc_status_block_data_e2) /
9477                      sizeof(uint32_t));
9478         bxe_map_sb_state_machines(sb_data_e2.index_data);
9479     } else {
9480         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9481         sb_data_e1x.common.state = SB_ENABLED;
9482         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9483         sb_data_e1x.common.p_func.vf_id = 0xff;
9484         sb_data_e1x.common.p_func.vf_valid = FALSE;
9485         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9486         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9487         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9488         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9489         hc_sm_p = sb_data_e1x.common.state_machine;
9490         sb_data_p = (uint32_t *)&sb_data_e1x;
9491         data_size = (sizeof(struct hc_status_block_data_e1x) /
9492                      sizeof(uint32_t));
9493         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9494     }
9495 
9496     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9497     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9498 
9499     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9500 
9501     /* write indices to HW - PCI guarantees endianity of regpairs */
9502     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9503 }
9504 
9505 static inline uint8_t
9506 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9507 {
9508     if (CHIP_IS_E1x(fp->sc)) {
9509         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9510     } else {
9511         return (fp->cl_id);
9512     }
9513 }
9514 
9515 static inline uint32_t
9516 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9517                            struct bxe_fastpath *fp)
9518 {
9519     uint32_t offset = BAR_USTRORM_INTMEM;
9520 
9521     if (!CHIP_IS_E1x(sc)) {
9522         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9523     } else {
9524         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9525     }
9526 
9527     return (offset);
9528 }
9529 
9530 static void
9531 bxe_init_eth_fp(struct bxe_softc *sc,
9532                 int              idx)
9533 {
9534     struct bxe_fastpath *fp = &sc->fp[idx];
9535     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9536     unsigned long q_type = 0;
9537     int cos;
9538 
9539     fp->sc    = sc;
9540     fp->index = idx;
9541 
9542     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9543     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9544 
9545     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9546                     (SC_L_ID(sc) + idx) :
9547                     /* want client ID same as IGU SB ID for non-E1 */
9548                     fp->igu_sb_id;
9549     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9550 
9551     /* setup sb indices */
9552     if (!CHIP_IS_E1x(sc)) {
9553         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9554         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9555     } else {
9556         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9557         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9558     }
9559 
9560     /* init shortcut */
9561     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9562 
9563     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9564 
9565     /*
9566      * XXX If multiple CoS is ever supported then each fastpath structure
9567      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9568      */
9569     for (cos = 0; cos < sc->max_cos; cos++) {
9570         cids[cos] = idx;
9571     }
9572     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9573 
9574     /* nothing more for a VF to do */
9575     if (IS_VF(sc)) {
9576         return;
9577     }
9578 
9579     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9580                 fp->fw_sb_id, fp->igu_sb_id);
9581 
9582     bxe_update_fp_sb_idx(fp);
9583 
9584     /* Configure Queue State object */
9585     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9586     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9587 
9588     ecore_init_queue_obj(sc,
9589                          &sc->sp_objs[idx].q_obj,
9590                          fp->cl_id,
9591                          cids,
9592                          sc->max_cos,
9593                          SC_FUNC(sc),
9594                          BXE_SP(sc, q_rdata),
9595                          BXE_SP_MAPPING(sc, q_rdata),
9596                          q_type);
9597 
9598     /* configure classification DBs */
9599     ecore_init_mac_obj(sc,
9600                        &sc->sp_objs[idx].mac_obj,
9601                        fp->cl_id,
9602                        idx,
9603                        SC_FUNC(sc),
9604                        BXE_SP(sc, mac_rdata),
9605                        BXE_SP_MAPPING(sc, mac_rdata),
9606                        ECORE_FILTER_MAC_PENDING,
9607                        &sc->sp_state,
9608                        ECORE_OBJ_TYPE_RX_TX,
9609                        &sc->macs_pool);
9610 
9611     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9612           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9613 }
9614 
9615 static inline void
9616 bxe_update_rx_prod(struct bxe_softc    *sc,
9617                    struct bxe_fastpath *fp,
9618                    uint16_t            rx_bd_prod,
9619                    uint16_t            rx_cq_prod,
9620                    uint16_t            rx_sge_prod)
9621 {
9622     struct ustorm_eth_rx_producers rx_prods = { 0 };
9623     uint32_t i;
9624 
9625     /* update producers */
9626     rx_prods.bd_prod  = rx_bd_prod;
9627     rx_prods.cqe_prod = rx_cq_prod;
9628     rx_prods.sge_prod = rx_sge_prod;
9629 
9630     /*
9631      * Make sure that the BD and SGE data is updated before updating the
9632      * producers since FW might read the BD/SGE right after the producer
9633      * is updated.
9634      * This is only applicable for weak-ordered memory model archs such
9635      * as IA-64. The following barrier is also mandatory since FW will
9636      * assumes BDs must have buffers.
9637      */
9638     wmb();
9639 
9640     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9641         REG_WR(sc,
9642                (fp->ustorm_rx_prods_offset + (i * 4)),
9643                ((uint32_t *)&rx_prods)[i]);
9644     }
9645 
9646     wmb(); /* keep prod updates ordered */
9647 
9648     BLOGD(sc, DBG_RX,
9649           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9650           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9651 }
9652 
9653 static void
9654 bxe_init_rx_rings(struct bxe_softc *sc)
9655 {
9656     struct bxe_fastpath *fp;
9657     int i;
9658 
9659     for (i = 0; i < sc->num_queues; i++) {
9660         fp = &sc->fp[i];
9661 
9662         fp->rx_bd_cons = 0;
9663 
9664         /*
9665          * Activate the BD ring...
9666          * Warning, this will generate an interrupt (to the TSTORM)
9667          * so this can only be done after the chip is initialized
9668          */
9669         bxe_update_rx_prod(sc, fp,
9670                            fp->rx_bd_prod,
9671                            fp->rx_cq_prod,
9672                            fp->rx_sge_prod);
9673 
9674         if (i != 0) {
9675             continue;
9676         }
9677 
9678         if (CHIP_IS_E1(sc)) {
9679             REG_WR(sc,
9680                    (BAR_USTRORM_INTMEM +
9681                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9682                    U64_LO(fp->rcq_dma.paddr));
9683             REG_WR(sc,
9684                    (BAR_USTRORM_INTMEM +
9685                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9686                    U64_HI(fp->rcq_dma.paddr));
9687         }
9688     }
9689 }
9690 
9691 static void
9692 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9693 {
9694     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9695     fp->tx_db.data.zero_fill1 = 0;
9696     fp->tx_db.data.prod = 0;
9697 
9698     fp->tx_pkt_prod = 0;
9699     fp->tx_pkt_cons = 0;
9700     fp->tx_bd_prod = 0;
9701     fp->tx_bd_cons = 0;
9702     fp->eth_q_stats.tx_pkts = 0;
9703 }
9704 
9705 static inline void
9706 bxe_init_tx_rings(struct bxe_softc *sc)
9707 {
9708     int i;
9709 
9710     for (i = 0; i < sc->num_queues; i++) {
9711         bxe_init_tx_ring_one(&sc->fp[i]);
9712     }
9713 }
9714 
9715 static void
9716 bxe_init_def_sb(struct bxe_softc *sc)
9717 {
9718     struct host_sp_status_block *def_sb = sc->def_sb;
9719     bus_addr_t mapping = sc->def_sb_dma.paddr;
9720     int igu_sp_sb_index;
9721     int igu_seg_id;
9722     int port = SC_PORT(sc);
9723     int func = SC_FUNC(sc);
9724     int reg_offset, reg_offset_en5;
9725     uint64_t section;
9726     int index, sindex;
9727     struct hc_sp_status_block_data sp_sb_data;
9728 
9729     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9730 
9731     if (CHIP_INT_MODE_IS_BC(sc)) {
9732         igu_sp_sb_index = DEF_SB_IGU_ID;
9733         igu_seg_id = HC_SEG_ACCESS_DEF;
9734     } else {
9735         igu_sp_sb_index = sc->igu_dsb_id;
9736         igu_seg_id = IGU_SEG_ACCESS_DEF;
9737     }
9738 
9739     /* attentions */
9740     section = ((uint64_t)mapping +
9741                offsetof(struct host_sp_status_block, atten_status_block));
9742     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9743     sc->attn_state = 0;
9744 
9745     reg_offset = (port) ?
9746                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9747                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9748     reg_offset_en5 = (port) ?
9749                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9750                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9751 
9752     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9753         /* take care of sig[0]..sig[4] */
9754         for (sindex = 0; sindex < 4; sindex++) {
9755             sc->attn_group[index].sig[sindex] =
9756                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9757         }
9758 
9759         if (!CHIP_IS_E1x(sc)) {
9760             /*
9761              * enable5 is separate from the rest of the registers,
9762              * and the address skip is 4 and not 16 between the
9763              * different groups
9764              */
9765             sc->attn_group[index].sig[4] =
9766                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9767         } else {
9768             sc->attn_group[index].sig[4] = 0;
9769         }
9770     }
9771 
9772     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9773         reg_offset = (port) ?
9774                          HC_REG_ATTN_MSG1_ADDR_L :
9775                          HC_REG_ATTN_MSG0_ADDR_L;
9776         REG_WR(sc, reg_offset, U64_LO(section));
9777         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9778     } else if (!CHIP_IS_E1x(sc)) {
9779         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9780         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9781     }
9782 
9783     section = ((uint64_t)mapping +
9784                offsetof(struct host_sp_status_block, sp_sb));
9785 
9786     bxe_zero_sp_sb(sc);
9787 
9788     /* PCI guarantees endianity of regpair */
9789     sp_sb_data.state           = SB_ENABLED;
9790     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9791     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9792     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9793     sp_sb_data.igu_seg_id      = igu_seg_id;
9794     sp_sb_data.p_func.pf_id    = func;
9795     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9796     sp_sb_data.p_func.vf_id    = 0xff;
9797 
9798     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9799 
9800     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9801 }
9802 
9803 static void
9804 bxe_init_sp_ring(struct bxe_softc *sc)
9805 {
9806     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9807     sc->spq_prod_idx = 0;
9808     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9809     sc->spq_prod_bd = sc->spq;
9810     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9811 }
9812 
9813 static void
9814 bxe_init_eq_ring(struct bxe_softc *sc)
9815 {
9816     union event_ring_elem *elem;
9817     int i;
9818 
9819     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9820         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9821 
9822         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9823                                                  BCM_PAGE_SIZE *
9824                                                  (i % NUM_EQ_PAGES)));
9825         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9826                                                  BCM_PAGE_SIZE *
9827                                                  (i % NUM_EQ_PAGES)));
9828     }
9829 
9830     sc->eq_cons    = 0;
9831     sc->eq_prod    = NUM_EQ_DESC;
9832     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9833 
9834     atomic_store_rel_long(&sc->eq_spq_left,
9835                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9836                                NUM_EQ_DESC) - 1));
9837 }
9838 
9839 static void
9840 bxe_init_internal_common(struct bxe_softc *sc)
9841 {
9842     int i;
9843 
9844     /*
9845      * Zero this manually as its initialization is currently missing
9846      * in the initTool.
9847      */
9848     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9849         REG_WR(sc,
9850                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9851                0);
9852     }
9853 
9854     if (!CHIP_IS_E1x(sc)) {
9855         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9856                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9857     }
9858 }
9859 
9860 static void
9861 bxe_init_internal(struct bxe_softc *sc,
9862                   uint32_t         load_code)
9863 {
9864     switch (load_code) {
9865     case FW_MSG_CODE_DRV_LOAD_COMMON:
9866     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9867         bxe_init_internal_common(sc);
9868         /* no break */
9869 
9870     case FW_MSG_CODE_DRV_LOAD_PORT:
9871         /* nothing to do */
9872         /* no break */
9873 
9874     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9875         /* internal memory per function is initialized inside bxe_pf_init */
9876         break;
9877 
9878     default:
9879         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9880         break;
9881     }
9882 }
9883 
9884 static void
9885 storm_memset_func_cfg(struct bxe_softc                         *sc,
9886                       struct tstorm_eth_function_common_config *tcfg,
9887                       uint16_t                                  abs_fid)
9888 {
9889     uint32_t addr;
9890     size_t size;
9891 
9892     addr = (BAR_TSTRORM_INTMEM +
9893             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9894     size = sizeof(struct tstorm_eth_function_common_config);
9895     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9896 }
9897 
9898 static void
9899 bxe_func_init(struct bxe_softc            *sc,
9900               struct bxe_func_init_params *p)
9901 {
9902     struct tstorm_eth_function_common_config tcfg = { 0 };
9903 
9904     if (CHIP_IS_E1x(sc)) {
9905         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9906     }
9907 
9908     /* Enable the function in the FW */
9909     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9910     storm_memset_func_en(sc, p->func_id, 1);
9911 
9912     /* spq */
9913     if (p->func_flgs & FUNC_FLG_SPQ) {
9914         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9915         REG_WR(sc,
9916                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9917                p->spq_prod);
9918     }
9919 }
9920 
9921 /*
9922  * Calculates the sum of vn_min_rates.
9923  * It's needed for further normalizing of the min_rates.
9924  * Returns:
9925  *   sum of vn_min_rates.
9926  *     or
9927  *   0 - if all the min_rates are 0.
9928  * In the later case fainess algorithm should be deactivated.
9929  * If all min rates are not zero then those that are zeroes will be set to 1.
9930  */
9931 static void
9932 bxe_calc_vn_min(struct bxe_softc       *sc,
9933                 struct cmng_init_input *input)
9934 {
9935     uint32_t vn_cfg;
9936     uint32_t vn_min_rate;
9937     int all_zero = 1;
9938     int vn;
9939 
9940     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9941         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9942         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9943                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9944 
9945         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9946             /* skip hidden VNs */
9947             vn_min_rate = 0;
9948         } else if (!vn_min_rate) {
9949             /* If min rate is zero - set it to 100 */
9950             vn_min_rate = DEF_MIN_RATE;
9951         } else {
9952             all_zero = 0;
9953         }
9954 
9955         input->vnic_min_rate[vn] = vn_min_rate;
9956     }
9957 
9958     /* if ETS or all min rates are zeros - disable fairness */
9959     if (BXE_IS_ETS_ENABLED(sc)) {
9960         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9961         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
9962     } else if (all_zero) {
9963         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9964         BLOGD(sc, DBG_LOAD,
9965               "Fariness disabled (all MIN values are zeroes)\n");
9966     } else {
9967         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9968     }
9969 }
9970 
9971 static inline uint16_t
9972 bxe_extract_max_cfg(struct bxe_softc *sc,
9973                     uint32_t         mf_cfg)
9974 {
9975     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
9976                         FUNC_MF_CFG_MAX_BW_SHIFT);
9977 
9978     if (!max_cfg) {
9979         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
9980         max_cfg = 100;
9981     }
9982 
9983     return (max_cfg);
9984 }
9985 
9986 static void
9987 bxe_calc_vn_max(struct bxe_softc       *sc,
9988                 int                    vn,
9989                 struct cmng_init_input *input)
9990 {
9991     uint16_t vn_max_rate;
9992     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9993     uint32_t max_cfg;
9994 
9995     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9996         vn_max_rate = 0;
9997     } else {
9998         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
9999 
10000         if (IS_MF_SI(sc)) {
10001             /* max_cfg in percents of linkspeed */
10002             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10003         } else { /* SD modes */
10004             /* max_cfg is absolute in 100Mb units */
10005             vn_max_rate = (max_cfg * 100);
10006         }
10007     }
10008 
10009     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10010 
10011     input->vnic_max_rate[vn] = vn_max_rate;
10012 }
10013 
10014 static void
10015 bxe_cmng_fns_init(struct bxe_softc *sc,
10016                   uint8_t          read_cfg,
10017                   uint8_t          cmng_type)
10018 {
10019     struct cmng_init_input input;
10020     int vn;
10021 
10022     memset(&input, 0, sizeof(struct cmng_init_input));
10023 
10024     input.port_rate = sc->link_vars.line_speed;
10025 
10026     if (cmng_type == CMNG_FNS_MINMAX) {
10027         /* read mf conf from shmem */
10028         if (read_cfg) {
10029             bxe_read_mf_cfg(sc);
10030         }
10031 
10032         /* get VN min rate and enable fairness if not 0 */
10033         bxe_calc_vn_min(sc, &input);
10034 
10035         /* get VN max rate */
10036         if (sc->port.pmf) {
10037             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10038                 bxe_calc_vn_max(sc, vn, &input);
10039             }
10040         }
10041 
10042         /* always enable rate shaping and fairness */
10043         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10044 
10045         ecore_init_cmng(&input, &sc->cmng);
10046         return;
10047     }
10048 
10049     /* rate shaping and fairness are disabled */
10050     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10051 }
10052 
10053 static int
10054 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10055 {
10056     if (CHIP_REV_IS_SLOW(sc)) {
10057         return (CMNG_FNS_NONE);
10058     }
10059 
10060     if (IS_MF(sc)) {
10061         return (CMNG_FNS_MINMAX);
10062     }
10063 
10064     return (CMNG_FNS_NONE);
10065 }
10066 
10067 static void
10068 storm_memset_cmng(struct bxe_softc *sc,
10069                   struct cmng_init *cmng,
10070                   uint8_t          port)
10071 {
10072     int vn;
10073     int func;
10074     uint32_t addr;
10075     size_t size;
10076 
10077     addr = (BAR_XSTRORM_INTMEM +
10078             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10079     size = sizeof(struct cmng_struct_per_port);
10080     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10081 
10082     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10083         func = func_by_vn(sc, vn);
10084 
10085         addr = (BAR_XSTRORM_INTMEM +
10086                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10087         size = sizeof(struct rate_shaping_vars_per_vn);
10088         ecore_storm_memset_struct(sc, addr, size,
10089                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10090 
10091         addr = (BAR_XSTRORM_INTMEM +
10092                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10093         size = sizeof(struct fairness_vars_per_vn);
10094         ecore_storm_memset_struct(sc, addr, size,
10095                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10096     }
10097 }
10098 
10099 static void
10100 bxe_pf_init(struct bxe_softc *sc)
10101 {
10102     struct bxe_func_init_params func_init = { 0 };
10103     struct event_ring_data eq_data = { { 0 } };
10104     uint16_t flags;
10105 
10106     if (!CHIP_IS_E1x(sc)) {
10107         /* reset IGU PF statistics: MSIX + ATTN */
10108         /* PF */
10109         REG_WR(sc,
10110                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10111                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10112                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10113                0);
10114         /* ATTN */
10115         REG_WR(sc,
10116                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10117                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10118                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10119                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10120                0);
10121     }
10122 
10123     /* function setup flags */
10124     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10125 
10126     /*
10127      * This flag is relevant for E1x only.
10128      * E2 doesn't have a TPA configuration in a function level.
10129      */
10130     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10131 
10132     func_init.func_flgs = flags;
10133     func_init.pf_id     = SC_FUNC(sc);
10134     func_init.func_id   = SC_FUNC(sc);
10135     func_init.spq_map   = sc->spq_dma.paddr;
10136     func_init.spq_prod  = sc->spq_prod_idx;
10137 
10138     bxe_func_init(sc, &func_init);
10139 
10140     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10141 
10142     /*
10143      * Congestion management values depend on the link rate.
10144      * There is no active link so initial link rate is set to 10Gbps.
10145      * When the link comes up the congestion management values are
10146      * re-calculated according to the actual link rate.
10147      */
10148     sc->link_vars.line_speed = SPEED_10000;
10149     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10150 
10151     /* Only the PMF sets the HW */
10152     if (sc->port.pmf) {
10153         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10154     }
10155 
10156     /* init Event Queue - PCI bus guarantees correct endainity */
10157     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10158     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10159     eq_data.producer     = sc->eq_prod;
10160     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10161     eq_data.sb_id        = DEF_SB_ID;
10162     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10163 }
10164 
10165 static void
10166 bxe_hc_int_enable(struct bxe_softc *sc)
10167 {
10168     int port = SC_PORT(sc);
10169     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10170     uint32_t val = REG_RD(sc, addr);
10171     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10172     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10173                            (sc->intr_count == 1)) ? TRUE : FALSE;
10174     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10175 
10176     if (msix) {
10177         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10178                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10179         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10180                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10181         if (single_msix) {
10182             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10183         }
10184     } else if (msi) {
10185         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10186         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10187                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10188                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10189     } else {
10190         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10191                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10192                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10193                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10194 
10195         if (!CHIP_IS_E1(sc)) {
10196             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10197                   val, port, addr);
10198 
10199             REG_WR(sc, addr, val);
10200 
10201             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10202         }
10203     }
10204 
10205     if (CHIP_IS_E1(sc)) {
10206         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10207     }
10208 
10209     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10210           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10211 
10212     REG_WR(sc, addr, val);
10213 
10214     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10215     mb();
10216 
10217     if (!CHIP_IS_E1(sc)) {
10218         /* init leading/trailing edge */
10219         if (IS_MF(sc)) {
10220             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10221             if (sc->port.pmf) {
10222                 /* enable nig and gpio3 attention */
10223                 val |= 0x1100;
10224             }
10225         } else {
10226             val = 0xffff;
10227         }
10228 
10229         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10230         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10231     }
10232 
10233     /* make sure that interrupts are indeed enabled from here on */
10234     mb();
10235 }
10236 
10237 static void
10238 bxe_igu_int_enable(struct bxe_softc *sc)
10239 {
10240     uint32_t val;
10241     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10242     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10243                            (sc->intr_count == 1)) ? TRUE : FALSE;
10244     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10245 
10246     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10247 
10248     if (msix) {
10249         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10250                  IGU_PF_CONF_SINGLE_ISR_EN);
10251         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10252                 IGU_PF_CONF_ATTN_BIT_EN);
10253         if (single_msix) {
10254             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10255         }
10256     } else if (msi) {
10257         val &= ~IGU_PF_CONF_INT_LINE_EN;
10258         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10259                 IGU_PF_CONF_ATTN_BIT_EN |
10260                 IGU_PF_CONF_SINGLE_ISR_EN);
10261     } else {
10262         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10263         val |= (IGU_PF_CONF_INT_LINE_EN |
10264                 IGU_PF_CONF_ATTN_BIT_EN |
10265                 IGU_PF_CONF_SINGLE_ISR_EN);
10266     }
10267 
10268     /* clean previous status - need to configure igu prior to ack*/
10269     if ((!msix) || single_msix) {
10270         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10271         bxe_ack_int(sc);
10272     }
10273 
10274     val |= IGU_PF_CONF_FUNC_EN;
10275 
10276     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10277           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10278 
10279     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10280 
10281     mb();
10282 
10283     /* init leading/trailing edge */
10284     if (IS_MF(sc)) {
10285         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10286         if (sc->port.pmf) {
10287             /* enable nig and gpio3 attention */
10288             val |= 0x1100;
10289         }
10290     } else {
10291         val = 0xffff;
10292     }
10293 
10294     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10295     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10296 
10297     /* make sure that interrupts are indeed enabled from here on */
10298     mb();
10299 }
10300 
10301 static void
10302 bxe_int_enable(struct bxe_softc *sc)
10303 {
10304     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10305         bxe_hc_int_enable(sc);
10306     } else {
10307         bxe_igu_int_enable(sc);
10308     }
10309 }
10310 
10311 static void
10312 bxe_hc_int_disable(struct bxe_softc *sc)
10313 {
10314     int port = SC_PORT(sc);
10315     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10316     uint32_t val = REG_RD(sc, addr);
10317 
10318     /*
10319      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10320      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10321      * block
10322      */
10323     if (CHIP_IS_E1(sc)) {
10324         /*
10325          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10326          * to prevent from HC sending interrupts after we exit the function
10327          */
10328         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10329 
10330         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10331                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10332                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10333     } else {
10334         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10335                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10336                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10337                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10338     }
10339 
10340     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10341 
10342     /* flush all outstanding writes */
10343     mb();
10344 
10345     REG_WR(sc, addr, val);
10346     if (REG_RD(sc, addr) != val) {
10347         BLOGE(sc, "proper val not read from HC IGU!\n");
10348     }
10349 }
10350 
10351 static void
10352 bxe_igu_int_disable(struct bxe_softc *sc)
10353 {
10354     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10355 
10356     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10357              IGU_PF_CONF_INT_LINE_EN |
10358              IGU_PF_CONF_ATTN_BIT_EN);
10359 
10360     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10361 
10362     /* flush all outstanding writes */
10363     mb();
10364 
10365     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10366     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10367         BLOGE(sc, "proper val not read from IGU!\n");
10368     }
10369 }
10370 
10371 static void
10372 bxe_int_disable(struct bxe_softc *sc)
10373 {
10374     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10375         bxe_hc_int_disable(sc);
10376     } else {
10377         bxe_igu_int_disable(sc);
10378     }
10379 }
10380 
10381 static void
10382 bxe_nic_init(struct bxe_softc *sc,
10383              int              load_code)
10384 {
10385     int i;
10386 
10387     for (i = 0; i < sc->num_queues; i++) {
10388         bxe_init_eth_fp(sc, i);
10389     }
10390 
10391     rmb(); /* ensure status block indices were read */
10392 
10393     bxe_init_rx_rings(sc);
10394     bxe_init_tx_rings(sc);
10395 
10396     if (IS_VF(sc)) {
10397         return;
10398     }
10399 
10400     /* initialize MOD_ABS interrupts */
10401     elink_init_mod_abs_int(sc, &sc->link_vars,
10402                            sc->devinfo.chip_id,
10403                            sc->devinfo.shmem_base,
10404                            sc->devinfo.shmem2_base,
10405                            SC_PORT(sc));
10406 
10407     bxe_init_def_sb(sc);
10408     bxe_update_dsb_idx(sc);
10409     bxe_init_sp_ring(sc);
10410     bxe_init_eq_ring(sc);
10411     bxe_init_internal(sc, load_code);
10412     bxe_pf_init(sc);
10413     bxe_stats_init(sc);
10414 
10415     /* flush all before enabling interrupts */
10416     mb();
10417 
10418     bxe_int_enable(sc);
10419 
10420     /* check for SPIO5 */
10421     bxe_attn_int_deasserted0(sc,
10422                              REG_RD(sc,
10423                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10424                                      SC_PORT(sc)*4)) &
10425                              AEU_INPUTS_ATTN_BITS_SPIO5);
10426 }
10427 
10428 static inline void
10429 bxe_init_objs(struct bxe_softc *sc)
10430 {
10431     /* mcast rules must be added to tx if tx switching is enabled */
10432     ecore_obj_type o_type =
10433         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10434                                          ECORE_OBJ_TYPE_RX;
10435 
10436     /* RX_MODE controlling object */
10437     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10438 
10439     /* multicast configuration controlling object */
10440     ecore_init_mcast_obj(sc,
10441                          &sc->mcast_obj,
10442                          sc->fp[0].cl_id,
10443                          sc->fp[0].index,
10444                          SC_FUNC(sc),
10445                          SC_FUNC(sc),
10446                          BXE_SP(sc, mcast_rdata),
10447                          BXE_SP_MAPPING(sc, mcast_rdata),
10448                          ECORE_FILTER_MCAST_PENDING,
10449                          &sc->sp_state,
10450                          o_type);
10451 
10452     /* Setup CAM credit pools */
10453     ecore_init_mac_credit_pool(sc,
10454                                &sc->macs_pool,
10455                                SC_FUNC(sc),
10456                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10457                                                  VNICS_PER_PATH(sc));
10458 
10459     ecore_init_vlan_credit_pool(sc,
10460                                 &sc->vlans_pool,
10461                                 SC_ABS_FUNC(sc) >> 1,
10462                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10463                                                   VNICS_PER_PATH(sc));
10464 
10465     /* RSS configuration object */
10466     ecore_init_rss_config_obj(sc,
10467                               &sc->rss_conf_obj,
10468                               sc->fp[0].cl_id,
10469                               sc->fp[0].index,
10470                               SC_FUNC(sc),
10471                               SC_FUNC(sc),
10472                               BXE_SP(sc, rss_rdata),
10473                               BXE_SP_MAPPING(sc, rss_rdata),
10474                               ECORE_FILTER_RSS_CONF_PENDING,
10475                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10476 }
10477 
10478 /*
10479  * Initialize the function. This must be called before sending CLIENT_SETUP
10480  * for the first client.
10481  */
10482 static inline int
10483 bxe_func_start(struct bxe_softc *sc)
10484 {
10485     struct ecore_func_state_params func_params = { NULL };
10486     struct ecore_func_start_params *start_params = &func_params.params.start;
10487 
10488     /* Prepare parameters for function state transitions */
10489     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10490 
10491     func_params.f_obj = &sc->func_obj;
10492     func_params.cmd = ECORE_F_CMD_START;
10493 
10494     /* Function parameters */
10495     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10496     start_params->sd_vlan_tag = OVLAN(sc);
10497 
10498     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10499         start_params->network_cos_mode = STATIC_COS;
10500     } else { /* CHIP_IS_E1X */
10501         start_params->network_cos_mode = FW_WRR;
10502     }
10503 
10504     //start_params->gre_tunnel_mode = 0;
10505     //start_params->gre_tunnel_rss  = 0;
10506 
10507     return (ecore_func_state_change(sc, &func_params));
10508 }
10509 
10510 static int
10511 bxe_set_power_state(struct bxe_softc *sc,
10512                     uint8_t          state)
10513 {
10514     uint16_t pmcsr;
10515 
10516     /* If there is no power capability, silently succeed */
10517     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10518         BLOGW(sc, "No power capability\n");
10519         return (0);
10520     }
10521 
10522     pmcsr = pci_read_config(sc->dev,
10523                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10524                             2);
10525 
10526     switch (state) {
10527     case PCI_PM_D0:
10528         pci_write_config(sc->dev,
10529                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10530                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10531 
10532         if (pmcsr & PCIM_PSTAT_DMASK) {
10533             /* delay required during transition out of D3hot */
10534             DELAY(20000);
10535         }
10536 
10537         break;
10538 
10539     case PCI_PM_D3hot:
10540         /* XXX if there are other clients above don't shut down the power */
10541 
10542         /* don't shut down the power for emulation and FPGA */
10543         if (CHIP_REV_IS_SLOW(sc)) {
10544             return (0);
10545         }
10546 
10547         pmcsr &= ~PCIM_PSTAT_DMASK;
10548         pmcsr |= PCIM_PSTAT_D3;
10549 
10550         if (sc->wol) {
10551             pmcsr |= PCIM_PSTAT_PMEENABLE;
10552         }
10553 
10554         pci_write_config(sc->dev,
10555                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10556                          pmcsr, 4);
10557 
10558         /*
10559          * No more memory access after this point until device is brought back
10560          * to D0 state.
10561          */
10562         break;
10563 
10564     default:
10565         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10566             state, pmcsr);
10567         return (-1);
10568     }
10569 
10570     return (0);
10571 }
10572 
10573 
10574 /* return true if succeeded to acquire the lock */
10575 static uint8_t
10576 bxe_trylock_hw_lock(struct bxe_softc *sc,
10577                     uint32_t         resource)
10578 {
10579     uint32_t lock_status;
10580     uint32_t resource_bit = (1 << resource);
10581     int func = SC_FUNC(sc);
10582     uint32_t hw_lock_control_reg;
10583 
10584     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10585 
10586     /* Validating that the resource is within range */
10587     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10588         BLOGD(sc, DBG_LOAD,
10589               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10590               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10591         return (FALSE);
10592     }
10593 
10594     if (func <= 5) {
10595         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10596     } else {
10597         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10598     }
10599 
10600     /* try to acquire the lock */
10601     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10602     lock_status = REG_RD(sc, hw_lock_control_reg);
10603     if (lock_status & resource_bit) {
10604         return (TRUE);
10605     }
10606 
10607     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10608         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10609         lock_status, resource_bit);
10610 
10611     return (FALSE);
10612 }
10613 
10614 /*
10615  * Get the recovery leader resource id according to the engine this function
10616  * belongs to. Currently only only 2 engines is supported.
10617  */
10618 static int
10619 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10620 {
10621     if (SC_PATH(sc)) {
10622         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10623     } else {
10624         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10625     }
10626 }
10627 
10628 /* try to acquire a leader lock for current engine */
10629 static uint8_t
10630 bxe_trylock_leader_lock(struct bxe_softc *sc)
10631 {
10632     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10633 }
10634 
10635 static int
10636 bxe_release_leader_lock(struct bxe_softc *sc)
10637 {
10638     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10639 }
10640 
10641 /* close gates #2, #3 and #4 */
10642 static void
10643 bxe_set_234_gates(struct bxe_softc *sc,
10644                   uint8_t          close)
10645 {
10646     uint32_t val;
10647 
10648     /* gates #2 and #4a are closed/opened for "not E1" only */
10649     if (!CHIP_IS_E1(sc)) {
10650         /* #4 */
10651         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10652         /* #2 */
10653         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10654     }
10655 
10656     /* #3 */
10657     if (CHIP_IS_E1x(sc)) {
10658         /* prevent interrupts from HC on both ports */
10659         val = REG_RD(sc, HC_REG_CONFIG_1);
10660         REG_WR(sc, HC_REG_CONFIG_1,
10661                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10662                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10663 
10664         val = REG_RD(sc, HC_REG_CONFIG_0);
10665         REG_WR(sc, HC_REG_CONFIG_0,
10666                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10667                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10668     } else {
10669         /* Prevent incoming interrupts in IGU */
10670         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10671 
10672         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10673                (!close) ?
10674                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10675                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10676     }
10677 
10678     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10679           close ? "closing" : "opening");
10680 
10681     wmb();
10682 }
10683 
10684 /* poll for pending writes bit, it should get cleared in no more than 1s */
10685 static int
10686 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10687 {
10688     uint32_t cnt = 1000;
10689     uint32_t pend_bits = 0;
10690 
10691     do {
10692         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10693 
10694         if (pend_bits == 0) {
10695             break;
10696         }
10697 
10698         DELAY(1000);
10699     } while (--cnt > 0);
10700 
10701     if (cnt == 0) {
10702         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10703         return (-1);
10704     }
10705 
10706     return (0);
10707 }
10708 
10709 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10710 
10711 static void
10712 bxe_clp_reset_prep(struct bxe_softc *sc,
10713                    uint32_t         *magic_val)
10714 {
10715     /* Do some magic... */
10716     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10717     *magic_val = val & SHARED_MF_CLP_MAGIC;
10718     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10719 }
10720 
10721 /* restore the value of the 'magic' bit */
10722 static void
10723 bxe_clp_reset_done(struct bxe_softc *sc,
10724                    uint32_t         magic_val)
10725 {
10726     /* Restore the 'magic' bit value... */
10727     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10728     MFCFG_WR(sc, shared_mf_config.clp_mb,
10729               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10730 }
10731 
10732 /* prepare for MCP reset, takes care of CLP configurations */
10733 static void
10734 bxe_reset_mcp_prep(struct bxe_softc *sc,
10735                    uint32_t         *magic_val)
10736 {
10737     uint32_t shmem;
10738     uint32_t validity_offset;
10739 
10740     /* set `magic' bit in order to save MF config */
10741     if (!CHIP_IS_E1(sc)) {
10742         bxe_clp_reset_prep(sc, magic_val);
10743     }
10744 
10745     /* get shmem offset */
10746     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10747     validity_offset =
10748         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10749 
10750     /* Clear validity map flags */
10751     if (shmem > 0) {
10752         REG_WR(sc, shmem + validity_offset, 0);
10753     }
10754 }
10755 
10756 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10757 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10758 
10759 static void
10760 bxe_mcp_wait_one(struct bxe_softc *sc)
10761 {
10762     /* special handling for emulation and FPGA (10 times longer) */
10763     if (CHIP_REV_IS_SLOW(sc)) {
10764         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10765     } else {
10766         DELAY((MCP_ONE_TIMEOUT) * 1000);
10767     }
10768 }
10769 
10770 /* initialize shmem_base and waits for validity signature to appear */
10771 static int
10772 bxe_init_shmem(struct bxe_softc *sc)
10773 {
10774     int cnt = 0;
10775     uint32_t val = 0;
10776 
10777     do {
10778         sc->devinfo.shmem_base     =
10779         sc->link_params.shmem_base =
10780             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10781 
10782         if (sc->devinfo.shmem_base) {
10783             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10784             if (val & SHR_MEM_VALIDITY_MB)
10785                 return (0);
10786         }
10787 
10788         bxe_mcp_wait_one(sc);
10789 
10790     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10791 
10792     BLOGE(sc, "BAD MCP validity signature\n");
10793 
10794     return (-1);
10795 }
10796 
10797 static int
10798 bxe_reset_mcp_comp(struct bxe_softc *sc,
10799                    uint32_t         magic_val)
10800 {
10801     int rc = bxe_init_shmem(sc);
10802 
10803     /* Restore the `magic' bit value */
10804     if (!CHIP_IS_E1(sc)) {
10805         bxe_clp_reset_done(sc, magic_val);
10806     }
10807 
10808     return (rc);
10809 }
10810 
10811 static void
10812 bxe_pxp_prep(struct bxe_softc *sc)
10813 {
10814     if (!CHIP_IS_E1(sc)) {
10815         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10816         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10817         wmb();
10818     }
10819 }
10820 
10821 /*
10822  * Reset the whole chip except for:
10823  *      - PCIE core
10824  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10825  *      - IGU
10826  *      - MISC (including AEU)
10827  *      - GRC
10828  *      - RBCN, RBCP
10829  */
10830 static void
10831 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10832                             uint8_t          global)
10833 {
10834     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10835     uint32_t global_bits2, stay_reset2;
10836 
10837     /*
10838      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10839      * (per chip) blocks.
10840      */
10841     global_bits2 =
10842         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10843         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10844 
10845     /*
10846      * Don't reset the following blocks.
10847      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10848      *            reset, as in 4 port device they might still be owned
10849      *            by the MCP (there is only one leader per path).
10850      */
10851     not_reset_mask1 =
10852         MISC_REGISTERS_RESET_REG_1_RST_HC |
10853         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10854         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10855 
10856     not_reset_mask2 =
10857         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10858         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10859         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10860         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10861         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10862         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10863         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10864         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10865         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10866         MISC_REGISTERS_RESET_REG_2_PGLC |
10867         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10868         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10869         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10870         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10871         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10872         MISC_REGISTERS_RESET_REG_2_UMAC1;
10873 
10874     /*
10875      * Keep the following blocks in reset:
10876      *  - all xxMACs are handled by the elink code.
10877      */
10878     stay_reset2 =
10879         MISC_REGISTERS_RESET_REG_2_XMAC |
10880         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10881 
10882     /* Full reset masks according to the chip */
10883     reset_mask1 = 0xffffffff;
10884 
10885     if (CHIP_IS_E1(sc))
10886         reset_mask2 = 0xffff;
10887     else if (CHIP_IS_E1H(sc))
10888         reset_mask2 = 0x1ffff;
10889     else if (CHIP_IS_E2(sc))
10890         reset_mask2 = 0xfffff;
10891     else /* CHIP_IS_E3 */
10892         reset_mask2 = 0x3ffffff;
10893 
10894     /* Don't reset global blocks unless we need to */
10895     if (!global)
10896         reset_mask2 &= ~global_bits2;
10897 
10898     /*
10899      * In case of attention in the QM, we need to reset PXP
10900      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10901      * because otherwise QM reset would release 'close the gates' shortly
10902      * before resetting the PXP, then the PSWRQ would send a write
10903      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10904      * read the payload data from PSWWR, but PSWWR would not
10905      * respond. The write queue in PGLUE would stuck, dmae commands
10906      * would not return. Therefore it's important to reset the second
10907      * reset register (containing the
10908      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10909      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10910      * bit).
10911      */
10912     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10913            reset_mask2 & (~not_reset_mask2));
10914 
10915     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10916            reset_mask1 & (~not_reset_mask1));
10917 
10918     mb();
10919     wmb();
10920 
10921     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10922            reset_mask2 & (~stay_reset2));
10923 
10924     mb();
10925     wmb();
10926 
10927     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10928     wmb();
10929 }
10930 
10931 static int
10932 bxe_process_kill(struct bxe_softc *sc,
10933                  uint8_t          global)
10934 {
10935     int cnt = 1000;
10936     uint32_t val = 0;
10937     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10938     uint32_t tags_63_32 = 0;
10939 
10940     /* Empty the Tetris buffer, wait for 1s */
10941     do {
10942         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10943         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10944         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10945         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10946         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10947         if (CHIP_IS_E3(sc)) {
10948             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10949         }
10950 
10951         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
10952             ((port_is_idle_0 & 0x1) == 0x1) &&
10953             ((port_is_idle_1 & 0x1) == 0x1) &&
10954             (pgl_exp_rom2 == 0xffffffff) &&
10955             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
10956             break;
10957         DELAY(1000);
10958     } while (cnt-- > 0);
10959 
10960     if (cnt <= 0) {
10961         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
10962                   "are still outstanding read requests after 1s! "
10963                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
10964                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
10965               sr_cnt, blk_cnt, port_is_idle_0,
10966               port_is_idle_1, pgl_exp_rom2);
10967         return (-1);
10968     }
10969 
10970     mb();
10971 
10972     /* Close gates #2, #3 and #4 */
10973     bxe_set_234_gates(sc, TRUE);
10974 
10975     /* Poll for IGU VQs for 57712 and newer chips */
10976     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
10977         return (-1);
10978     }
10979 
10980     /* XXX indicate that "process kill" is in progress to MCP */
10981 
10982     /* clear "unprepared" bit */
10983     REG_WR(sc, MISC_REG_UNPREPARED, 0);
10984     mb();
10985 
10986     /* Make sure all is written to the chip before the reset */
10987     wmb();
10988 
10989     /*
10990      * Wait for 1ms to empty GLUE and PCI-E core queues,
10991      * PSWHST, GRC and PSWRD Tetris buffer.
10992      */
10993     DELAY(1000);
10994 
10995     /* Prepare to chip reset: */
10996     /* MCP */
10997     if (global) {
10998         bxe_reset_mcp_prep(sc, &val);
10999     }
11000 
11001     /* PXP */
11002     bxe_pxp_prep(sc);
11003     mb();
11004 
11005     /* reset the chip */
11006     bxe_process_kill_chip_reset(sc, global);
11007     mb();
11008 
11009     /* clear errors in PGB */
11010     if (!CHIP_IS_E1(sc))
11011         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11012 
11013     /* Recover after reset: */
11014     /* MCP */
11015     if (global && bxe_reset_mcp_comp(sc, val)) {
11016         return (-1);
11017     }
11018 
11019     /* XXX add resetting the NO_MCP mode DB here */
11020 
11021     /* Open the gates #2, #3 and #4 */
11022     bxe_set_234_gates(sc, FALSE);
11023 
11024     /* XXX
11025      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11026      * re-enable attentions
11027      */
11028 
11029     return (0);
11030 }
11031 
11032 static int
11033 bxe_leader_reset(struct bxe_softc *sc)
11034 {
11035     int rc = 0;
11036     uint8_t global = bxe_reset_is_global(sc);
11037     uint32_t load_code;
11038 
11039     /*
11040      * If not going to reset MCP, load "fake" driver to reset HW while
11041      * driver is owner of the HW.
11042      */
11043     if (!global && !BXE_NOMCP(sc)) {
11044         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11045                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11046         if (!load_code) {
11047             BLOGE(sc, "MCP response failure, aborting\n");
11048             rc = -1;
11049             goto exit_leader_reset;
11050         }
11051 
11052         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11053             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11054             BLOGE(sc, "MCP unexpected response, aborting\n");
11055             rc = -1;
11056             goto exit_leader_reset2;
11057         }
11058 
11059         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11060         if (!load_code) {
11061             BLOGE(sc, "MCP response failure, aborting\n");
11062             rc = -1;
11063             goto exit_leader_reset2;
11064         }
11065     }
11066 
11067     /* try to recover after the failure */
11068     if (bxe_process_kill(sc, global)) {
11069         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11070         rc = -1;
11071         goto exit_leader_reset2;
11072     }
11073 
11074     /*
11075      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11076      * state.
11077      */
11078     bxe_set_reset_done(sc);
11079     if (global) {
11080         bxe_clear_reset_global(sc);
11081     }
11082 
11083 exit_leader_reset2:
11084 
11085     /* unload "fake driver" if it was loaded */
11086     if (!global && !BXE_NOMCP(sc)) {
11087         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11088         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11089     }
11090 
11091 exit_leader_reset:
11092 
11093     sc->is_leader = 0;
11094     bxe_release_leader_lock(sc);
11095 
11096     mb();
11097     return (rc);
11098 }
11099 
11100 /*
11101  * prepare INIT transition, parameters configured:
11102  *   - HC configuration
11103  *   - Queue's CDU context
11104  */
11105 static void
11106 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11107                    struct bxe_fastpath            *fp,
11108                    struct ecore_queue_init_params *init_params)
11109 {
11110     uint8_t cos;
11111     int cxt_index, cxt_offset;
11112 
11113     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11114     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11115 
11116     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11117     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11118 
11119     /* HC rate */
11120     init_params->rx.hc_rate =
11121         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11122     init_params->tx.hc_rate =
11123         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11124 
11125     /* FW SB ID */
11126     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11127 
11128     /* CQ index among the SB indices */
11129     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11130     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11131 
11132     /* set maximum number of COSs supported by this queue */
11133     init_params->max_cos = sc->max_cos;
11134 
11135     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11136           fp->index, init_params->max_cos);
11137 
11138     /* set the context pointers queue object */
11139     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11140         /* XXX change index/cid here if ever support multiple tx CoS */
11141         /* fp->txdata[cos]->cid */
11142         cxt_index = fp->index / ILT_PAGE_CIDS;
11143         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11144         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11145     }
11146 }
11147 
11148 /* set flags that are common for the Tx-only and not normal connections */
11149 static unsigned long
11150 bxe_get_common_flags(struct bxe_softc    *sc,
11151                      struct bxe_fastpath *fp,
11152                      uint8_t             zero_stats)
11153 {
11154     unsigned long flags = 0;
11155 
11156     /* PF driver will always initialize the Queue to an ACTIVE state */
11157     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11158 
11159     /*
11160      * tx only connections collect statistics (on the same index as the
11161      * parent connection). The statistics are zeroed when the parent
11162      * connection is initialized.
11163      */
11164 
11165     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11166     if (zero_stats) {
11167         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11168     }
11169 
11170     /*
11171      * tx only connections can support tx-switching, though their
11172      * CoS-ness doesn't survive the loopback
11173      */
11174     if (sc->flags & BXE_TX_SWITCHING) {
11175         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11176     }
11177 
11178     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11179 
11180     return (flags);
11181 }
11182 
11183 static unsigned long
11184 bxe_get_q_flags(struct bxe_softc    *sc,
11185                 struct bxe_fastpath *fp,
11186                 uint8_t             leading)
11187 {
11188     unsigned long flags = 0;
11189 
11190     if (IS_MF_SD(sc)) {
11191         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11192     }
11193 
11194     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11195         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11196         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11197     }
11198 
11199     if (leading) {
11200         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11201         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11202     }
11203 
11204     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11205 
11206     /* merge with common flags */
11207     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11208 }
11209 
11210 static void
11211 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11212                       struct bxe_fastpath               *fp,
11213                       struct ecore_general_setup_params *gen_init,
11214                       uint8_t                           cos)
11215 {
11216     gen_init->stat_id = bxe_stats_id(fp);
11217     gen_init->spcl_id = fp->cl_id;
11218     gen_init->mtu = sc->mtu;
11219     gen_init->cos = cos;
11220 }
11221 
11222 static void
11223 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11224                  struct bxe_fastpath           *fp,
11225                  struct rxq_pause_params       *pause,
11226                  struct ecore_rxq_setup_params *rxq_init)
11227 {
11228     uint8_t max_sge = 0;
11229     uint16_t sge_sz = 0;
11230     uint16_t tpa_agg_size = 0;
11231 
11232     pause->sge_th_lo = SGE_TH_LO(sc);
11233     pause->sge_th_hi = SGE_TH_HI(sc);
11234 
11235     /* validate SGE ring has enough to cross high threshold */
11236     if (sc->dropless_fc &&
11237             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11238             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11239         BLOGW(sc, "sge ring threshold limit\n");
11240     }
11241 
11242     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11243     tpa_agg_size = (2 * sc->mtu);
11244     if (tpa_agg_size < sc->max_aggregation_size) {
11245         tpa_agg_size = sc->max_aggregation_size;
11246     }
11247 
11248     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11249     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11250                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11251     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11252 
11253     /* pause - not for e1 */
11254     if (!CHIP_IS_E1(sc)) {
11255         pause->bd_th_lo = BD_TH_LO(sc);
11256         pause->bd_th_hi = BD_TH_HI(sc);
11257 
11258         pause->rcq_th_lo = RCQ_TH_LO(sc);
11259         pause->rcq_th_hi = RCQ_TH_HI(sc);
11260 
11261         /* validate rings have enough entries to cross high thresholds */
11262         if (sc->dropless_fc &&
11263             pause->bd_th_hi + FW_PREFETCH_CNT >
11264             sc->rx_ring_size) {
11265             BLOGW(sc, "rx bd ring threshold limit\n");
11266         }
11267 
11268         if (sc->dropless_fc &&
11269             pause->rcq_th_hi + FW_PREFETCH_CNT >
11270             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11271             BLOGW(sc, "rcq ring threshold limit\n");
11272         }
11273 
11274         pause->pri_map = 1;
11275     }
11276 
11277     /* rxq setup */
11278     rxq_init->dscr_map   = fp->rx_dma.paddr;
11279     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11280     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11281     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11282 
11283     /*
11284      * This should be a maximum number of data bytes that may be
11285      * placed on the BD (not including paddings).
11286      */
11287     rxq_init->buf_sz = (fp->rx_buf_size -
11288                         IP_HEADER_ALIGNMENT_PADDING);
11289 
11290     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11291     rxq_init->tpa_agg_sz      = tpa_agg_size;
11292     rxq_init->sge_buf_sz      = sge_sz;
11293     rxq_init->max_sges_pkt    = max_sge;
11294     rxq_init->rss_engine_id   = SC_FUNC(sc);
11295     rxq_init->mcast_engine_id = SC_FUNC(sc);
11296 
11297     /*
11298      * Maximum number or simultaneous TPA aggregation for this Queue.
11299      * For PF Clients it should be the maximum available number.
11300      * VF driver(s) may want to define it to a smaller value.
11301      */
11302     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11303 
11304     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11305     rxq_init->fw_sb_id = fp->fw_sb_id;
11306 
11307     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11308 
11309     /*
11310      * configure silent vlan removal
11311      * if multi function mode is afex, then mask default vlan
11312      */
11313     if (IS_MF_AFEX(sc)) {
11314         rxq_init->silent_removal_value =
11315             sc->devinfo.mf_info.afex_def_vlan_tag;
11316         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11317     }
11318 }
11319 
11320 static void
11321 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11322                  struct bxe_fastpath           *fp,
11323                  struct ecore_txq_setup_params *txq_init,
11324                  uint8_t                       cos)
11325 {
11326     /*
11327      * XXX If multiple CoS is ever supported then each fastpath structure
11328      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11329      * fp->txdata[cos]->tx_dma.paddr;
11330      */
11331     txq_init->dscr_map     = fp->tx_dma.paddr;
11332     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11333     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11334     txq_init->fw_sb_id     = fp->fw_sb_id;
11335 
11336     /*
11337      * set the TSS leading client id for TX classfication to the
11338      * leading RSS client id
11339      */
11340     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11341 }
11342 
11343 /*
11344  * This function performs 2 steps in a queue state machine:
11345  *   1) RESET->INIT
11346  *   2) INIT->SETUP
11347  */
11348 static int
11349 bxe_setup_queue(struct bxe_softc    *sc,
11350                 struct bxe_fastpath *fp,
11351                 uint8_t             leading)
11352 {
11353     struct ecore_queue_state_params q_params = { NULL };
11354     struct ecore_queue_setup_params *setup_params =
11355                         &q_params.params.setup;
11356     int rc;
11357 
11358     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11359 
11360     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11361 
11362     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11363 
11364     /* we want to wait for completion in this context */
11365     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11366 
11367     /* prepare the INIT parameters */
11368     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11369 
11370     /* Set the command */
11371     q_params.cmd = ECORE_Q_CMD_INIT;
11372 
11373     /* Change the state to INIT */
11374     rc = ecore_queue_state_change(sc, &q_params);
11375     if (rc) {
11376         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11377         return (rc);
11378     }
11379 
11380     BLOGD(sc, DBG_LOAD, "init complete\n");
11381 
11382     /* now move the Queue to the SETUP state */
11383     memset(setup_params, 0, sizeof(*setup_params));
11384 
11385     /* set Queue flags */
11386     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11387 
11388     /* set general SETUP parameters */
11389     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11390                           FIRST_TX_COS_INDEX);
11391 
11392     bxe_pf_rx_q_prep(sc, fp,
11393                      &setup_params->pause_params,
11394                      &setup_params->rxq_params);
11395 
11396     bxe_pf_tx_q_prep(sc, fp,
11397                      &setup_params->txq_params,
11398                      FIRST_TX_COS_INDEX);
11399 
11400     /* Set the command */
11401     q_params.cmd = ECORE_Q_CMD_SETUP;
11402 
11403     /* change the state to SETUP */
11404     rc = ecore_queue_state_change(sc, &q_params);
11405     if (rc) {
11406         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11407         return (rc);
11408     }
11409 
11410     return (rc);
11411 }
11412 
11413 static int
11414 bxe_setup_leading(struct bxe_softc *sc)
11415 {
11416     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11417 }
11418 
11419 static int
11420 bxe_config_rss_pf(struct bxe_softc            *sc,
11421                   struct ecore_rss_config_obj *rss_obj,
11422                   uint8_t                     config_hash)
11423 {
11424     struct ecore_config_rss_params params = { NULL };
11425     int i;
11426 
11427     /*
11428      * Although RSS is meaningless when there is a single HW queue we
11429      * still need it enabled in order to have HW Rx hash generated.
11430      */
11431 
11432     params.rss_obj = rss_obj;
11433 
11434     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11435 
11436     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11437 
11438     /* RSS configuration */
11439     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11440     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11441     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11442     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11443     if (rss_obj->udp_rss_v4) {
11444         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11445     }
11446     if (rss_obj->udp_rss_v6) {
11447         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11448     }
11449 
11450     /* Hash bits */
11451     params.rss_result_mask = MULTI_MASK;
11452 
11453     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11454 
11455     if (config_hash) {
11456         /* RSS keys */
11457         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11458             params.rss_key[i] = arc4random();
11459         }
11460 
11461         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11462     }
11463 
11464     return (ecore_config_rss(sc, &params));
11465 }
11466 
11467 static int
11468 bxe_config_rss_eth(struct bxe_softc *sc,
11469                    uint8_t          config_hash)
11470 {
11471     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11472 }
11473 
11474 static int
11475 bxe_init_rss_pf(struct bxe_softc *sc)
11476 {
11477     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11478     int i;
11479 
11480     /*
11481      * Prepare the initial contents of the indirection table if
11482      * RSS is enabled
11483      */
11484     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11485         sc->rss_conf_obj.ind_table[i] =
11486             (sc->fp->cl_id + (i % num_eth_queues));
11487     }
11488 
11489     if (sc->udp_rss) {
11490         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11491     }
11492 
11493     /*
11494      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11495      * per-port, so if explicit configuration is needed, do it only
11496      * for a PMF.
11497      *
11498      * For 57712 and newer it's a per-function configuration.
11499      */
11500     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11501 }
11502 
11503 static int
11504 bxe_set_mac_one(struct bxe_softc          *sc,
11505                 uint8_t                   *mac,
11506                 struct ecore_vlan_mac_obj *obj,
11507                 uint8_t                   set,
11508                 int                       mac_type,
11509                 unsigned long             *ramrod_flags)
11510 {
11511     struct ecore_vlan_mac_ramrod_params ramrod_param;
11512     int rc;
11513 
11514     memset(&ramrod_param, 0, sizeof(ramrod_param));
11515 
11516     /* fill in general parameters */
11517     ramrod_param.vlan_mac_obj = obj;
11518     ramrod_param.ramrod_flags = *ramrod_flags;
11519 
11520     /* fill a user request section if needed */
11521     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11522         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11523 
11524         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11525 
11526         /* Set the command: ADD or DEL */
11527         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11528                                             ECORE_VLAN_MAC_DEL;
11529     }
11530 
11531     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11532 
11533     if (rc == ECORE_EXISTS) {
11534         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11535         /* do not treat adding same MAC as error */
11536         rc = 0;
11537     } else if (rc < 0) {
11538         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11539     }
11540 
11541     return (rc);
11542 }
11543 
11544 static int
11545 bxe_set_eth_mac(struct bxe_softc *sc,
11546                 uint8_t          set)
11547 {
11548     unsigned long ramrod_flags = 0;
11549 
11550     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11551 
11552     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11553 
11554     /* Eth MAC is set on RSS leading client (fp[0]) */
11555     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11556                             &sc->sp_objs->mac_obj,
11557                             set, ECORE_ETH_MAC, &ramrod_flags));
11558 }
11559 
11560 static int
11561 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11562 {
11563     uint32_t sel_phy_idx = 0;
11564 
11565     if (sc->link_params.num_phys <= 1) {
11566         return (ELINK_INT_PHY);
11567     }
11568 
11569     if (sc->link_vars.link_up) {
11570         sel_phy_idx = ELINK_EXT_PHY1;
11571         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11572         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11573             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11574              ELINK_SUPPORTED_FIBRE))
11575             sel_phy_idx = ELINK_EXT_PHY2;
11576     } else {
11577         switch (elink_phy_selection(&sc->link_params)) {
11578         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11579         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11580         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11581                sel_phy_idx = ELINK_EXT_PHY1;
11582                break;
11583         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11584         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11585                sel_phy_idx = ELINK_EXT_PHY2;
11586                break;
11587         }
11588     }
11589 
11590     return (sel_phy_idx);
11591 }
11592 
11593 static int
11594 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11595 {
11596     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11597 
11598     /*
11599      * The selected activated PHY is always after swapping (in case PHY
11600      * swapping is enabled). So when swapping is enabled, we need to reverse
11601      * the configuration
11602      */
11603 
11604     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11605         if (sel_phy_idx == ELINK_EXT_PHY1)
11606             sel_phy_idx = ELINK_EXT_PHY2;
11607         else if (sel_phy_idx == ELINK_EXT_PHY2)
11608             sel_phy_idx = ELINK_EXT_PHY1;
11609     }
11610 
11611     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11612 }
11613 
11614 static void
11615 bxe_set_requested_fc(struct bxe_softc *sc)
11616 {
11617     /*
11618      * Initialize link parameters structure variables
11619      * It is recommended to turn off RX FC for jumbo frames
11620      * for better performance
11621      */
11622     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11623         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11624     } else {
11625         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11626     }
11627 }
11628 
11629 static void
11630 bxe_calc_fc_adv(struct bxe_softc *sc)
11631 {
11632     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11633     switch (sc->link_vars.ieee_fc &
11634             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11635     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11636     default:
11637         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11638                                            ADVERTISED_Pause);
11639         break;
11640 
11641     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11642         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11643                                           ADVERTISED_Pause);
11644         break;
11645 
11646     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11647         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11648         break;
11649     }
11650 }
11651 
11652 static uint16_t
11653 bxe_get_mf_speed(struct bxe_softc *sc)
11654 {
11655     uint16_t line_speed = sc->link_vars.line_speed;
11656     if (IS_MF(sc)) {
11657         uint16_t maxCfg =
11658             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11659 
11660         /* calculate the current MAX line speed limit for the MF devices */
11661         if (IS_MF_SI(sc)) {
11662             line_speed = (line_speed * maxCfg) / 100;
11663         } else { /* SD mode */
11664             uint16_t vn_max_rate = maxCfg * 100;
11665 
11666             if (vn_max_rate < line_speed) {
11667                 line_speed = vn_max_rate;
11668             }
11669         }
11670     }
11671 
11672     return (line_speed);
11673 }
11674 
11675 static void
11676 bxe_fill_report_data(struct bxe_softc            *sc,
11677                      struct bxe_link_report_data *data)
11678 {
11679     uint16_t line_speed = bxe_get_mf_speed(sc);
11680 
11681     memset(data, 0, sizeof(*data));
11682 
11683     /* fill the report data with the effective line speed */
11684     data->line_speed = line_speed;
11685 
11686     /* Link is down */
11687     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11688         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11689     }
11690 
11691     /* Full DUPLEX */
11692     if (sc->link_vars.duplex == DUPLEX_FULL) {
11693         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11694     }
11695 
11696     /* Rx Flow Control is ON */
11697     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11698         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11699     }
11700 
11701     /* Tx Flow Control is ON */
11702     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11703         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11704     }
11705 }
11706 
11707 /* report link status to OS, should be called under phy_lock */
11708 static void
11709 bxe_link_report_locked(struct bxe_softc *sc)
11710 {
11711     struct bxe_link_report_data cur_data;
11712 
11713     /* reread mf_cfg */
11714     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11715         bxe_read_mf_cfg(sc);
11716     }
11717 
11718     /* Read the current link report info */
11719     bxe_fill_report_data(sc, &cur_data);
11720 
11721     /* Don't report link down or exactly the same link status twice */
11722     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11723         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11724                       &sc->last_reported_link.link_report_flags) &&
11725          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11726                       &cur_data.link_report_flags))) {
11727         return;
11728     }
11729 
11730     sc->link_cnt++;
11731 
11732     /* report new link params and remember the state for the next time */
11733     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11734 
11735     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11736                      &cur_data.link_report_flags)) {
11737         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11738         BLOGI(sc, "NIC Link is Down\n");
11739     } else {
11740         const char *duplex;
11741         const char *flow;
11742 
11743         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11744                                    &cur_data.link_report_flags)) {
11745             duplex = "full";
11746         } else {
11747             duplex = "half";
11748         }
11749 
11750         /*
11751          * Handle the FC at the end so that only these flags would be
11752          * possibly set. This way we may easily check if there is no FC
11753          * enabled.
11754          */
11755         if (cur_data.link_report_flags) {
11756             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11757                              &cur_data.link_report_flags) &&
11758                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11759                              &cur_data.link_report_flags)) {
11760                 flow = "ON - receive & transmit";
11761             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11762                                     &cur_data.link_report_flags) &&
11763                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11764                                      &cur_data.link_report_flags)) {
11765                 flow = "ON - receive";
11766             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11767                                      &cur_data.link_report_flags) &&
11768                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11769                                     &cur_data.link_report_flags)) {
11770                 flow = "ON - transmit";
11771             } else {
11772                 flow = "none"; /* possible? */
11773             }
11774         } else {
11775             flow = "none";
11776         }
11777 
11778         if_link_state_change(sc->ifp, LINK_STATE_UP);
11779         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11780               cur_data.line_speed, duplex, flow);
11781     }
11782 }
11783 
11784 static void
11785 bxe_link_report(struct bxe_softc *sc)
11786 {
11787     bxe_acquire_phy_lock(sc);
11788     bxe_link_report_locked(sc);
11789     bxe_release_phy_lock(sc);
11790 }
11791 
11792 static void
11793 bxe_link_status_update(struct bxe_softc *sc)
11794 {
11795     if (sc->state != BXE_STATE_OPEN) {
11796         return;
11797     }
11798 
11799     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11800         elink_link_status_update(&sc->link_params, &sc->link_vars);
11801     } else {
11802         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11803                                   ELINK_SUPPORTED_10baseT_Full |
11804                                   ELINK_SUPPORTED_100baseT_Half |
11805                                   ELINK_SUPPORTED_100baseT_Full |
11806                                   ELINK_SUPPORTED_1000baseT_Full |
11807                                   ELINK_SUPPORTED_2500baseX_Full |
11808                                   ELINK_SUPPORTED_10000baseT_Full |
11809                                   ELINK_SUPPORTED_TP |
11810                                   ELINK_SUPPORTED_FIBRE |
11811                                   ELINK_SUPPORTED_Autoneg |
11812                                   ELINK_SUPPORTED_Pause |
11813                                   ELINK_SUPPORTED_Asym_Pause);
11814         sc->port.advertising[0] = sc->port.supported[0];
11815 
11816         sc->link_params.sc                = sc;
11817         sc->link_params.port              = SC_PORT(sc);
11818         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11819         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11820         sc->link_params.req_line_speed[0] = SPEED_10000;
11821         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11822         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11823 
11824         if (CHIP_REV_IS_FPGA(sc)) {
11825             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11826             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11827             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11828                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11829         } else {
11830             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11831             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11832             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11833                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11834         }
11835 
11836         sc->link_vars.link_up = 1;
11837 
11838         sc->link_vars.duplex    = DUPLEX_FULL;
11839         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11840 
11841         if (IS_PF(sc)) {
11842             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11843             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11844             bxe_link_report(sc);
11845         }
11846     }
11847 
11848     if (IS_PF(sc)) {
11849         if (sc->link_vars.link_up) {
11850             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11851         } else {
11852             bxe_stats_handle(sc, STATS_EVENT_STOP);
11853         }
11854         bxe_link_report(sc);
11855     } else {
11856         bxe_link_report(sc);
11857         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11858     }
11859 }
11860 
11861 static int
11862 bxe_initial_phy_init(struct bxe_softc *sc,
11863                      int              load_mode)
11864 {
11865     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11866     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11867     struct elink_params *lp = &sc->link_params;
11868 
11869     bxe_set_requested_fc(sc);
11870 
11871     if (CHIP_REV_IS_SLOW(sc)) {
11872         uint32_t bond = CHIP_BOND_ID(sc);
11873         uint32_t feat = 0;
11874 
11875         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11876             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11877         } else if (bond & 0x4) {
11878             if (CHIP_IS_E3(sc)) {
11879                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11880             } else {
11881                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11882             }
11883         } else if (bond & 0x8) {
11884             if (CHIP_IS_E3(sc)) {
11885                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11886             } else {
11887                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11888             }
11889         }
11890 
11891         /* disable EMAC for E3 and above */
11892         if (bond & 0x2) {
11893             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11894         }
11895 
11896         sc->link_params.feature_config_flags |= feat;
11897     }
11898 
11899     bxe_acquire_phy_lock(sc);
11900 
11901     if (load_mode == LOAD_DIAG) {
11902         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11903         /* Prefer doing PHY loopback at 10G speed, if possible */
11904         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11905             if (lp->speed_cap_mask[cfg_idx] &
11906                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11907                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11908             } else {
11909                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11910             }
11911         }
11912     }
11913 
11914     if (load_mode == LOAD_LOOPBACK_EXT) {
11915         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11916     }
11917 
11918     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11919 
11920     bxe_release_phy_lock(sc);
11921 
11922     bxe_calc_fc_adv(sc);
11923 
11924     if (sc->link_vars.link_up) {
11925         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11926         bxe_link_report(sc);
11927     }
11928 
11929     if (!CHIP_REV_IS_SLOW(sc)) {
11930         bxe_periodic_start(sc);
11931     }
11932 
11933     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11934     return (rc);
11935 }
11936 
11937 /* must be called under IF_ADDR_LOCK */
11938 
11939 static int
11940 bxe_set_mc_list(struct bxe_softc *sc)
11941 {
11942     struct ecore_mcast_ramrod_params rparam = { NULL };
11943     int rc = 0;
11944     int mc_count = 0;
11945     int mcnt, i;
11946     struct ecore_mcast_list_elem *mc_mac, *mc_mac_start;
11947     unsigned char *mta;
11948     if_t ifp = sc->ifp;
11949 
11950     mc_count = if_multiaddr_count(ifp, -1);/* XXX they don't have a limit */
11951     if (!mc_count)
11952         return (0);
11953 
11954     mta = malloc(sizeof(unsigned char) * ETHER_ADDR_LEN *
11955             mc_count, M_DEVBUF, M_NOWAIT);
11956 
11957     if(mta == NULL) {
11958         BLOGE(sc, "Failed to allocate temp mcast list\n");
11959         return (-1);
11960     }
11961     bzero(mta, (sizeof(unsigned char) * ETHER_ADDR_LEN * mc_count));
11962 
11963     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF, (M_NOWAIT | M_ZERO));
11964     mc_mac_start = mc_mac;
11965 
11966     if (!mc_mac) {
11967         free(mta, M_DEVBUF);
11968         BLOGE(sc, "Failed to allocate temp mcast list\n");
11969         return (-1);
11970     }
11971     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
11972 
11973     /* mta and mcnt not expected to be  different */
11974     if_multiaddr_array(ifp, mta, &mcnt, mc_count);
11975 
11976 
11977     rparam.mcast_obj = &sc->mcast_obj;
11978     ECORE_LIST_INIT(&rparam.mcast_list);
11979 
11980     for(i=0; i< mcnt; i++) {
11981 
11982         mc_mac->mac = (uint8_t *)(mta + (i * ETHER_ADDR_LEN));
11983         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &rparam.mcast_list);
11984 
11985         BLOGD(sc, DBG_LOAD,
11986               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
11987               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
11988               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
11989 
11990         mc_mac++;
11991     }
11992     rparam.mcast_list_len = mc_count;
11993 
11994     BXE_MCAST_LOCK(sc);
11995 
11996     /* first, clear all configured multicast MACs */
11997     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
11998     if (rc < 0) {
11999         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12000         BXE_MCAST_UNLOCK(sc);
12001     	free(mc_mac_start, M_DEVBUF);
12002         free(mta, M_DEVBUF);
12003         return (rc);
12004     }
12005 
12006     /* Now add the new MACs */
12007     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12008     if (rc < 0) {
12009         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12010     }
12011 
12012     BXE_MCAST_UNLOCK(sc);
12013 
12014     free(mc_mac_start, M_DEVBUF);
12015     free(mta, M_DEVBUF);
12016 
12017     return (rc);
12018 }
12019 
12020 static int
12021 bxe_set_uc_list(struct bxe_softc *sc)
12022 {
12023     if_t ifp = sc->ifp;
12024     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12025     struct ifaddr *ifa;
12026     unsigned long ramrod_flags = 0;
12027     int rc;
12028 
12029 #if __FreeBSD_version < 800000
12030     IF_ADDR_LOCK(ifp);
12031 #else
12032     if_addr_rlock(ifp);
12033 #endif
12034 
12035     /* first schedule a cleanup up of old configuration */
12036     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12037     if (rc < 0) {
12038         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12039 #if __FreeBSD_version < 800000
12040         IF_ADDR_UNLOCK(ifp);
12041 #else
12042         if_addr_runlock(ifp);
12043 #endif
12044         return (rc);
12045     }
12046 
12047     ifa = if_getifaddr(ifp); /* XXX Is this structure */
12048     while (ifa) {
12049         if (ifa->ifa_addr->sa_family != AF_LINK) {
12050             ifa = TAILQ_NEXT(ifa, ifa_link);
12051             continue;
12052         }
12053 
12054         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12055                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12056         if (rc == -EEXIST) {
12057             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12058             /* do not treat adding same MAC as an error */
12059             rc = 0;
12060         } else if (rc < 0) {
12061             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12062 #if __FreeBSD_version < 800000
12063             IF_ADDR_UNLOCK(ifp);
12064 #else
12065             if_addr_runlock(ifp);
12066 #endif
12067             return (rc);
12068         }
12069 
12070         ifa = TAILQ_NEXT(ifa, ifa_link);
12071     }
12072 
12073 #if __FreeBSD_version < 800000
12074     IF_ADDR_UNLOCK(ifp);
12075 #else
12076     if_addr_runlock(ifp);
12077 #endif
12078 
12079     /* Execute the pending commands */
12080     bit_set(&ramrod_flags, RAMROD_CONT);
12081     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12082                             ECORE_UC_LIST_MAC, &ramrod_flags));
12083 }
12084 
12085 static void
12086 bxe_set_rx_mode(struct bxe_softc *sc)
12087 {
12088     if_t ifp = sc->ifp;
12089     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12090 
12091     if (sc->state != BXE_STATE_OPEN) {
12092         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12093         return;
12094     }
12095 
12096     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12097 
12098     if (if_getflags(ifp) & IFF_PROMISC) {
12099         rx_mode = BXE_RX_MODE_PROMISC;
12100     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12101                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12102                 CHIP_IS_E1(sc))) {
12103         rx_mode = BXE_RX_MODE_ALLMULTI;
12104     } else {
12105         if (IS_PF(sc)) {
12106             /* some multicasts */
12107             if (bxe_set_mc_list(sc) < 0) {
12108                 rx_mode = BXE_RX_MODE_ALLMULTI;
12109             }
12110             if (bxe_set_uc_list(sc) < 0) {
12111                 rx_mode = BXE_RX_MODE_PROMISC;
12112             }
12113         }
12114     }
12115 
12116     sc->rx_mode = rx_mode;
12117 
12118     /* schedule the rx_mode command */
12119     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12120         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12121         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12122         return;
12123     }
12124 
12125     if (IS_PF(sc)) {
12126         bxe_set_storm_rx_mode(sc);
12127     }
12128 }
12129 
12130 
12131 /* update flags in shmem */
12132 static void
12133 bxe_update_drv_flags(struct bxe_softc *sc,
12134                      uint32_t         flags,
12135                      uint32_t         set)
12136 {
12137     uint32_t drv_flags;
12138 
12139     if (SHMEM2_HAS(sc, drv_flags)) {
12140         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12141         drv_flags = SHMEM2_RD(sc, drv_flags);
12142 
12143         if (set) {
12144             SET_FLAGS(drv_flags, flags);
12145         } else {
12146             RESET_FLAGS(drv_flags, flags);
12147         }
12148 
12149         SHMEM2_WR(sc, drv_flags, drv_flags);
12150         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12151 
12152         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12153     }
12154 }
12155 
12156 /* periodic timer callout routine, only runs when the interface is up */
12157 
12158 static void
12159 bxe_periodic_callout_func(void *xsc)
12160 {
12161     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12162     int i;
12163 
12164 #if __FreeBSD_version < 800000
12165     struct bxe_fastpath *fp;
12166     uint16_t tx_bd_avail;
12167 #endif
12168 
12169     if (!BXE_CORE_TRYLOCK(sc)) {
12170         /* just bail and try again next time */
12171 
12172         if ((sc->state == BXE_STATE_OPEN) &&
12173             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12174             /* schedule the next periodic callout */
12175             callout_reset(&sc->periodic_callout, hz,
12176                           bxe_periodic_callout_func, sc);
12177         }
12178 
12179         return;
12180     }
12181 
12182     if ((sc->state != BXE_STATE_OPEN) ||
12183         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12184         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12185         BXE_CORE_UNLOCK(sc);
12186         return;
12187     }
12188 
12189 #if __FreeBSD_version < 800000
12190 
12191     fp = &sc->fp[0];
12192     if (BXE_FP_TX_TRYLOCK(fp)) {
12193         struct ifnet *ifp = sc->ifnet;
12194         /*
12195          * If interface was stopped due to unavailable
12196          * bds, try to process some tx completions
12197          */
12198         (void) bxe_txeof(sc, fp);
12199 
12200         tx_bd_avail = bxe_tx_avail(sc, fp);
12201         if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12202             bxe_tx_start_locked(sc, ifp, fp);
12203         }
12204 
12205         BXE_FP_TX_UNLOCK(fp);
12206     }
12207 
12208 #endif /* #if __FreeBSD_version >= 800000 */
12209 
12210     /* Check for TX timeouts on any fastpath. */
12211     FOR_EACH_QUEUE(sc, i) {
12212         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12213             /* Ruh-Roh, chip was reset! */
12214             break;
12215         }
12216     }
12217 
12218     if (!CHIP_REV_IS_SLOW(sc)) {
12219         /*
12220          * This barrier is needed to ensure the ordering between the writing
12221          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12222          * the reading here.
12223          */
12224         mb();
12225         if (sc->port.pmf) {
12226 	    bxe_acquire_phy_lock(sc);
12227             elink_period_func(&sc->link_params, &sc->link_vars);
12228 	    bxe_release_phy_lock(sc);
12229         }
12230     }
12231 
12232     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12233         int mb_idx = SC_FW_MB_IDX(sc);
12234         uint32_t drv_pulse;
12235         uint32_t mcp_pulse;
12236 
12237         ++sc->fw_drv_pulse_wr_seq;
12238         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12239 
12240         drv_pulse = sc->fw_drv_pulse_wr_seq;
12241         bxe_drv_pulse(sc);
12242 
12243         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12244                      MCP_PULSE_SEQ_MASK);
12245 
12246         /*
12247          * The delta between driver pulse and mcp response should
12248          * be 1 (before mcp response) or 0 (after mcp response).
12249          */
12250         if ((drv_pulse != mcp_pulse) &&
12251             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12252             /* someone lost a heartbeat... */
12253             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12254                   drv_pulse, mcp_pulse);
12255         }
12256     }
12257 
12258     /* state is BXE_STATE_OPEN */
12259     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12260 
12261     BXE_CORE_UNLOCK(sc);
12262 
12263     if ((sc->state == BXE_STATE_OPEN) &&
12264         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12265         /* schedule the next periodic callout */
12266         callout_reset(&sc->periodic_callout, hz,
12267                       bxe_periodic_callout_func, sc);
12268     }
12269 }
12270 
12271 static void
12272 bxe_periodic_start(struct bxe_softc *sc)
12273 {
12274     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12275     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12276 }
12277 
12278 static void
12279 bxe_periodic_stop(struct bxe_softc *sc)
12280 {
12281     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12282     callout_drain(&sc->periodic_callout);
12283 }
12284 
12285 /* start the controller */
12286 static __noinline int
12287 bxe_nic_load(struct bxe_softc *sc,
12288              int              load_mode)
12289 {
12290     uint32_t val;
12291     int load_code = 0;
12292     int i, rc = 0;
12293 
12294     BXE_CORE_LOCK_ASSERT(sc);
12295 
12296     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12297 
12298     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12299 
12300     if (IS_PF(sc)) {
12301         /* must be called before memory allocation and HW init */
12302         bxe_ilt_set_info(sc);
12303     }
12304 
12305     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12306 
12307     bxe_set_fp_rx_buf_size(sc);
12308 
12309     if (bxe_alloc_fp_buffers(sc) != 0) {
12310         BLOGE(sc, "Failed to allocate fastpath memory\n");
12311         sc->state = BXE_STATE_CLOSED;
12312         rc = ENOMEM;
12313         goto bxe_nic_load_error0;
12314     }
12315 
12316     if (bxe_alloc_mem(sc) != 0) {
12317         sc->state = BXE_STATE_CLOSED;
12318         rc = ENOMEM;
12319         goto bxe_nic_load_error0;
12320     }
12321 
12322     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12323         sc->state = BXE_STATE_CLOSED;
12324         rc = ENOMEM;
12325         goto bxe_nic_load_error0;
12326     }
12327 
12328     if (IS_PF(sc)) {
12329         /* set pf load just before approaching the MCP */
12330         bxe_set_pf_load(sc);
12331 
12332         /* if MCP exists send load request and analyze response */
12333         if (!BXE_NOMCP(sc)) {
12334             /* attempt to load pf */
12335             if (bxe_nic_load_request(sc, &load_code) != 0) {
12336                 sc->state = BXE_STATE_CLOSED;
12337                 rc = ENXIO;
12338                 goto bxe_nic_load_error1;
12339             }
12340 
12341             /* what did the MCP say? */
12342             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12343                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12344                 sc->state = BXE_STATE_CLOSED;
12345                 rc = ENXIO;
12346                 goto bxe_nic_load_error2;
12347             }
12348         } else {
12349             BLOGI(sc, "Device has no MCP!\n");
12350             load_code = bxe_nic_load_no_mcp(sc);
12351         }
12352 
12353         /* mark PMF if applicable */
12354         bxe_nic_load_pmf(sc, load_code);
12355 
12356         /* Init Function state controlling object */
12357         bxe_init_func_obj(sc);
12358 
12359         /* Initialize HW */
12360         if (bxe_init_hw(sc, load_code) != 0) {
12361             BLOGE(sc, "HW init failed\n");
12362             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12363             sc->state = BXE_STATE_CLOSED;
12364             rc = ENXIO;
12365             goto bxe_nic_load_error2;
12366         }
12367     }
12368 
12369     /* set ALWAYS_ALIVE bit in shmem */
12370     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12371     bxe_drv_pulse(sc);
12372     sc->flags |= BXE_NO_PULSE;
12373 
12374     /* attach interrupts */
12375     if (bxe_interrupt_attach(sc) != 0) {
12376         sc->state = BXE_STATE_CLOSED;
12377         rc = ENXIO;
12378         goto bxe_nic_load_error2;
12379     }
12380 
12381     bxe_nic_init(sc, load_code);
12382 
12383     /* Init per-function objects */
12384     if (IS_PF(sc)) {
12385         bxe_init_objs(sc);
12386         // XXX bxe_iov_nic_init(sc);
12387 
12388         /* set AFEX default VLAN tag to an invalid value */
12389         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12390         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12391 
12392         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12393         rc = bxe_func_start(sc);
12394         if (rc) {
12395             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12396             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12397             sc->state = BXE_STATE_ERROR;
12398             goto bxe_nic_load_error3;
12399         }
12400 
12401         /* send LOAD_DONE command to MCP */
12402         if (!BXE_NOMCP(sc)) {
12403             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12404             if (!load_code) {
12405                 BLOGE(sc, "MCP response failure, aborting\n");
12406                 sc->state = BXE_STATE_ERROR;
12407                 rc = ENXIO;
12408                 goto bxe_nic_load_error3;
12409             }
12410         }
12411 
12412         rc = bxe_setup_leading(sc);
12413         if (rc) {
12414             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12415             sc->state = BXE_STATE_ERROR;
12416             goto bxe_nic_load_error3;
12417         }
12418 
12419         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12420             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12421             if (rc) {
12422                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12423                 sc->state = BXE_STATE_ERROR;
12424                 goto bxe_nic_load_error3;
12425             }
12426         }
12427 
12428         rc = bxe_init_rss_pf(sc);
12429         if (rc) {
12430             BLOGE(sc, "PF RSS init failed\n");
12431             sc->state = BXE_STATE_ERROR;
12432             goto bxe_nic_load_error3;
12433         }
12434     }
12435     /* XXX VF */
12436 
12437     /* now when Clients are configured we are ready to work */
12438     sc->state = BXE_STATE_OPEN;
12439 
12440     /* Configure a ucast MAC */
12441     if (IS_PF(sc)) {
12442         rc = bxe_set_eth_mac(sc, TRUE);
12443     }
12444     if (rc) {
12445         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12446         sc->state = BXE_STATE_ERROR;
12447         goto bxe_nic_load_error3;
12448     }
12449 
12450     if (sc->port.pmf) {
12451         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12452         if (rc) {
12453             sc->state = BXE_STATE_ERROR;
12454             goto bxe_nic_load_error3;
12455         }
12456     }
12457 
12458     sc->link_params.feature_config_flags &=
12459         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12460 
12461     /* start fast path */
12462 
12463     /* Initialize Rx filter */
12464     bxe_set_rx_mode(sc);
12465 
12466     /* start the Tx */
12467     switch (/* XXX load_mode */LOAD_OPEN) {
12468     case LOAD_NORMAL:
12469     case LOAD_OPEN:
12470         break;
12471 
12472     case LOAD_DIAG:
12473     case LOAD_LOOPBACK_EXT:
12474         sc->state = BXE_STATE_DIAG;
12475         break;
12476 
12477     default:
12478         break;
12479     }
12480 
12481     if (sc->port.pmf) {
12482         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12483     } else {
12484         bxe_link_status_update(sc);
12485     }
12486 
12487     /* start the periodic timer callout */
12488     bxe_periodic_start(sc);
12489 
12490     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12491         /* mark driver is loaded in shmem2 */
12492         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12493         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12494                   (val |
12495                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12496                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12497     }
12498 
12499     /* wait for all pending SP commands to complete */
12500     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12501         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12502         bxe_periodic_stop(sc);
12503         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12504         return (ENXIO);
12505     }
12506 
12507     /* Tell the stack the driver is running! */
12508     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12509 
12510     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12511 
12512     return (0);
12513 
12514 bxe_nic_load_error3:
12515 
12516     if (IS_PF(sc)) {
12517         bxe_int_disable_sync(sc, 1);
12518 
12519         /* clean out queued objects */
12520         bxe_squeeze_objects(sc);
12521     }
12522 
12523     bxe_interrupt_detach(sc);
12524 
12525 bxe_nic_load_error2:
12526 
12527     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12528         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12529         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12530     }
12531 
12532     sc->port.pmf = 0;
12533 
12534 bxe_nic_load_error1:
12535 
12536     /* clear pf_load status, as it was already set */
12537     if (IS_PF(sc)) {
12538         bxe_clear_pf_load(sc);
12539     }
12540 
12541 bxe_nic_load_error0:
12542 
12543     bxe_free_fw_stats_mem(sc);
12544     bxe_free_fp_buffers(sc);
12545     bxe_free_mem(sc);
12546 
12547     return (rc);
12548 }
12549 
12550 static int
12551 bxe_init_locked(struct bxe_softc *sc)
12552 {
12553     int other_engine = SC_PATH(sc) ? 0 : 1;
12554     uint8_t other_load_status, load_status;
12555     uint8_t global = FALSE;
12556     int rc;
12557 
12558     BXE_CORE_LOCK_ASSERT(sc);
12559 
12560     /* check if the driver is already running */
12561     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12562         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12563         return (0);
12564     }
12565 
12566     bxe_set_power_state(sc, PCI_PM_D0);
12567 
12568     /*
12569      * If parity occurred during the unload, then attentions and/or
12570      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12571      * loaded on the current engine to complete the recovery. Parity recovery
12572      * is only relevant for PF driver.
12573      */
12574     if (IS_PF(sc)) {
12575         other_load_status = bxe_get_load_status(sc, other_engine);
12576         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12577 
12578         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12579             bxe_chk_parity_attn(sc, &global, TRUE)) {
12580             do {
12581                 /*
12582                  * If there are attentions and they are in global blocks, set
12583                  * the GLOBAL_RESET bit regardless whether it will be this
12584                  * function that will complete the recovery or not.
12585                  */
12586                 if (global) {
12587                     bxe_set_reset_global(sc);
12588                 }
12589 
12590                 /*
12591                  * Only the first function on the current engine should try
12592                  * to recover in open. In case of attentions in global blocks
12593                  * only the first in the chip should try to recover.
12594                  */
12595                 if ((!load_status && (!global || !other_load_status)) &&
12596                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12597                     BLOGI(sc, "Recovered during init\n");
12598                     break;
12599                 }
12600 
12601                 /* recovery has failed... */
12602                 bxe_set_power_state(sc, PCI_PM_D3hot);
12603                 sc->recovery_state = BXE_RECOVERY_FAILED;
12604 
12605                 BLOGE(sc, "Recovery flow hasn't properly "
12606                           "completed yet, try again later. "
12607                           "If you still see this message after a "
12608                           "few retries then power cycle is required.\n");
12609 
12610                 rc = ENXIO;
12611                 goto bxe_init_locked_done;
12612             } while (0);
12613         }
12614     }
12615 
12616     sc->recovery_state = BXE_RECOVERY_DONE;
12617 
12618     rc = bxe_nic_load(sc, LOAD_OPEN);
12619 
12620 bxe_init_locked_done:
12621 
12622     if (rc) {
12623         /* Tell the stack the driver is NOT running! */
12624         BLOGE(sc, "Initialization failed, "
12625                   "stack notified driver is NOT running!\n");
12626 	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
12627     }
12628 
12629     return (rc);
12630 }
12631 
12632 static int
12633 bxe_stop_locked(struct bxe_softc *sc)
12634 {
12635     BXE_CORE_LOCK_ASSERT(sc);
12636     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12637 }
12638 
12639 /*
12640  * Handles controller initialization when called from an unlocked routine.
12641  * ifconfig calls this function.
12642  *
12643  * Returns:
12644  *   void
12645  */
12646 static void
12647 bxe_init(void *xsc)
12648 {
12649     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12650 
12651     BXE_CORE_LOCK(sc);
12652     bxe_init_locked(sc);
12653     BXE_CORE_UNLOCK(sc);
12654 }
12655 
12656 static int
12657 bxe_init_ifnet(struct bxe_softc *sc)
12658 {
12659     if_t ifp;
12660     int capabilities;
12661 
12662     /* ifconfig entrypoint for media type/status reporting */
12663     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12664                  bxe_ifmedia_update,
12665                  bxe_ifmedia_status);
12666 
12667     /* set the default interface values */
12668     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12669     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12670     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12671 
12672     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12673 
12674     /* allocate the ifnet structure */
12675     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
12676         BLOGE(sc, "Interface allocation failed!\n");
12677         return (ENXIO);
12678     }
12679 
12680     if_setsoftc(ifp, sc);
12681     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12682     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
12683     if_setioctlfn(ifp, bxe_ioctl);
12684     if_setstartfn(ifp, bxe_tx_start);
12685     if_setgetcounterfn(ifp, bxe_get_counter);
12686 #if __FreeBSD_version >= 800000
12687     if_settransmitfn(ifp, bxe_tx_mq_start);
12688     if_setqflushfn(ifp, bxe_mq_flush);
12689 #endif
12690 #ifdef FreeBSD8_0
12691     if_settimer(ifp, 0);
12692 #endif
12693     if_setinitfn(ifp, bxe_init);
12694     if_setmtu(ifp, sc->mtu);
12695     if_sethwassist(ifp, (CSUM_IP      |
12696                         CSUM_TCP      |
12697                         CSUM_UDP      |
12698                         CSUM_TSO      |
12699                         CSUM_TCP_IPV6 |
12700                         CSUM_UDP_IPV6));
12701 
12702     capabilities =
12703 #if __FreeBSD_version < 700000
12704         (IFCAP_VLAN_MTU       |
12705          IFCAP_VLAN_HWTAGGING |
12706          IFCAP_HWCSUM         |
12707          IFCAP_JUMBO_MTU      |
12708          IFCAP_LRO);
12709 #else
12710         (IFCAP_VLAN_MTU       |
12711          IFCAP_VLAN_HWTAGGING |
12712          IFCAP_VLAN_HWTSO     |
12713          IFCAP_VLAN_HWFILTER  |
12714          IFCAP_VLAN_HWCSUM    |
12715          IFCAP_HWCSUM         |
12716          IFCAP_JUMBO_MTU      |
12717          IFCAP_LRO            |
12718          IFCAP_TSO4           |
12719          IFCAP_TSO6           |
12720          IFCAP_WOL_MAGIC);
12721 #endif
12722     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
12723     if_setbaudrate(ifp, IF_Gbps(10));
12724 /* XXX */
12725     if_setsendqlen(ifp, sc->tx_ring_size);
12726     if_setsendqready(ifp);
12727 /* XXX */
12728 
12729     sc->ifp = ifp;
12730 
12731     /* attach to the Ethernet interface list */
12732     ether_ifattach(ifp, sc->link_params.mac_addr);
12733 
12734     return (0);
12735 }
12736 
12737 static void
12738 bxe_deallocate_bars(struct bxe_softc *sc)
12739 {
12740     int i;
12741 
12742     for (i = 0; i < MAX_BARS; i++) {
12743         if (sc->bar[i].resource != NULL) {
12744             bus_release_resource(sc->dev,
12745                                  SYS_RES_MEMORY,
12746                                  sc->bar[i].rid,
12747                                  sc->bar[i].resource);
12748             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12749                   i, PCIR_BAR(i));
12750         }
12751     }
12752 }
12753 
12754 static int
12755 bxe_allocate_bars(struct bxe_softc *sc)
12756 {
12757     u_int flags;
12758     int i;
12759 
12760     memset(sc->bar, 0, sizeof(sc->bar));
12761 
12762     for (i = 0; i < MAX_BARS; i++) {
12763 
12764         /* memory resources reside at BARs 0, 2, 4 */
12765         /* Run `pciconf -lb` to see mappings */
12766         if ((i != 0) && (i != 2) && (i != 4)) {
12767             continue;
12768         }
12769 
12770         sc->bar[i].rid = PCIR_BAR(i);
12771 
12772         flags = RF_ACTIVE;
12773         if (i == 0) {
12774             flags |= RF_SHAREABLE;
12775         }
12776 
12777         if ((sc->bar[i].resource =
12778              bus_alloc_resource_any(sc->dev,
12779                                     SYS_RES_MEMORY,
12780                                     &sc->bar[i].rid,
12781                                     flags)) == NULL) {
12782             return (0);
12783         }
12784 
12785         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12786         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12787         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12788 
12789         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%jd) -> %p\n",
12790               i, PCIR_BAR(i),
12791               (void *)rman_get_start(sc->bar[i].resource),
12792               (void *)rman_get_end(sc->bar[i].resource),
12793               rman_get_size(sc->bar[i].resource),
12794               (void *)sc->bar[i].kva);
12795     }
12796 
12797     return (0);
12798 }
12799 
12800 static void
12801 bxe_get_function_num(struct bxe_softc *sc)
12802 {
12803     uint32_t val = 0;
12804 
12805     /*
12806      * Read the ME register to get the function number. The ME register
12807      * holds the relative-function number and absolute-function number. The
12808      * absolute-function number appears only in E2 and above. Before that
12809      * these bits always contained zero, therefore we cannot blindly use them.
12810      */
12811 
12812     val = REG_RD(sc, BAR_ME_REGISTER);
12813 
12814     sc->pfunc_rel =
12815         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12816     sc->path_id =
12817         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12818 
12819     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12820         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12821     } else {
12822         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12823     }
12824 
12825     BLOGD(sc, DBG_LOAD,
12826           "Relative function %d, Absolute function %d, Path %d\n",
12827           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12828 }
12829 
12830 static uint32_t
12831 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12832 {
12833     uint32_t shmem2_size;
12834     uint32_t offset;
12835     uint32_t mf_cfg_offset_value;
12836 
12837     /* Non 57712 */
12838     offset = (SHMEM_RD(sc, func_mb) +
12839               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12840 
12841     /* 57712 plus */
12842     if (sc->devinfo.shmem2_base != 0) {
12843         shmem2_size = SHMEM2_RD(sc, size);
12844         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12845             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12846             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12847                 offset = mf_cfg_offset_value;
12848             }
12849         }
12850     }
12851 
12852     return (offset);
12853 }
12854 
12855 static uint32_t
12856 bxe_pcie_capability_read(struct bxe_softc *sc,
12857                          int    reg,
12858                          int    width)
12859 {
12860     int pcie_reg;
12861 
12862     /* ensure PCIe capability is enabled */
12863     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12864         if (pcie_reg != 0) {
12865             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12866             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12867         }
12868     }
12869 
12870     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12871 
12872     return (0);
12873 }
12874 
12875 static uint8_t
12876 bxe_is_pcie_pending(struct bxe_softc *sc)
12877 {
12878     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12879             PCIM_EXP_STA_TRANSACTION_PND);
12880 }
12881 
12882 /*
12883  * Walk the PCI capabiites list for the device to find what features are
12884  * supported. These capabilites may be enabled/disabled by firmware so it's
12885  * best to walk the list rather than make assumptions.
12886  */
12887 static void
12888 bxe_probe_pci_caps(struct bxe_softc *sc)
12889 {
12890     uint16_t link_status;
12891     int reg;
12892 
12893     /* check if PCI Power Management is enabled */
12894     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12895         if (reg != 0) {
12896             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12897 
12898             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12899             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12900         }
12901     }
12902 
12903     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12904 
12905     /* handle PCIe 2.0 workarounds for 57710 */
12906     if (CHIP_IS_E1(sc)) {
12907         /* workaround for 57710 errata E4_57710_27462 */
12908         sc->devinfo.pcie_link_speed =
12909             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12910 
12911         /* workaround for 57710 errata E4_57710_27488 */
12912         sc->devinfo.pcie_link_width =
12913             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12914         if (sc->devinfo.pcie_link_speed > 1) {
12915             sc->devinfo.pcie_link_width =
12916                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12917         }
12918     } else {
12919         sc->devinfo.pcie_link_speed =
12920             (link_status & PCIM_LINK_STA_SPEED);
12921         sc->devinfo.pcie_link_width =
12922             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12923     }
12924 
12925     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12926           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12927 
12928     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12929     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12930 
12931     /* check if MSI capability is enabled */
12932     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12933         if (reg != 0) {
12934             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
12935 
12936             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
12937             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
12938         }
12939     }
12940 
12941     /* check if MSI-X capability is enabled */
12942     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
12943         if (reg != 0) {
12944             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
12945 
12946             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
12947             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
12948         }
12949     }
12950 }
12951 
12952 static int
12953 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
12954 {
12955     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12956     uint32_t val;
12957 
12958     /* get the outer vlan if we're in switch-dependent mode */
12959 
12960     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
12961     mf_info->ext_id = (uint16_t)val;
12962 
12963     mf_info->multi_vnics_mode = 1;
12964 
12965     if (!VALID_OVLAN(mf_info->ext_id)) {
12966         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
12967         return (1);
12968     }
12969 
12970     /* get the capabilities */
12971     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12972         FUNC_MF_CFG_PROTOCOL_ISCSI) {
12973         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
12974     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12975                FUNC_MF_CFG_PROTOCOL_FCOE) {
12976         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
12977     } else {
12978         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
12979     }
12980 
12981     mf_info->vnics_per_port =
12982         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
12983 
12984     return (0);
12985 }
12986 
12987 static uint32_t
12988 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
12989 {
12990     uint32_t retval = 0;
12991     uint32_t val;
12992 
12993     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
12994 
12995     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
12996         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
12997             retval |= MF_PROTO_SUPPORT_ETHERNET;
12998         }
12999         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13000             retval |= MF_PROTO_SUPPORT_ISCSI;
13001         }
13002         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13003             retval |= MF_PROTO_SUPPORT_FCOE;
13004         }
13005     }
13006 
13007     return (retval);
13008 }
13009 
13010 static int
13011 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13012 {
13013     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13014     uint32_t val;
13015 
13016     /*
13017      * There is no outer vlan if we're in switch-independent mode.
13018      * If the mac is valid then assume multi-function.
13019      */
13020 
13021     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13022 
13023     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13024 
13025     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13026 
13027     mf_info->vnics_per_port =
13028         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13029 
13030     return (0);
13031 }
13032 
13033 static int
13034 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13035 {
13036     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13037     uint32_t e1hov_tag;
13038     uint32_t func_config;
13039     uint32_t niv_config;
13040 
13041     mf_info->multi_vnics_mode = 1;
13042 
13043     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13044     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13045     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13046 
13047     mf_info->ext_id =
13048         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13049                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13050 
13051     mf_info->default_vlan =
13052         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13053                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13054 
13055     mf_info->niv_allowed_priorities =
13056         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13057                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13058 
13059     mf_info->niv_default_cos =
13060         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13061                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13062 
13063     mf_info->afex_vlan_mode =
13064         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13065          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13066 
13067     mf_info->niv_mba_enabled =
13068         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13069          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13070 
13071     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13072 
13073     mf_info->vnics_per_port =
13074         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13075 
13076     return (0);
13077 }
13078 
13079 static int
13080 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13081 {
13082     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13083     uint32_t mf_cfg1;
13084     uint32_t mf_cfg2;
13085     uint32_t ovlan1;
13086     uint32_t ovlan2;
13087     uint8_t i, j;
13088 
13089     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13090           SC_PORT(sc));
13091     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13092           mf_info->mf_config[SC_VN(sc)]);
13093     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13094           mf_info->multi_vnics_mode);
13095     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13096           mf_info->vnics_per_port);
13097     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13098           mf_info->ext_id);
13099     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13100           mf_info->min_bw[0], mf_info->min_bw[1],
13101           mf_info->min_bw[2], mf_info->min_bw[3]);
13102     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13103           mf_info->max_bw[0], mf_info->max_bw[1],
13104           mf_info->max_bw[2], mf_info->max_bw[3]);
13105     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13106           sc->mac_addr_str);
13107 
13108     /* various MF mode sanity checks... */
13109 
13110     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13111         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13112               SC_PORT(sc));
13113         return (1);
13114     }
13115 
13116     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13117         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13118               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13119         return (1);
13120     }
13121 
13122     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13123         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13124         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13125             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13126                   SC_VN(sc), OVLAN(sc));
13127             return (1);
13128         }
13129 
13130         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13131             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13132                   mf_info->multi_vnics_mode, OVLAN(sc));
13133             return (1);
13134         }
13135 
13136         /*
13137          * Verify all functions are either MF or SF mode. If MF, make sure
13138          * sure that all non-hidden functions have a valid ovlan. If SF,
13139          * make sure that all non-hidden functions have an invalid ovlan.
13140          */
13141         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13142             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13143             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13144             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13145                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13146                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13147                 BLOGE(sc, "mf_mode=SD function %d MF config "
13148                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13149                       i, mf_info->multi_vnics_mode, ovlan1);
13150                 return (1);
13151             }
13152         }
13153 
13154         /* Verify all funcs on the same port each have a different ovlan. */
13155         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13156             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13157             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13158             /* iterate from the next function on the port to the max func */
13159             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13160                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13161                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13162                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13163                     VALID_OVLAN(ovlan1) &&
13164                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13165                     VALID_OVLAN(ovlan2) &&
13166                     (ovlan1 == ovlan2)) {
13167                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13168                               "have the same ovlan (%d)\n",
13169                           i, j, ovlan1);
13170                     return (1);
13171                 }
13172             }
13173         }
13174     } /* MULTI_FUNCTION_SD */
13175 
13176     return (0);
13177 }
13178 
13179 static int
13180 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13181 {
13182     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13183     uint32_t val, mac_upper;
13184     uint8_t i, vnic;
13185 
13186     /* initialize mf_info defaults */
13187     mf_info->vnics_per_port   = 1;
13188     mf_info->multi_vnics_mode = FALSE;
13189     mf_info->path_has_ovlan   = FALSE;
13190     mf_info->mf_mode          = SINGLE_FUNCTION;
13191 
13192     if (!CHIP_IS_MF_CAP(sc)) {
13193         return (0);
13194     }
13195 
13196     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13197         BLOGE(sc, "Invalid mf_cfg_base!\n");
13198         return (1);
13199     }
13200 
13201     /* get the MF mode (switch dependent / independent / single-function) */
13202 
13203     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13204 
13205     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13206     {
13207     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13208 
13209         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13210 
13211         /* check for legal upper mac bytes */
13212         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13213             mf_info->mf_mode = MULTI_FUNCTION_SI;
13214         } else {
13215             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13216         }
13217 
13218         break;
13219 
13220     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13221     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13222 
13223         /* get outer vlan configuration */
13224         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13225 
13226         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13227             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13228             mf_info->mf_mode = MULTI_FUNCTION_SD;
13229         } else {
13230             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13231         }
13232 
13233         break;
13234 
13235     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13236 
13237         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13238         return (0);
13239 
13240     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13241 
13242         /*
13243          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13244          * and the MAC address is valid.
13245          */
13246         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13247 
13248         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13249             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13250             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13251         } else {
13252             BLOGE(sc, "Invalid config for AFEX mode\n");
13253         }
13254 
13255         break;
13256 
13257     default:
13258 
13259         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13260               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13261 
13262         return (1);
13263     }
13264 
13265     /* set path mf_mode (which could be different than function mf_mode) */
13266     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13267         mf_info->path_has_ovlan = TRUE;
13268     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13269         /*
13270          * Decide on path multi vnics mode. If we're not in MF mode and in
13271          * 4-port mode, this is good enough to check vnic-0 of the other port
13272          * on the same path
13273          */
13274         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13275             uint8_t other_port = !(PORT_ID(sc) & 1);
13276             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13277 
13278             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13279 
13280             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13281         }
13282     }
13283 
13284     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13285         /* invalid MF config */
13286         if (SC_VN(sc) >= 1) {
13287             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13288             return (1);
13289         }
13290 
13291         return (0);
13292     }
13293 
13294     /* get the MF configuration */
13295     mf_info->mf_config[SC_VN(sc)] =
13296         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13297 
13298     switch(mf_info->mf_mode)
13299     {
13300     case MULTI_FUNCTION_SD:
13301 
13302         bxe_get_shmem_mf_cfg_info_sd(sc);
13303         break;
13304 
13305     case MULTI_FUNCTION_SI:
13306 
13307         bxe_get_shmem_mf_cfg_info_si(sc);
13308         break;
13309 
13310     case MULTI_FUNCTION_AFEX:
13311 
13312         bxe_get_shmem_mf_cfg_info_niv(sc);
13313         break;
13314 
13315     default:
13316 
13317         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13318               mf_info->mf_mode);
13319         return (1);
13320     }
13321 
13322     /* get the congestion management parameters */
13323 
13324     vnic = 0;
13325     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13326         /* get min/max bw */
13327         val = MFCFG_RD(sc, func_mf_config[i].config);
13328         mf_info->min_bw[vnic] =
13329             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13330         mf_info->max_bw[vnic] =
13331             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13332         vnic++;
13333     }
13334 
13335     return (bxe_check_valid_mf_cfg(sc));
13336 }
13337 
13338 static int
13339 bxe_get_shmem_info(struct bxe_softc *sc)
13340 {
13341     int port;
13342     uint32_t mac_hi, mac_lo, val;
13343 
13344     port = SC_PORT(sc);
13345     mac_hi = mac_lo = 0;
13346 
13347     sc->link_params.sc   = sc;
13348     sc->link_params.port = port;
13349 
13350     /* get the hardware config info */
13351     sc->devinfo.hw_config =
13352         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13353     sc->devinfo.hw_config2 =
13354         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13355 
13356     sc->link_params.hw_led_mode =
13357         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13358          SHARED_HW_CFG_LED_MODE_SHIFT);
13359 
13360     /* get the port feature config */
13361     sc->port.config =
13362         SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13363 
13364     /* get the link params */
13365     sc->link_params.speed_cap_mask[0] =
13366         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13367     sc->link_params.speed_cap_mask[1] =
13368         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13369 
13370     /* get the lane config */
13371     sc->link_params.lane_config =
13372         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13373 
13374     /* get the link config */
13375     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13376     sc->port.link_config[ELINK_INT_PHY] = val;
13377     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13378     sc->port.link_config[ELINK_EXT_PHY1] =
13379         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13380 
13381     /* get the override preemphasis flag and enable it or turn it off */
13382     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13383     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13384         sc->link_params.feature_config_flags |=
13385             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13386     } else {
13387         sc->link_params.feature_config_flags &=
13388             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13389     }
13390 
13391     /* get the initial value of the link params */
13392     sc->link_params.multi_phy_config =
13393         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13394 
13395     /* get external phy info */
13396     sc->port.ext_phy_config =
13397         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13398 
13399     /* get the multifunction configuration */
13400     bxe_get_mf_cfg_info(sc);
13401 
13402     /* get the mac address */
13403     if (IS_MF(sc)) {
13404         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13405         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13406     } else {
13407         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13408         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13409     }
13410 
13411     if ((mac_lo == 0) && (mac_hi == 0)) {
13412         *sc->mac_addr_str = 0;
13413         BLOGE(sc, "No Ethernet address programmed!\n");
13414     } else {
13415         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13416         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13417         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13418         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13419         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13420         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13421         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13422                  "%02x:%02x:%02x:%02x:%02x:%02x",
13423                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13424                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13425                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13426         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13427     }
13428 
13429     return (0);
13430 }
13431 
13432 static void
13433 bxe_get_tunable_params(struct bxe_softc *sc)
13434 {
13435     /* sanity checks */
13436 
13437     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13438         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13439         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13440         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13441         bxe_interrupt_mode = INTR_MODE_MSIX;
13442     }
13443 
13444     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13445         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13446         bxe_queue_count = 0;
13447     }
13448 
13449     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13450         if (bxe_max_rx_bufs == 0) {
13451             bxe_max_rx_bufs = RX_BD_USABLE;
13452         } else {
13453             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13454             bxe_max_rx_bufs = 2048;
13455         }
13456     }
13457 
13458     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13459         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13460         bxe_hc_rx_ticks = 25;
13461     }
13462 
13463     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13464         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13465         bxe_hc_tx_ticks = 50;
13466     }
13467 
13468     if (bxe_max_aggregation_size == 0) {
13469         bxe_max_aggregation_size = TPA_AGG_SIZE;
13470     }
13471 
13472     if (bxe_max_aggregation_size > 0xffff) {
13473         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13474               bxe_max_aggregation_size);
13475         bxe_max_aggregation_size = TPA_AGG_SIZE;
13476     }
13477 
13478     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13479         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13480         bxe_mrrs = -1;
13481     }
13482 
13483     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13484         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13485         bxe_autogreeen = 0;
13486     }
13487 
13488     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13489         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13490         bxe_udp_rss = 0;
13491     }
13492 
13493     /* pull in user settings */
13494 
13495     sc->interrupt_mode       = bxe_interrupt_mode;
13496     sc->max_rx_bufs          = bxe_max_rx_bufs;
13497     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13498     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13499     sc->max_aggregation_size = bxe_max_aggregation_size;
13500     sc->mrrs                 = bxe_mrrs;
13501     sc->autogreeen           = bxe_autogreeen;
13502     sc->udp_rss              = bxe_udp_rss;
13503 
13504     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13505         sc->num_queues = 1;
13506     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13507         sc->num_queues =
13508             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13509                 MAX_RSS_CHAINS);
13510         if (sc->num_queues > mp_ncpus) {
13511             sc->num_queues = mp_ncpus;
13512         }
13513     }
13514 
13515     BLOGD(sc, DBG_LOAD,
13516           "User Config: "
13517           "debug=0x%lx "
13518           "interrupt_mode=%d "
13519           "queue_count=%d "
13520           "hc_rx_ticks=%d "
13521           "hc_tx_ticks=%d "
13522           "rx_budget=%d "
13523           "max_aggregation_size=%d "
13524           "mrrs=%d "
13525           "autogreeen=%d "
13526           "udp_rss=%d\n",
13527           bxe_debug,
13528           sc->interrupt_mode,
13529           sc->num_queues,
13530           sc->hc_rx_ticks,
13531           sc->hc_tx_ticks,
13532           bxe_rx_budget,
13533           sc->max_aggregation_size,
13534           sc->mrrs,
13535           sc->autogreeen,
13536           sc->udp_rss);
13537 }
13538 
13539 static int
13540 bxe_media_detect(struct bxe_softc *sc)
13541 {
13542     int port_type;
13543     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13544 
13545     switch (sc->link_params.phy[phy_idx].media_type) {
13546     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13547     case ELINK_ETH_PHY_XFP_FIBER:
13548         BLOGI(sc, "Found 10Gb Fiber media.\n");
13549         sc->media = IFM_10G_SR;
13550         port_type = PORT_FIBRE;
13551         break;
13552     case ELINK_ETH_PHY_SFP_1G_FIBER:
13553         BLOGI(sc, "Found 1Gb Fiber media.\n");
13554         sc->media = IFM_1000_SX;
13555         port_type = PORT_FIBRE;
13556         break;
13557     case ELINK_ETH_PHY_KR:
13558     case ELINK_ETH_PHY_CX4:
13559         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13560         sc->media = IFM_10G_CX4;
13561         port_type = PORT_FIBRE;
13562         break;
13563     case ELINK_ETH_PHY_DA_TWINAX:
13564         BLOGI(sc, "Found 10Gb Twinax media.\n");
13565         sc->media = IFM_10G_TWINAX;
13566         port_type = PORT_DA;
13567         break;
13568     case ELINK_ETH_PHY_BASE_T:
13569         if (sc->link_params.speed_cap_mask[0] &
13570             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13571             BLOGI(sc, "Found 10GBase-T media.\n");
13572             sc->media = IFM_10G_T;
13573             port_type = PORT_TP;
13574         } else {
13575             BLOGI(sc, "Found 1000Base-T media.\n");
13576             sc->media = IFM_1000_T;
13577             port_type = PORT_TP;
13578         }
13579         break;
13580     case ELINK_ETH_PHY_NOT_PRESENT:
13581         BLOGI(sc, "Media not present.\n");
13582         sc->media = 0;
13583         port_type = PORT_OTHER;
13584         break;
13585     case ELINK_ETH_PHY_UNSPECIFIED:
13586     default:
13587         BLOGI(sc, "Unknown media!\n");
13588         sc->media = 0;
13589         port_type = PORT_OTHER;
13590         break;
13591     }
13592     return port_type;
13593 }
13594 
13595 #define GET_FIELD(value, fname)                     \
13596     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13597 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13598 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13599 
13600 static int
13601 bxe_get_igu_cam_info(struct bxe_softc *sc)
13602 {
13603     int pfid = SC_FUNC(sc);
13604     int igu_sb_id;
13605     uint32_t val;
13606     uint8_t fid, igu_sb_cnt = 0;
13607 
13608     sc->igu_base_sb = 0xff;
13609 
13610     if (CHIP_INT_MODE_IS_BC(sc)) {
13611         int vn = SC_VN(sc);
13612         igu_sb_cnt = sc->igu_sb_cnt;
13613         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13614                            FP_SB_MAX_E1x);
13615         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13616                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13617         return (0);
13618     }
13619 
13620     /* IGU in normal mode - read CAM */
13621     for (igu_sb_id = 0;
13622          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13623          igu_sb_id++) {
13624         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13625         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13626             continue;
13627         }
13628         fid = IGU_FID(val);
13629         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13630             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13631                 continue;
13632             }
13633             if (IGU_VEC(val) == 0) {
13634                 /* default status block */
13635                 sc->igu_dsb_id = igu_sb_id;
13636             } else {
13637                 if (sc->igu_base_sb == 0xff) {
13638                     sc->igu_base_sb = igu_sb_id;
13639                 }
13640                 igu_sb_cnt++;
13641             }
13642         }
13643     }
13644 
13645     /*
13646      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13647      * that number of CAM entries will not be equal to the value advertised in
13648      * PCI. Driver should use the minimal value of both as the actual status
13649      * block count
13650      */
13651     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13652 
13653     if (igu_sb_cnt == 0) {
13654         BLOGE(sc, "CAM configuration error\n");
13655         return (-1);
13656     }
13657 
13658     return (0);
13659 }
13660 
13661 /*
13662  * Gather various information from the device config space, the device itself,
13663  * shmem, and the user input.
13664  */
13665 static int
13666 bxe_get_device_info(struct bxe_softc *sc)
13667 {
13668     uint32_t val;
13669     int rc;
13670 
13671     /* Get the data for the device */
13672     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13673     sc->devinfo.device_id    = pci_get_device(sc->dev);
13674     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13675     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13676 
13677     /* get the chip revision (chip metal comes from pci config space) */
13678     sc->devinfo.chip_id     =
13679     sc->link_params.chip_id =
13680         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13681          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13682          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13683          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13684 
13685     /* force 57811 according to MISC register */
13686     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13687         if (CHIP_IS_57810(sc)) {
13688             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13689                                    (sc->devinfo.chip_id & 0x0000ffff));
13690         } else if (CHIP_IS_57810_MF(sc)) {
13691             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13692                                    (sc->devinfo.chip_id & 0x0000ffff));
13693         }
13694         sc->devinfo.chip_id |= 0x1;
13695     }
13696 
13697     BLOGD(sc, DBG_LOAD,
13698           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13699           sc->devinfo.chip_id,
13700           ((sc->devinfo.chip_id >> 16) & 0xffff),
13701           ((sc->devinfo.chip_id >> 12) & 0xf),
13702           ((sc->devinfo.chip_id >>  4) & 0xff),
13703           ((sc->devinfo.chip_id >>  0) & 0xf));
13704 
13705     val = (REG_RD(sc, 0x2874) & 0x55);
13706     if ((sc->devinfo.chip_id & 0x1) ||
13707         (CHIP_IS_E1(sc) && val) ||
13708         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13709         sc->flags |= BXE_ONE_PORT_FLAG;
13710         BLOGD(sc, DBG_LOAD, "single port device\n");
13711     }
13712 
13713     /* set the doorbell size */
13714     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13715 
13716     /* determine whether the device is in 2 port or 4 port mode */
13717     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13718     if (CHIP_IS_E2E3(sc)) {
13719         /*
13720          * Read port4mode_en_ovwr[0]:
13721          *   If 1, four port mode is in port4mode_en_ovwr[1].
13722          *   If 0, four port mode is in port4mode_en[0].
13723          */
13724         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13725         if (val & 1) {
13726             val = ((val >> 1) & 1);
13727         } else {
13728             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13729         }
13730 
13731         sc->devinfo.chip_port_mode =
13732             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13733 
13734         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13735     }
13736 
13737     /* get the function and path info for the device */
13738     bxe_get_function_num(sc);
13739 
13740     /* get the shared memory base address */
13741     sc->devinfo.shmem_base     =
13742     sc->link_params.shmem_base =
13743         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13744     sc->devinfo.shmem2_base =
13745         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13746                                   MISC_REG_GENERIC_CR_0));
13747 
13748     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13749           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13750 
13751     if (!sc->devinfo.shmem_base) {
13752         /* this should ONLY prevent upcoming shmem reads */
13753         BLOGI(sc, "MCP not active\n");
13754         sc->flags |= BXE_NO_MCP_FLAG;
13755         return (0);
13756     }
13757 
13758     /* make sure the shared memory contents are valid */
13759     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13760     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13761         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13762         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13763         return (0);
13764     }
13765     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13766 
13767     /* get the bootcode version */
13768     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13769     snprintf(sc->devinfo.bc_ver_str,
13770              sizeof(sc->devinfo.bc_ver_str),
13771              "%d.%d.%d",
13772              ((sc->devinfo.bc_ver >> 24) & 0xff),
13773              ((sc->devinfo.bc_ver >> 16) & 0xff),
13774              ((sc->devinfo.bc_ver >>  8) & 0xff));
13775     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13776 
13777     /* get the bootcode shmem address */
13778     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13779     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13780 
13781     /* clean indirect addresses as they're not used */
13782     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13783     if (IS_PF(sc)) {
13784         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13785         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13786         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13787         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13788         if (CHIP_IS_E1x(sc)) {
13789             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13790             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13791             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13792             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13793         }
13794 
13795         /*
13796          * Enable internal target-read (in case we are probed after PF
13797          * FLR). Must be done prior to any BAR read access. Only for
13798          * 57712 and up
13799          */
13800         if (!CHIP_IS_E1x(sc)) {
13801             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13802         }
13803     }
13804 
13805     /* get the nvram size */
13806     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13807     sc->devinfo.flash_size =
13808         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13809     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13810 
13811     /* get PCI capabilites */
13812     bxe_probe_pci_caps(sc);
13813 
13814     bxe_set_power_state(sc, PCI_PM_D0);
13815 
13816     /* get various configuration parameters from shmem */
13817     bxe_get_shmem_info(sc);
13818 
13819     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13820         val = pci_read_config(sc->dev,
13821                               (sc->devinfo.pcie_msix_cap_reg +
13822                                PCIR_MSIX_CTRL),
13823                               2);
13824         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13825     } else {
13826         sc->igu_sb_cnt = 1;
13827     }
13828 
13829     sc->igu_base_addr = BAR_IGU_INTMEM;
13830 
13831     /* initialize IGU parameters */
13832     if (CHIP_IS_E1x(sc)) {
13833         sc->devinfo.int_block = INT_BLOCK_HC;
13834         sc->igu_dsb_id = DEF_SB_IGU_ID;
13835         sc->igu_base_sb = 0;
13836     } else {
13837         sc->devinfo.int_block = INT_BLOCK_IGU;
13838 
13839         /* do not allow device reset during IGU info preocessing */
13840         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13841 
13842         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13843 
13844         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13845             int tout = 5000;
13846 
13847             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13848 
13849             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13850             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13851             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13852 
13853             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13854                 tout--;
13855                 DELAY(1000);
13856             }
13857 
13858             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13859                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13860                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13861                 return (-1);
13862             }
13863         }
13864 
13865         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13866             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13867             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13868         } else {
13869             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13870         }
13871 
13872         rc = bxe_get_igu_cam_info(sc);
13873 
13874         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13875 
13876         if (rc) {
13877             return (rc);
13878         }
13879     }
13880 
13881     /*
13882      * Get base FW non-default (fast path) status block ID. This value is
13883      * used to initialize the fw_sb_id saved on the fp/queue structure to
13884      * determine the id used by the FW.
13885      */
13886     if (CHIP_IS_E1x(sc)) {
13887         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13888     } else {
13889         /*
13890          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13891          * the same queue are indicated on the same IGU SB). So we prefer
13892          * FW and IGU SBs to be the same value.
13893          */
13894         sc->base_fw_ndsb = sc->igu_base_sb;
13895     }
13896 
13897     BLOGD(sc, DBG_LOAD,
13898           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13899           sc->igu_dsb_id, sc->igu_base_sb,
13900           sc->igu_sb_cnt, sc->base_fw_ndsb);
13901 
13902     elink_phy_probe(&sc->link_params);
13903 
13904     return (0);
13905 }
13906 
13907 static void
13908 bxe_link_settings_supported(struct bxe_softc *sc,
13909                             uint32_t         switch_cfg)
13910 {
13911     uint32_t cfg_size = 0;
13912     uint32_t idx;
13913     uint8_t port = SC_PORT(sc);
13914 
13915     /* aggregation of supported attributes of all external phys */
13916     sc->port.supported[0] = 0;
13917     sc->port.supported[1] = 0;
13918 
13919     switch (sc->link_params.num_phys) {
13920     case 1:
13921         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13922         cfg_size = 1;
13923         break;
13924     case 2:
13925         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13926         cfg_size = 1;
13927         break;
13928     case 3:
13929         if (sc->link_params.multi_phy_config &
13930             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13931             sc->port.supported[1] =
13932                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13933             sc->port.supported[0] =
13934                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13935         } else {
13936             sc->port.supported[0] =
13937                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13938             sc->port.supported[1] =
13939                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13940         }
13941         cfg_size = 2;
13942         break;
13943     }
13944 
13945     if (!(sc->port.supported[0] || sc->port.supported[1])) {
13946         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
13947               SHMEM_RD(sc,
13948                        dev_info.port_hw_config[port].external_phy_config),
13949               SHMEM_RD(sc,
13950                        dev_info.port_hw_config[port].external_phy_config2));
13951         return;
13952     }
13953 
13954     if (CHIP_IS_E3(sc))
13955         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
13956     else {
13957         switch (switch_cfg) {
13958         case ELINK_SWITCH_CFG_1G:
13959             sc->port.phy_addr =
13960                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
13961             break;
13962         case ELINK_SWITCH_CFG_10G:
13963             sc->port.phy_addr =
13964                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
13965             break;
13966         default:
13967             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
13968                   sc->port.link_config[0]);
13969             return;
13970         }
13971     }
13972 
13973     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
13974 
13975     /* mask what we support according to speed_cap_mask per configuration */
13976     for (idx = 0; idx < cfg_size; idx++) {
13977         if (!(sc->link_params.speed_cap_mask[idx] &
13978               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
13979             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
13980         }
13981 
13982         if (!(sc->link_params.speed_cap_mask[idx] &
13983               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
13984             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
13985         }
13986 
13987         if (!(sc->link_params.speed_cap_mask[idx] &
13988               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
13989             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
13990         }
13991 
13992         if (!(sc->link_params.speed_cap_mask[idx] &
13993               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
13994             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
13995         }
13996 
13997         if (!(sc->link_params.speed_cap_mask[idx] &
13998               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
13999             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14000         }
14001 
14002         if (!(sc->link_params.speed_cap_mask[idx] &
14003               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14004             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14005         }
14006 
14007         if (!(sc->link_params.speed_cap_mask[idx] &
14008               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14009             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14010         }
14011 
14012         if (!(sc->link_params.speed_cap_mask[idx] &
14013               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14014             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14015         }
14016     }
14017 
14018     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14019           sc->port.supported[0], sc->port.supported[1]);
14020 }
14021 
14022 static void
14023 bxe_link_settings_requested(struct bxe_softc *sc)
14024 {
14025     uint32_t link_config;
14026     uint32_t idx;
14027     uint32_t cfg_size = 0;
14028 
14029     sc->port.advertising[0] = 0;
14030     sc->port.advertising[1] = 0;
14031 
14032     switch (sc->link_params.num_phys) {
14033     case 1:
14034     case 2:
14035         cfg_size = 1;
14036         break;
14037     case 3:
14038         cfg_size = 2;
14039         break;
14040     }
14041 
14042     for (idx = 0; idx < cfg_size; idx++) {
14043         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14044         link_config = sc->port.link_config[idx];
14045 
14046         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14047         case PORT_FEATURE_LINK_SPEED_AUTO:
14048             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14049                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14050                 sc->port.advertising[idx] |= sc->port.supported[idx];
14051                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14052                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14053                     sc->port.advertising[idx] |=
14054                         (ELINK_SUPPORTED_100baseT_Half |
14055                          ELINK_SUPPORTED_100baseT_Full);
14056             } else {
14057                 /* force 10G, no AN */
14058                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14059                 sc->port.advertising[idx] |=
14060                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14061                 continue;
14062             }
14063             break;
14064 
14065         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14066             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14067                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14068                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14069                                               ADVERTISED_TP);
14070             } else {
14071                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14072                           "speed_cap_mask=0x%08x\n",
14073                       link_config, sc->link_params.speed_cap_mask[idx]);
14074                 return;
14075             }
14076             break;
14077 
14078         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14079             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14080                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14081                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14082                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14083                                               ADVERTISED_TP);
14084             } else {
14085                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14086                           "speed_cap_mask=0x%08x\n",
14087                       link_config, sc->link_params.speed_cap_mask[idx]);
14088                 return;
14089             }
14090             break;
14091 
14092         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14093             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14094                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14095                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14096                                               ADVERTISED_TP);
14097             } else {
14098                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14099                           "speed_cap_mask=0x%08x\n",
14100                       link_config, sc->link_params.speed_cap_mask[idx]);
14101                 return;
14102             }
14103             break;
14104 
14105         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14106             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14107                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14108                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14109                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14110                                               ADVERTISED_TP);
14111             } else {
14112                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14113                           "speed_cap_mask=0x%08x\n",
14114                       link_config, sc->link_params.speed_cap_mask[idx]);
14115                 return;
14116             }
14117             break;
14118 
14119         case PORT_FEATURE_LINK_SPEED_1G:
14120             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14121                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14122                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14123                                               ADVERTISED_TP);
14124             } else {
14125                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14126                           "speed_cap_mask=0x%08x\n",
14127                       link_config, sc->link_params.speed_cap_mask[idx]);
14128                 return;
14129             }
14130             break;
14131 
14132         case PORT_FEATURE_LINK_SPEED_2_5G:
14133             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14134                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14135                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14136                                               ADVERTISED_TP);
14137             } else {
14138                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14139                           "speed_cap_mask=0x%08x\n",
14140                       link_config, sc->link_params.speed_cap_mask[idx]);
14141                 return;
14142             }
14143             break;
14144 
14145         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14146             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14147                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14148                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14149                                               ADVERTISED_FIBRE);
14150             } else {
14151                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14152                           "speed_cap_mask=0x%08x\n",
14153                       link_config, sc->link_params.speed_cap_mask[idx]);
14154                 return;
14155             }
14156             break;
14157 
14158         case PORT_FEATURE_LINK_SPEED_20G:
14159             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14160             break;
14161 
14162         default:
14163             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14164                       "speed_cap_mask=0x%08x\n",
14165                   link_config, sc->link_params.speed_cap_mask[idx]);
14166             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14167             sc->port.advertising[idx] = sc->port.supported[idx];
14168             break;
14169         }
14170 
14171         sc->link_params.req_flow_ctrl[idx] =
14172             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14173 
14174         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14175             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14176                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14177             } else {
14178                 bxe_set_requested_fc(sc);
14179             }
14180         }
14181 
14182         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14183                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14184               sc->link_params.req_line_speed[idx],
14185               sc->link_params.req_duplex[idx],
14186               sc->link_params.req_flow_ctrl[idx],
14187               sc->port.advertising[idx]);
14188     }
14189 }
14190 
14191 static void
14192 bxe_get_phy_info(struct bxe_softc *sc)
14193 {
14194     uint8_t port = SC_PORT(sc);
14195     uint32_t config = sc->port.config;
14196     uint32_t eee_mode;
14197 
14198     /* shmem data already read in bxe_get_shmem_info() */
14199 
14200     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14201                         "link_config0=0x%08x\n",
14202                sc->link_params.lane_config,
14203                sc->link_params.speed_cap_mask[0],
14204                sc->port.link_config[0]);
14205 
14206     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14207     bxe_link_settings_requested(sc);
14208 
14209     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14210         sc->link_params.feature_config_flags |=
14211             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14212     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14213         sc->link_params.feature_config_flags &=
14214             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14215     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14216         sc->link_params.feature_config_flags |=
14217             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14218     }
14219 
14220     /* configure link feature according to nvram value */
14221     eee_mode =
14222         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14223           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14224          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14225     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14226         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14227                                     ELINK_EEE_MODE_ENABLE_LPI |
14228                                     ELINK_EEE_MODE_OUTPUT_TIME);
14229     } else {
14230         sc->link_params.eee_mode = 0;
14231     }
14232 
14233     /* get the media type */
14234     bxe_media_detect(sc);
14235 }
14236 
14237 static void
14238 bxe_get_params(struct bxe_softc *sc)
14239 {
14240     /* get user tunable params */
14241     bxe_get_tunable_params(sc);
14242 
14243     /* select the RX and TX ring sizes */
14244     sc->tx_ring_size = TX_BD_USABLE;
14245     sc->rx_ring_size = RX_BD_USABLE;
14246 
14247     /* XXX disable WoL */
14248     sc->wol = 0;
14249 }
14250 
14251 static void
14252 bxe_set_modes_bitmap(struct bxe_softc *sc)
14253 {
14254     uint32_t flags = 0;
14255 
14256     if (CHIP_REV_IS_FPGA(sc)) {
14257         SET_FLAGS(flags, MODE_FPGA);
14258     } else if (CHIP_REV_IS_EMUL(sc)) {
14259         SET_FLAGS(flags, MODE_EMUL);
14260     } else {
14261         SET_FLAGS(flags, MODE_ASIC);
14262     }
14263 
14264     if (CHIP_IS_MODE_4_PORT(sc)) {
14265         SET_FLAGS(flags, MODE_PORT4);
14266     } else {
14267         SET_FLAGS(flags, MODE_PORT2);
14268     }
14269 
14270     if (CHIP_IS_E2(sc)) {
14271         SET_FLAGS(flags, MODE_E2);
14272     } else if (CHIP_IS_E3(sc)) {
14273         SET_FLAGS(flags, MODE_E3);
14274         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14275             SET_FLAGS(flags, MODE_E3_A0);
14276         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14277             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14278         }
14279     }
14280 
14281     if (IS_MF(sc)) {
14282         SET_FLAGS(flags, MODE_MF);
14283         switch (sc->devinfo.mf_info.mf_mode) {
14284         case MULTI_FUNCTION_SD:
14285             SET_FLAGS(flags, MODE_MF_SD);
14286             break;
14287         case MULTI_FUNCTION_SI:
14288             SET_FLAGS(flags, MODE_MF_SI);
14289             break;
14290         case MULTI_FUNCTION_AFEX:
14291             SET_FLAGS(flags, MODE_MF_AFEX);
14292             break;
14293         }
14294     } else {
14295         SET_FLAGS(flags, MODE_SF);
14296     }
14297 
14298 #if defined(__LITTLE_ENDIAN)
14299     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14300 #else /* __BIG_ENDIAN */
14301     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14302 #endif
14303 
14304     INIT_MODE_FLAGS(sc) = flags;
14305 }
14306 
14307 static int
14308 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14309 {
14310     struct bxe_fastpath *fp;
14311     bus_addr_t busaddr;
14312     int max_agg_queues;
14313     int max_segments;
14314     bus_size_t max_size;
14315     bus_size_t max_seg_size;
14316     char buf[32];
14317     int rc;
14318     int i, j;
14319 
14320     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14321 
14322     /* allocate the parent bus DMA tag */
14323     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14324                             1,                        /* alignment */
14325                             0,                        /* boundary limit */
14326                             BUS_SPACE_MAXADDR,        /* restricted low */
14327                             BUS_SPACE_MAXADDR,        /* restricted hi */
14328                             NULL,                     /* addr filter() */
14329                             NULL,                     /* addr filter() arg */
14330                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14331                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14332                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14333                             0,                        /* flags */
14334                             NULL,                     /* lock() */
14335                             NULL,                     /* lock() arg */
14336                             &sc->parent_dma_tag);     /* returned dma tag */
14337     if (rc != 0) {
14338         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14339         return (1);
14340     }
14341 
14342     /************************/
14343     /* DEFAULT STATUS BLOCK */
14344     /************************/
14345 
14346     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14347                       &sc->def_sb_dma, "default status block") != 0) {
14348         /* XXX */
14349         bus_dma_tag_destroy(sc->parent_dma_tag);
14350         return (1);
14351     }
14352 
14353     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14354 
14355     /***************/
14356     /* EVENT QUEUE */
14357     /***************/
14358 
14359     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14360                       &sc->eq_dma, "event queue") != 0) {
14361         /* XXX */
14362         bxe_dma_free(sc, &sc->def_sb_dma);
14363         sc->def_sb = NULL;
14364         bus_dma_tag_destroy(sc->parent_dma_tag);
14365         return (1);
14366     }
14367 
14368     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14369 
14370     /*************/
14371     /* SLOW PATH */
14372     /*************/
14373 
14374     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14375                       &sc->sp_dma, "slow path") != 0) {
14376         /* XXX */
14377         bxe_dma_free(sc, &sc->eq_dma);
14378         sc->eq = NULL;
14379         bxe_dma_free(sc, &sc->def_sb_dma);
14380         sc->def_sb = NULL;
14381         bus_dma_tag_destroy(sc->parent_dma_tag);
14382         return (1);
14383     }
14384 
14385     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14386 
14387     /*******************/
14388     /* SLOW PATH QUEUE */
14389     /*******************/
14390 
14391     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14392                       &sc->spq_dma, "slow path queue") != 0) {
14393         /* XXX */
14394         bxe_dma_free(sc, &sc->sp_dma);
14395         sc->sp = NULL;
14396         bxe_dma_free(sc, &sc->eq_dma);
14397         sc->eq = NULL;
14398         bxe_dma_free(sc, &sc->def_sb_dma);
14399         sc->def_sb = NULL;
14400         bus_dma_tag_destroy(sc->parent_dma_tag);
14401         return (1);
14402     }
14403 
14404     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14405 
14406     /***************************/
14407     /* FW DECOMPRESSION BUFFER */
14408     /***************************/
14409 
14410     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14411                       "fw decompression buffer") != 0) {
14412         /* XXX */
14413         bxe_dma_free(sc, &sc->spq_dma);
14414         sc->spq = NULL;
14415         bxe_dma_free(sc, &sc->sp_dma);
14416         sc->sp = NULL;
14417         bxe_dma_free(sc, &sc->eq_dma);
14418         sc->eq = NULL;
14419         bxe_dma_free(sc, &sc->def_sb_dma);
14420         sc->def_sb = NULL;
14421         bus_dma_tag_destroy(sc->parent_dma_tag);
14422         return (1);
14423     }
14424 
14425     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14426 
14427     if ((sc->gz_strm =
14428          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14429         /* XXX */
14430         bxe_dma_free(sc, &sc->gz_buf_dma);
14431         sc->gz_buf = NULL;
14432         bxe_dma_free(sc, &sc->spq_dma);
14433         sc->spq = NULL;
14434         bxe_dma_free(sc, &sc->sp_dma);
14435         sc->sp = NULL;
14436         bxe_dma_free(sc, &sc->eq_dma);
14437         sc->eq = NULL;
14438         bxe_dma_free(sc, &sc->def_sb_dma);
14439         sc->def_sb = NULL;
14440         bus_dma_tag_destroy(sc->parent_dma_tag);
14441         return (1);
14442     }
14443 
14444     /*************/
14445     /* FASTPATHS */
14446     /*************/
14447 
14448     /* allocate DMA memory for each fastpath structure */
14449     for (i = 0; i < sc->num_queues; i++) {
14450         fp = &sc->fp[i];
14451         fp->sc    = sc;
14452         fp->index = i;
14453 
14454         /*******************/
14455         /* FP STATUS BLOCK */
14456         /*******************/
14457 
14458         snprintf(buf, sizeof(buf), "fp %d status block", i);
14459         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14460                           &fp->sb_dma, buf) != 0) {
14461             /* XXX unwind and free previous fastpath allocations */
14462             BLOGE(sc, "Failed to alloc %s\n", buf);
14463             return (1);
14464         } else {
14465             if (CHIP_IS_E2E3(sc)) {
14466                 fp->status_block.e2_sb =
14467                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14468             } else {
14469                 fp->status_block.e1x_sb =
14470                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14471             }
14472         }
14473 
14474         /******************/
14475         /* FP TX BD CHAIN */
14476         /******************/
14477 
14478         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14479         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14480                           &fp->tx_dma, buf) != 0) {
14481             /* XXX unwind and free previous fastpath allocations */
14482             BLOGE(sc, "Failed to alloc %s\n", buf);
14483             return (1);
14484         } else {
14485             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14486         }
14487 
14488         /* link together the tx bd chain pages */
14489         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14490             /* index into the tx bd chain array to last entry per page */
14491             struct eth_tx_next_bd *tx_next_bd =
14492                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14493             /* point to the next page and wrap from last page */
14494             busaddr = (fp->tx_dma.paddr +
14495                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14496             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14497             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14498         }
14499 
14500         /******************/
14501         /* FP RX BD CHAIN */
14502         /******************/
14503 
14504         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14505         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14506                           &fp->rx_dma, buf) != 0) {
14507             /* XXX unwind and free previous fastpath allocations */
14508             BLOGE(sc, "Failed to alloc %s\n", buf);
14509             return (1);
14510         } else {
14511             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14512         }
14513 
14514         /* link together the rx bd chain pages */
14515         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14516             /* index into the rx bd chain array to last entry per page */
14517             struct eth_rx_bd *rx_bd =
14518                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14519             /* point to the next page and wrap from last page */
14520             busaddr = (fp->rx_dma.paddr +
14521                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14522             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14523             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14524         }
14525 
14526         /*******************/
14527         /* FP RX RCQ CHAIN */
14528         /*******************/
14529 
14530         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14531         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14532                           &fp->rcq_dma, buf) != 0) {
14533             /* XXX unwind and free previous fastpath allocations */
14534             BLOGE(sc, "Failed to alloc %s\n", buf);
14535             return (1);
14536         } else {
14537             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14538         }
14539 
14540         /* link together the rcq chain pages */
14541         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14542             /* index into the rcq chain array to last entry per page */
14543             struct eth_rx_cqe_next_page *rx_cqe_next =
14544                 (struct eth_rx_cqe_next_page *)
14545                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14546             /* point to the next page and wrap from last page */
14547             busaddr = (fp->rcq_dma.paddr +
14548                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14549             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14550             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14551         }
14552 
14553         /*******************/
14554         /* FP RX SGE CHAIN */
14555         /*******************/
14556 
14557         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14558         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14559                           &fp->rx_sge_dma, buf) != 0) {
14560             /* XXX unwind and free previous fastpath allocations */
14561             BLOGE(sc, "Failed to alloc %s\n", buf);
14562             return (1);
14563         } else {
14564             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14565         }
14566 
14567         /* link together the sge chain pages */
14568         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14569             /* index into the rcq chain array to last entry per page */
14570             struct eth_rx_sge *rx_sge =
14571                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14572             /* point to the next page and wrap from last page */
14573             busaddr = (fp->rx_sge_dma.paddr +
14574                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14575             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14576             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14577         }
14578 
14579         /***********************/
14580         /* FP TX MBUF DMA MAPS */
14581         /***********************/
14582 
14583         /* set required sizes before mapping to conserve resources */
14584         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14585             max_size     = BXE_TSO_MAX_SIZE;
14586             max_segments = BXE_TSO_MAX_SEGMENTS;
14587             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14588         } else {
14589             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14590             max_segments = BXE_MAX_SEGMENTS;
14591             max_seg_size = MCLBYTES;
14592         }
14593 
14594         /* create a dma tag for the tx mbufs */
14595         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14596                                 1,                  /* alignment */
14597                                 0,                  /* boundary limit */
14598                                 BUS_SPACE_MAXADDR,  /* restricted low */
14599                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14600                                 NULL,               /* addr filter() */
14601                                 NULL,               /* addr filter() arg */
14602                                 max_size,           /* max map size */
14603                                 max_segments,       /* num discontinuous */
14604                                 max_seg_size,       /* max seg size */
14605                                 0,                  /* flags */
14606                                 NULL,               /* lock() */
14607                                 NULL,               /* lock() arg */
14608                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14609         if (rc != 0) {
14610             /* XXX unwind and free previous fastpath allocations */
14611             BLOGE(sc, "Failed to create dma tag for "
14612                       "'fp %d tx mbufs' (%d)\n", i, rc);
14613             return (1);
14614         }
14615 
14616         /* create dma maps for each of the tx mbuf clusters */
14617         for (j = 0; j < TX_BD_TOTAL; j++) {
14618             if (bus_dmamap_create(fp->tx_mbuf_tag,
14619                                   BUS_DMA_NOWAIT,
14620                                   &fp->tx_mbuf_chain[j].m_map)) {
14621                 /* XXX unwind and free previous fastpath allocations */
14622                 BLOGE(sc, "Failed to create dma map for "
14623                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14624                 return (1);
14625             }
14626         }
14627 
14628         /***********************/
14629         /* FP RX MBUF DMA MAPS */
14630         /***********************/
14631 
14632         /* create a dma tag for the rx mbufs */
14633         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14634                                 1,                  /* alignment */
14635                                 0,                  /* boundary limit */
14636                                 BUS_SPACE_MAXADDR,  /* restricted low */
14637                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14638                                 NULL,               /* addr filter() */
14639                                 NULL,               /* addr filter() arg */
14640                                 MJUM9BYTES,         /* max map size */
14641                                 1,                  /* num discontinuous */
14642                                 MJUM9BYTES,         /* max seg size */
14643                                 0,                  /* flags */
14644                                 NULL,               /* lock() */
14645                                 NULL,               /* lock() arg */
14646                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14647         if (rc != 0) {
14648             /* XXX unwind and free previous fastpath allocations */
14649             BLOGE(sc, "Failed to create dma tag for "
14650                       "'fp %d rx mbufs' (%d)\n", i, rc);
14651             return (1);
14652         }
14653 
14654         /* create dma maps for each of the rx mbuf clusters */
14655         for (j = 0; j < RX_BD_TOTAL; j++) {
14656             if (bus_dmamap_create(fp->rx_mbuf_tag,
14657                                   BUS_DMA_NOWAIT,
14658                                   &fp->rx_mbuf_chain[j].m_map)) {
14659                 /* XXX unwind and free previous fastpath allocations */
14660                 BLOGE(sc, "Failed to create dma map for "
14661                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14662                 return (1);
14663             }
14664         }
14665 
14666         /* create dma map for the spare rx mbuf cluster */
14667         if (bus_dmamap_create(fp->rx_mbuf_tag,
14668                               BUS_DMA_NOWAIT,
14669                               &fp->rx_mbuf_spare_map)) {
14670             /* XXX unwind and free previous fastpath allocations */
14671             BLOGE(sc, "Failed to create dma map for "
14672                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14673             return (1);
14674         }
14675 
14676         /***************************/
14677         /* FP RX SGE MBUF DMA MAPS */
14678         /***************************/
14679 
14680         /* create a dma tag for the rx sge mbufs */
14681         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14682                                 1,                  /* alignment */
14683                                 0,                  /* boundary limit */
14684                                 BUS_SPACE_MAXADDR,  /* restricted low */
14685                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14686                                 NULL,               /* addr filter() */
14687                                 NULL,               /* addr filter() arg */
14688                                 BCM_PAGE_SIZE,      /* max map size */
14689                                 1,                  /* num discontinuous */
14690                                 BCM_PAGE_SIZE,      /* max seg size */
14691                                 0,                  /* flags */
14692                                 NULL,               /* lock() */
14693                                 NULL,               /* lock() arg */
14694                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14695         if (rc != 0) {
14696             /* XXX unwind and free previous fastpath allocations */
14697             BLOGE(sc, "Failed to create dma tag for "
14698                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14699             return (1);
14700         }
14701 
14702         /* create dma maps for the rx sge mbuf clusters */
14703         for (j = 0; j < RX_SGE_TOTAL; j++) {
14704             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14705                                   BUS_DMA_NOWAIT,
14706                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14707                 /* XXX unwind and free previous fastpath allocations */
14708                 BLOGE(sc, "Failed to create dma map for "
14709                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14710                 return (1);
14711             }
14712         }
14713 
14714         /* create dma map for the spare rx sge mbuf cluster */
14715         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14716                               BUS_DMA_NOWAIT,
14717                               &fp->rx_sge_mbuf_spare_map)) {
14718             /* XXX unwind and free previous fastpath allocations */
14719             BLOGE(sc, "Failed to create dma map for "
14720                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14721             return (1);
14722         }
14723 
14724         /***************************/
14725         /* FP RX TPA MBUF DMA MAPS */
14726         /***************************/
14727 
14728         /* create dma maps for the rx tpa mbuf clusters */
14729         max_agg_queues = MAX_AGG_QS(sc);
14730 
14731         for (j = 0; j < max_agg_queues; j++) {
14732             if (bus_dmamap_create(fp->rx_mbuf_tag,
14733                                   BUS_DMA_NOWAIT,
14734                                   &fp->rx_tpa_info[j].bd.m_map)) {
14735                 /* XXX unwind and free previous fastpath allocations */
14736                 BLOGE(sc, "Failed to create dma map for "
14737                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14738                 return (1);
14739             }
14740         }
14741 
14742         /* create dma map for the spare rx tpa mbuf cluster */
14743         if (bus_dmamap_create(fp->rx_mbuf_tag,
14744                               BUS_DMA_NOWAIT,
14745                               &fp->rx_tpa_info_mbuf_spare_map)) {
14746             /* XXX unwind and free previous fastpath allocations */
14747             BLOGE(sc, "Failed to create dma map for "
14748                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14749             return (1);
14750         }
14751 
14752         bxe_init_sge_ring_bit_mask(fp);
14753     }
14754 
14755     return (0);
14756 }
14757 
14758 static void
14759 bxe_free_hsi_mem(struct bxe_softc *sc)
14760 {
14761     struct bxe_fastpath *fp;
14762     int max_agg_queues;
14763     int i, j;
14764 
14765     if (sc->parent_dma_tag == NULL) {
14766         return; /* assume nothing was allocated */
14767     }
14768 
14769     for (i = 0; i < sc->num_queues; i++) {
14770         fp = &sc->fp[i];
14771 
14772         /*******************/
14773         /* FP STATUS BLOCK */
14774         /*******************/
14775 
14776         bxe_dma_free(sc, &fp->sb_dma);
14777         memset(&fp->status_block, 0, sizeof(fp->status_block));
14778 
14779         /******************/
14780         /* FP TX BD CHAIN */
14781         /******************/
14782 
14783         bxe_dma_free(sc, &fp->tx_dma);
14784         fp->tx_chain = NULL;
14785 
14786         /******************/
14787         /* FP RX BD CHAIN */
14788         /******************/
14789 
14790         bxe_dma_free(sc, &fp->rx_dma);
14791         fp->rx_chain = NULL;
14792 
14793         /*******************/
14794         /* FP RX RCQ CHAIN */
14795         /*******************/
14796 
14797         bxe_dma_free(sc, &fp->rcq_dma);
14798         fp->rcq_chain = NULL;
14799 
14800         /*******************/
14801         /* FP RX SGE CHAIN */
14802         /*******************/
14803 
14804         bxe_dma_free(sc, &fp->rx_sge_dma);
14805         fp->rx_sge_chain = NULL;
14806 
14807         /***********************/
14808         /* FP TX MBUF DMA MAPS */
14809         /***********************/
14810 
14811         if (fp->tx_mbuf_tag != NULL) {
14812             for (j = 0; j < TX_BD_TOTAL; j++) {
14813                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14814                     bus_dmamap_unload(fp->tx_mbuf_tag,
14815                                       fp->tx_mbuf_chain[j].m_map);
14816                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14817                                        fp->tx_mbuf_chain[j].m_map);
14818                 }
14819             }
14820 
14821             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14822             fp->tx_mbuf_tag = NULL;
14823         }
14824 
14825         /***********************/
14826         /* FP RX MBUF DMA MAPS */
14827         /***********************/
14828 
14829         if (fp->rx_mbuf_tag != NULL) {
14830             for (j = 0; j < RX_BD_TOTAL; j++) {
14831                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14832                     bus_dmamap_unload(fp->rx_mbuf_tag,
14833                                       fp->rx_mbuf_chain[j].m_map);
14834                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14835                                        fp->rx_mbuf_chain[j].m_map);
14836                 }
14837             }
14838 
14839             if (fp->rx_mbuf_spare_map != NULL) {
14840                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14841                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14842             }
14843 
14844             /***************************/
14845             /* FP RX TPA MBUF DMA MAPS */
14846             /***************************/
14847 
14848             max_agg_queues = MAX_AGG_QS(sc);
14849 
14850             for (j = 0; j < max_agg_queues; j++) {
14851                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14852                     bus_dmamap_unload(fp->rx_mbuf_tag,
14853                                       fp->rx_tpa_info[j].bd.m_map);
14854                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14855                                        fp->rx_tpa_info[j].bd.m_map);
14856                 }
14857             }
14858 
14859             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14860                 bus_dmamap_unload(fp->rx_mbuf_tag,
14861                                   fp->rx_tpa_info_mbuf_spare_map);
14862                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14863                                    fp->rx_tpa_info_mbuf_spare_map);
14864             }
14865 
14866             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14867             fp->rx_mbuf_tag = NULL;
14868         }
14869 
14870         /***************************/
14871         /* FP RX SGE MBUF DMA MAPS */
14872         /***************************/
14873 
14874         if (fp->rx_sge_mbuf_tag != NULL) {
14875             for (j = 0; j < RX_SGE_TOTAL; j++) {
14876                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14877                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14878                                       fp->rx_sge_mbuf_chain[j].m_map);
14879                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14880                                        fp->rx_sge_mbuf_chain[j].m_map);
14881                 }
14882             }
14883 
14884             if (fp->rx_sge_mbuf_spare_map != NULL) {
14885                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14886                                   fp->rx_sge_mbuf_spare_map);
14887                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14888                                    fp->rx_sge_mbuf_spare_map);
14889             }
14890 
14891             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14892             fp->rx_sge_mbuf_tag = NULL;
14893         }
14894     }
14895 
14896     /***************************/
14897     /* FW DECOMPRESSION BUFFER */
14898     /***************************/
14899 
14900     bxe_dma_free(sc, &sc->gz_buf_dma);
14901     sc->gz_buf = NULL;
14902     free(sc->gz_strm, M_DEVBUF);
14903     sc->gz_strm = NULL;
14904 
14905     /*******************/
14906     /* SLOW PATH QUEUE */
14907     /*******************/
14908 
14909     bxe_dma_free(sc, &sc->spq_dma);
14910     sc->spq = NULL;
14911 
14912     /*************/
14913     /* SLOW PATH */
14914     /*************/
14915 
14916     bxe_dma_free(sc, &sc->sp_dma);
14917     sc->sp = NULL;
14918 
14919     /***************/
14920     /* EVENT QUEUE */
14921     /***************/
14922 
14923     bxe_dma_free(sc, &sc->eq_dma);
14924     sc->eq = NULL;
14925 
14926     /************************/
14927     /* DEFAULT STATUS BLOCK */
14928     /************************/
14929 
14930     bxe_dma_free(sc, &sc->def_sb_dma);
14931     sc->def_sb = NULL;
14932 
14933     bus_dma_tag_destroy(sc->parent_dma_tag);
14934     sc->parent_dma_tag = NULL;
14935 }
14936 
14937 /*
14938  * Previous driver DMAE transaction may have occurred when pre-boot stage
14939  * ended and boot began. This would invalidate the addresses of the
14940  * transaction, resulting in was-error bit set in the PCI causing all
14941  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
14942  * the interrupt which detected this from the pglueb and the was-done bit
14943  */
14944 static void
14945 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
14946 {
14947     uint32_t val;
14948 
14949     if (!CHIP_IS_E1x(sc)) {
14950         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
14951         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
14952             BLOGD(sc, DBG_LOAD,
14953                   "Clearing 'was-error' bit that was set in pglueb");
14954             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
14955         }
14956     }
14957 }
14958 
14959 static int
14960 bxe_prev_mcp_done(struct bxe_softc *sc)
14961 {
14962     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
14963                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
14964     if (!rc) {
14965         BLOGE(sc, "MCP response failure, aborting\n");
14966         return (-1);
14967     }
14968 
14969     return (0);
14970 }
14971 
14972 static struct bxe_prev_list_node *
14973 bxe_prev_path_get_entry(struct bxe_softc *sc)
14974 {
14975     struct bxe_prev_list_node *tmp;
14976 
14977     LIST_FOREACH(tmp, &bxe_prev_list, node) {
14978         if ((sc->pcie_bus == tmp->bus) &&
14979             (sc->pcie_device == tmp->slot) &&
14980             (SC_PATH(sc) == tmp->path)) {
14981             return (tmp);
14982         }
14983     }
14984 
14985     return (NULL);
14986 }
14987 
14988 static uint8_t
14989 bxe_prev_is_path_marked(struct bxe_softc *sc)
14990 {
14991     struct bxe_prev_list_node *tmp;
14992     int rc = FALSE;
14993 
14994     mtx_lock(&bxe_prev_mtx);
14995 
14996     tmp = bxe_prev_path_get_entry(sc);
14997     if (tmp) {
14998         if (tmp->aer) {
14999             BLOGD(sc, DBG_LOAD,
15000                   "Path %d/%d/%d was marked by AER\n",
15001                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15002         } else {
15003             rc = TRUE;
15004             BLOGD(sc, DBG_LOAD,
15005                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15006                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15007         }
15008     }
15009 
15010     mtx_unlock(&bxe_prev_mtx);
15011 
15012     return (rc);
15013 }
15014 
15015 static int
15016 bxe_prev_mark_path(struct bxe_softc *sc,
15017                    uint8_t          after_undi)
15018 {
15019     struct bxe_prev_list_node *tmp;
15020 
15021     mtx_lock(&bxe_prev_mtx);
15022 
15023     /* Check whether the entry for this path already exists */
15024     tmp = bxe_prev_path_get_entry(sc);
15025     if (tmp) {
15026         if (!tmp->aer) {
15027             BLOGD(sc, DBG_LOAD,
15028                   "Re-marking AER in path %d/%d/%d\n",
15029                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15030         } else {
15031             BLOGD(sc, DBG_LOAD,
15032                   "Removing AER indication from path %d/%d/%d\n",
15033                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15034             tmp->aer = 0;
15035         }
15036 
15037         mtx_unlock(&bxe_prev_mtx);
15038         return (0);
15039     }
15040 
15041     mtx_unlock(&bxe_prev_mtx);
15042 
15043     /* Create an entry for this path and add it */
15044     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15045                  (M_NOWAIT | M_ZERO));
15046     if (!tmp) {
15047         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15048         return (-1);
15049     }
15050 
15051     tmp->bus  = sc->pcie_bus;
15052     tmp->slot = sc->pcie_device;
15053     tmp->path = SC_PATH(sc);
15054     tmp->aer  = 0;
15055     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15056 
15057     mtx_lock(&bxe_prev_mtx);
15058 
15059     BLOGD(sc, DBG_LOAD,
15060           "Marked path %d/%d/%d - finished previous unload\n",
15061           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15062     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15063 
15064     mtx_unlock(&bxe_prev_mtx);
15065 
15066     return (0);
15067 }
15068 
15069 static int
15070 bxe_do_flr(struct bxe_softc *sc)
15071 {
15072     int i;
15073 
15074     /* only E2 and onwards support FLR */
15075     if (CHIP_IS_E1x(sc)) {
15076         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15077         return (-1);
15078     }
15079 
15080     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15081     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15082         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15083               sc->devinfo.bc_ver);
15084         return (-1);
15085     }
15086 
15087     /* Wait for Transaction Pending bit clean */
15088     for (i = 0; i < 4; i++) {
15089         if (i) {
15090             DELAY(((1 << (i - 1)) * 100) * 1000);
15091         }
15092 
15093         if (!bxe_is_pcie_pending(sc)) {
15094             goto clear;
15095         }
15096     }
15097 
15098     BLOGE(sc, "PCIE transaction is not cleared, "
15099               "proceeding with reset anyway\n");
15100 
15101 clear:
15102 
15103     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15104     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15105 
15106     return (0);
15107 }
15108 
15109 struct bxe_mac_vals {
15110     uint32_t xmac_addr;
15111     uint32_t xmac_val;
15112     uint32_t emac_addr;
15113     uint32_t emac_val;
15114     uint32_t umac_addr;
15115     uint32_t umac_val;
15116     uint32_t bmac_addr;
15117     uint32_t bmac_val[2];
15118 };
15119 
15120 static void
15121 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15122                           struct bxe_mac_vals *vals)
15123 {
15124     uint32_t val, base_addr, offset, mask, reset_reg;
15125     uint8_t mac_stopped = FALSE;
15126     uint8_t port = SC_PORT(sc);
15127     uint32_t wb_data[2];
15128 
15129     /* reset addresses as they also mark which values were changed */
15130     vals->bmac_addr = 0;
15131     vals->umac_addr = 0;
15132     vals->xmac_addr = 0;
15133     vals->emac_addr = 0;
15134 
15135     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15136 
15137     if (!CHIP_IS_E3(sc)) {
15138         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15139         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15140         if ((mask & reset_reg) && val) {
15141             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15142             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15143                                     : NIG_REG_INGRESS_BMAC0_MEM;
15144             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15145                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15146 
15147             /*
15148              * use rd/wr since we cannot use dmae. This is safe
15149              * since MCP won't access the bus due to the request
15150              * to unload, and no function on the path can be
15151              * loaded at this time.
15152              */
15153             wb_data[0] = REG_RD(sc, base_addr + offset);
15154             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15155             vals->bmac_addr = base_addr + offset;
15156             vals->bmac_val[0] = wb_data[0];
15157             vals->bmac_val[1] = wb_data[1];
15158             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15159             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15160             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15161         }
15162 
15163         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15164         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15165         vals->emac_val = REG_RD(sc, vals->emac_addr);
15166         REG_WR(sc, vals->emac_addr, 0);
15167         mac_stopped = TRUE;
15168     } else {
15169         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15170             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15171             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15172             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15173             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15174             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15175             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15176             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15177             REG_WR(sc, vals->xmac_addr, 0);
15178             mac_stopped = TRUE;
15179         }
15180 
15181         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15182         if (mask & reset_reg) {
15183             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15184             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15185             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15186             vals->umac_val = REG_RD(sc, vals->umac_addr);
15187             REG_WR(sc, vals->umac_addr, 0);
15188             mac_stopped = TRUE;
15189         }
15190     }
15191 
15192     if (mac_stopped) {
15193         DELAY(20000);
15194     }
15195 }
15196 
15197 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15198 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15199 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15200 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15201 
15202 static void
15203 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15204                          uint8_t          port,
15205                          uint8_t          inc)
15206 {
15207     uint16_t rcq, bd;
15208     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15209 
15210     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15211     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15212 
15213     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15214     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15215 
15216     BLOGD(sc, DBG_LOAD,
15217           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15218           port, bd, rcq);
15219 }
15220 
15221 static int
15222 bxe_prev_unload_common(struct bxe_softc *sc)
15223 {
15224     uint32_t reset_reg, tmp_reg = 0, rc;
15225     uint8_t prev_undi = FALSE;
15226     struct bxe_mac_vals mac_vals;
15227     uint32_t timer_count = 1000;
15228     uint32_t prev_brb;
15229 
15230     /*
15231      * It is possible a previous function received 'common' answer,
15232      * but hasn't loaded yet, therefore creating a scenario of
15233      * multiple functions receiving 'common' on the same path.
15234      */
15235     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15236 
15237     memset(&mac_vals, 0, sizeof(mac_vals));
15238 
15239     if (bxe_prev_is_path_marked(sc)) {
15240         return (bxe_prev_mcp_done(sc));
15241     }
15242 
15243     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15244 
15245     /* Reset should be performed after BRB is emptied */
15246     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15247         /* Close the MAC Rx to prevent BRB from filling up */
15248         bxe_prev_unload_close_mac(sc, &mac_vals);
15249 
15250         /* close LLH filters towards the BRB */
15251         elink_set_rx_filter(&sc->link_params, 0);
15252 
15253         /*
15254          * Check if the UNDI driver was previously loaded.
15255          * UNDI driver initializes CID offset for normal bell to 0x7
15256          */
15257         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15258             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15259             if (tmp_reg == 0x7) {
15260                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15261                 prev_undi = TRUE;
15262                 /* clear the UNDI indication */
15263                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15264                 /* clear possible idle check errors */
15265                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15266             }
15267         }
15268 
15269         /* wait until BRB is empty */
15270         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15271         while (timer_count) {
15272             prev_brb = tmp_reg;
15273 
15274             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15275             if (!tmp_reg) {
15276                 break;
15277             }
15278 
15279             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15280 
15281             /* reset timer as long as BRB actually gets emptied */
15282             if (prev_brb > tmp_reg) {
15283                 timer_count = 1000;
15284             } else {
15285                 timer_count--;
15286             }
15287 
15288             /* If UNDI resides in memory, manually increment it */
15289             if (prev_undi) {
15290                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15291             }
15292 
15293             DELAY(10);
15294         }
15295 
15296         if (!timer_count) {
15297             BLOGE(sc, "Failed to empty BRB\n");
15298         }
15299     }
15300 
15301     /* No packets are in the pipeline, path is ready for reset */
15302     bxe_reset_common(sc);
15303 
15304     if (mac_vals.xmac_addr) {
15305         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15306     }
15307     if (mac_vals.umac_addr) {
15308         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15309     }
15310     if (mac_vals.emac_addr) {
15311         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15312     }
15313     if (mac_vals.bmac_addr) {
15314         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15315         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15316     }
15317 
15318     rc = bxe_prev_mark_path(sc, prev_undi);
15319     if (rc) {
15320         bxe_prev_mcp_done(sc);
15321         return (rc);
15322     }
15323 
15324     return (bxe_prev_mcp_done(sc));
15325 }
15326 
15327 static int
15328 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15329 {
15330     int rc;
15331 
15332     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15333 
15334     /* Test if previous unload process was already finished for this path */
15335     if (bxe_prev_is_path_marked(sc)) {
15336         return (bxe_prev_mcp_done(sc));
15337     }
15338 
15339     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15340 
15341     /*
15342      * If function has FLR capabilities, and existing FW version matches
15343      * the one required, then FLR will be sufficient to clean any residue
15344      * left by previous driver
15345      */
15346     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15347     if (!rc) {
15348         /* fw version is good */
15349         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15350         rc = bxe_do_flr(sc);
15351     }
15352 
15353     if (!rc) {
15354         /* FLR was performed */
15355         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15356         return (0);
15357     }
15358 
15359     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15360 
15361     /* Close the MCP request, return failure*/
15362     rc = bxe_prev_mcp_done(sc);
15363     if (!rc) {
15364         rc = BXE_PREV_WAIT_NEEDED;
15365     }
15366 
15367     return (rc);
15368 }
15369 
15370 static int
15371 bxe_prev_unload(struct bxe_softc *sc)
15372 {
15373     int time_counter = 10;
15374     uint32_t fw, hw_lock_reg, hw_lock_val;
15375     uint32_t rc = 0;
15376 
15377     /*
15378      * Clear HW from errors which may have resulted from an interrupted
15379      * DMAE transaction.
15380      */
15381     bxe_prev_interrupted_dmae(sc);
15382 
15383     /* Release previously held locks */
15384     hw_lock_reg =
15385         (SC_FUNC(sc) <= 5) ?
15386             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15387             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15388 
15389     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15390     if (hw_lock_val) {
15391         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15392             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15393             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15394                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15395         }
15396         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15397         REG_WR(sc, hw_lock_reg, 0xffffffff);
15398     } else {
15399         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15400     }
15401 
15402     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15403         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15404         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15405     }
15406 
15407     do {
15408         /* Lock MCP using an unload request */
15409         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15410         if (!fw) {
15411             BLOGE(sc, "MCP response failure, aborting\n");
15412             rc = -1;
15413             break;
15414         }
15415 
15416         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15417             rc = bxe_prev_unload_common(sc);
15418             break;
15419         }
15420 
15421         /* non-common reply from MCP night require looping */
15422         rc = bxe_prev_unload_uncommon(sc);
15423         if (rc != BXE_PREV_WAIT_NEEDED) {
15424             break;
15425         }
15426 
15427         DELAY(20000);
15428     } while (--time_counter);
15429 
15430     if (!time_counter || rc) {
15431         BLOGE(sc, "Failed to unload previous driver!"
15432             " time_counter %d rc %d\n", time_counter, rc);
15433         rc = -1;
15434     }
15435 
15436     return (rc);
15437 }
15438 
15439 void
15440 bxe_dcbx_set_state(struct bxe_softc *sc,
15441                    uint8_t          dcb_on,
15442                    uint32_t         dcbx_enabled)
15443 {
15444     if (!CHIP_IS_E1x(sc)) {
15445         sc->dcb_state = dcb_on;
15446         sc->dcbx_enabled = dcbx_enabled;
15447     } else {
15448         sc->dcb_state = FALSE;
15449         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15450     }
15451     BLOGD(sc, DBG_LOAD,
15452           "DCB state [%s:%s]\n",
15453           dcb_on ? "ON" : "OFF",
15454           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15455           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15456           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15457           "on-chip with negotiation" : "invalid");
15458 }
15459 
15460 /* must be called after sriov-enable */
15461 static int
15462 bxe_set_qm_cid_count(struct bxe_softc *sc)
15463 {
15464     int cid_count = BXE_L2_MAX_CID(sc);
15465 
15466     if (IS_SRIOV(sc)) {
15467         cid_count += BXE_VF_CIDS;
15468     }
15469 
15470     if (CNIC_SUPPORT(sc)) {
15471         cid_count += CNIC_CID_MAX;
15472     }
15473 
15474     return (roundup(cid_count, QM_CID_ROUND));
15475 }
15476 
15477 static void
15478 bxe_init_multi_cos(struct bxe_softc *sc)
15479 {
15480     int pri, cos;
15481 
15482     uint32_t pri_map = 0; /* XXX change to user config */
15483 
15484     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15485         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15486         if (cos < sc->max_cos) {
15487             sc->prio_to_cos[pri] = cos;
15488         } else {
15489             BLOGW(sc, "Invalid COS %d for priority %d "
15490                       "(max COS is %d), setting to 0\n",
15491                   cos, pri, (sc->max_cos - 1));
15492             sc->prio_to_cos[pri] = 0;
15493         }
15494     }
15495 }
15496 
15497 static int
15498 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15499 {
15500     struct bxe_softc *sc;
15501     int error, result;
15502 
15503     result = 0;
15504     error = sysctl_handle_int(oidp, &result, 0, req);
15505 
15506     if (error || !req->newptr) {
15507         return (error);
15508     }
15509 
15510     if (result == 1) {
15511         uint32_t  temp;
15512         sc = (struct bxe_softc *)arg1;
15513 
15514         BLOGI(sc, "... dumping driver state ...\n");
15515         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15516         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15517     }
15518 
15519     return (error);
15520 }
15521 
15522 static int
15523 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15524 {
15525     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15526     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15527     uint32_t *offset;
15528     uint64_t value = 0;
15529     int index = (int)arg2;
15530 
15531     if (index >= BXE_NUM_ETH_STATS) {
15532         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15533         return (-1);
15534     }
15535 
15536     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15537 
15538     switch (bxe_eth_stats_arr[index].size) {
15539     case 4:
15540         value = (uint64_t)*offset;
15541         break;
15542     case 8:
15543         value = HILO_U64(*offset, *(offset + 1));
15544         break;
15545     default:
15546         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15547               index, bxe_eth_stats_arr[index].size);
15548         return (-1);
15549     }
15550 
15551     return (sysctl_handle_64(oidp, &value, 0, req));
15552 }
15553 
15554 static int
15555 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15556 {
15557     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15558     uint32_t *eth_stats;
15559     uint32_t *offset;
15560     uint64_t value = 0;
15561     uint32_t q_stat = (uint32_t)arg2;
15562     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15563     uint32_t index = (q_stat & 0xffff);
15564 
15565     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15566 
15567     if (index >= BXE_NUM_ETH_Q_STATS) {
15568         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15569         return (-1);
15570     }
15571 
15572     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15573 
15574     switch (bxe_eth_q_stats_arr[index].size) {
15575     case 4:
15576         value = (uint64_t)*offset;
15577         break;
15578     case 8:
15579         value = HILO_U64(*offset, *(offset + 1));
15580         break;
15581     default:
15582         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15583               index, bxe_eth_q_stats_arr[index].size);
15584         return (-1);
15585     }
15586 
15587     return (sysctl_handle_64(oidp, &value, 0, req));
15588 }
15589 
15590 static void
15591 bxe_add_sysctls(struct bxe_softc *sc)
15592 {
15593     struct sysctl_ctx_list *ctx;
15594     struct sysctl_oid_list *children;
15595     struct sysctl_oid *queue_top, *queue;
15596     struct sysctl_oid_list *queue_top_children, *queue_children;
15597     char queue_num_buf[32];
15598     uint32_t q_stat;
15599     int i, j;
15600 
15601     ctx = device_get_sysctl_ctx(sc->dev);
15602     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15603 
15604     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15605                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15606                       "version");
15607 
15608     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15609              BCM_5710_FW_MAJOR_VERSION,
15610              BCM_5710_FW_MINOR_VERSION,
15611              BCM_5710_FW_REVISION_VERSION,
15612              BCM_5710_FW_ENGINEERING_VERSION);
15613 
15614     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15615         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15616          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15617          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15618          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15619                                                                 "Unknown"));
15620     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15621                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15622                     "multifunction vnics per port");
15623 
15624     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15625         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15626          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15627          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15628                                               "???GT/s"),
15629         sc->devinfo.pcie_link_width);
15630 
15631     sc->debug = bxe_debug;
15632 
15633 #if __FreeBSD_version >= 900000
15634     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15635                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15636                       "bootcode version");
15637     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15638                       CTLFLAG_RD, sc->fw_ver_str, 0,
15639                       "firmware version");
15640     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15641                       CTLFLAG_RD, sc->mf_mode_str, 0,
15642                       "multifunction mode");
15643     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15644                       CTLFLAG_RD, sc->mac_addr_str, 0,
15645                       "mac address");
15646     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15647                       CTLFLAG_RD, sc->pci_link_str, 0,
15648                       "pci link status");
15649     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15650                     CTLFLAG_RW, &sc->debug,
15651                     "debug logging mode");
15652 #else
15653     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15654                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15655                       "bootcode version");
15656     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15657                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15658                       "firmware version");
15659     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15660                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15661                       "multifunction mode");
15662     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15663                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15664                       "mac address");
15665     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15666                       CTLFLAG_RD, &sc->pci_link_str, 0,
15667                       "pci link status");
15668     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15669                     CTLFLAG_RW, &sc->debug, 0,
15670                     "debug logging mode");
15671 #endif /* #if __FreeBSD_version >= 900000 */
15672 
15673     sc->trigger_grcdump = 0;
15674     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15675                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15676                    "trigger grcdump should be invoked"
15677                    "  before collecting grcdump");
15678 
15679     sc->grcdump_started = 0;
15680     sc->grcdump_done = 0;
15681     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15682                    CTLFLAG_RD, &sc->grcdump_done, 0,
15683                    "set by driver when grcdump is done");
15684 
15685     sc->rx_budget = bxe_rx_budget;
15686     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15687                     CTLFLAG_RW, &sc->rx_budget, 0,
15688                     "rx processing budget");
15689 
15690     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15691                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15692                     bxe_sysctl_state, "IU", "dump driver state");
15693 
15694     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15695         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15696                         bxe_eth_stats_arr[i].string,
15697                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15698                         bxe_sysctl_eth_stat, "LU",
15699                         bxe_eth_stats_arr[i].string);
15700     }
15701 
15702     /* add a new parent node for all queues "dev.bxe.#.queue" */
15703     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15704                                 CTLFLAG_RD, NULL, "queue");
15705     queue_top_children = SYSCTL_CHILDREN(queue_top);
15706 
15707     for (i = 0; i < sc->num_queues; i++) {
15708         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15709         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15710         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15711                                 queue_num_buf, CTLFLAG_RD, NULL,
15712                                 "single queue");
15713         queue_children = SYSCTL_CHILDREN(queue);
15714 
15715         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15716             q_stat = ((i << 16) | j);
15717             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15718                             bxe_eth_q_stats_arr[j].string,
15719                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15720                             bxe_sysctl_eth_q_stat, "LU",
15721                             bxe_eth_q_stats_arr[j].string);
15722         }
15723     }
15724 }
15725 
15726 static int
15727 bxe_alloc_buf_rings(struct bxe_softc *sc)
15728 {
15729 #if __FreeBSD_version >= 800000
15730 
15731     int i;
15732     struct bxe_fastpath *fp;
15733 
15734     for (i = 0; i < sc->num_queues; i++) {
15735 
15736         fp = &sc->fp[i];
15737 
15738         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15739                                    M_NOWAIT, &fp->tx_mtx);
15740         if (fp->tx_br == NULL)
15741             return (-1);
15742     }
15743 #endif
15744     return (0);
15745 }
15746 
15747 static void
15748 bxe_free_buf_rings(struct bxe_softc *sc)
15749 {
15750 #if __FreeBSD_version >= 800000
15751 
15752     int i;
15753     struct bxe_fastpath *fp;
15754 
15755     for (i = 0; i < sc->num_queues; i++) {
15756 
15757         fp = &sc->fp[i];
15758 
15759         if (fp->tx_br) {
15760             buf_ring_free(fp->tx_br, M_DEVBUF);
15761             fp->tx_br = NULL;
15762         }
15763     }
15764 
15765 #endif
15766 }
15767 
15768 static void
15769 bxe_init_fp_mutexs(struct bxe_softc *sc)
15770 {
15771     int i;
15772     struct bxe_fastpath *fp;
15773 
15774     for (i = 0; i < sc->num_queues; i++) {
15775 
15776         fp = &sc->fp[i];
15777 
15778         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15779             "bxe%d_fp%d_tx_lock", sc->unit, i);
15780         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15781 
15782         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15783             "bxe%d_fp%d_rx_lock", sc->unit, i);
15784         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15785     }
15786 }
15787 
15788 static void
15789 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15790 {
15791     int i;
15792     struct bxe_fastpath *fp;
15793 
15794     for (i = 0; i < sc->num_queues; i++) {
15795 
15796         fp = &sc->fp[i];
15797 
15798         if (mtx_initialized(&fp->tx_mtx)) {
15799             mtx_destroy(&fp->tx_mtx);
15800         }
15801 
15802         if (mtx_initialized(&fp->rx_mtx)) {
15803             mtx_destroy(&fp->rx_mtx);
15804         }
15805     }
15806 }
15807 
15808 
15809 /*
15810  * Device attach function.
15811  *
15812  * Allocates device resources, performs secondary chip identification, and
15813  * initializes driver instance variables. This function is called from driver
15814  * load after a successful probe.
15815  *
15816  * Returns:
15817  *   0 = Success, >0 = Failure
15818  */
15819 static int
15820 bxe_attach(device_t dev)
15821 {
15822     struct bxe_softc *sc;
15823 
15824     sc = device_get_softc(dev);
15825 
15826     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15827 
15828     sc->state = BXE_STATE_CLOSED;
15829 
15830     sc->dev  = dev;
15831     sc->unit = device_get_unit(dev);
15832 
15833     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15834 
15835     sc->pcie_bus    = pci_get_bus(dev);
15836     sc->pcie_device = pci_get_slot(dev);
15837     sc->pcie_func   = pci_get_function(dev);
15838 
15839     /* enable bus master capability */
15840     pci_enable_busmaster(dev);
15841 
15842     /* get the BARs */
15843     if (bxe_allocate_bars(sc) != 0) {
15844         return (ENXIO);
15845     }
15846 
15847     /* initialize the mutexes */
15848     bxe_init_mutexes(sc);
15849 
15850     /* prepare the periodic callout */
15851     callout_init(&sc->periodic_callout, 0);
15852 
15853     /* prepare the chip taskqueue */
15854     sc->chip_tq_flags = CHIP_TQ_NONE;
15855     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15856              "bxe%d_chip_tq", sc->unit);
15857     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15858     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15859                                    taskqueue_thread_enqueue,
15860                                    &sc->chip_tq);
15861     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15862                             "%s", sc->chip_tq_name);
15863 
15864     /* get device info and set params */
15865     if (bxe_get_device_info(sc) != 0) {
15866         BLOGE(sc, "getting device info\n");
15867         bxe_deallocate_bars(sc);
15868         pci_disable_busmaster(dev);
15869         return (ENXIO);
15870     }
15871 
15872     /* get final misc params */
15873     bxe_get_params(sc);
15874 
15875     /* set the default MTU (changed via ifconfig) */
15876     sc->mtu = ETHERMTU;
15877 
15878     bxe_set_modes_bitmap(sc);
15879 
15880     /* XXX
15881      * If in AFEX mode and the function is configured for FCoE
15882      * then bail... no L2 allowed.
15883      */
15884 
15885     /* get phy settings from shmem and 'and' against admin settings */
15886     bxe_get_phy_info(sc);
15887 
15888     /* initialize the FreeBSD ifnet interface */
15889     if (bxe_init_ifnet(sc) != 0) {
15890         bxe_release_mutexes(sc);
15891         bxe_deallocate_bars(sc);
15892         pci_disable_busmaster(dev);
15893         return (ENXIO);
15894     }
15895 
15896     if (bxe_add_cdev(sc) != 0) {
15897         if (sc->ifp != NULL) {
15898             ether_ifdetach(sc->ifp);
15899         }
15900         ifmedia_removeall(&sc->ifmedia);
15901         bxe_release_mutexes(sc);
15902         bxe_deallocate_bars(sc);
15903         pci_disable_busmaster(dev);
15904         return (ENXIO);
15905     }
15906 
15907     /* allocate device interrupts */
15908     if (bxe_interrupt_alloc(sc) != 0) {
15909         bxe_del_cdev(sc);
15910         if (sc->ifp != NULL) {
15911             ether_ifdetach(sc->ifp);
15912         }
15913         ifmedia_removeall(&sc->ifmedia);
15914         bxe_release_mutexes(sc);
15915         bxe_deallocate_bars(sc);
15916         pci_disable_busmaster(dev);
15917         return (ENXIO);
15918     }
15919 
15920     bxe_init_fp_mutexs(sc);
15921 
15922     if (bxe_alloc_buf_rings(sc) != 0) {
15923 	bxe_free_buf_rings(sc);
15924         bxe_interrupt_free(sc);
15925         bxe_del_cdev(sc);
15926         if (sc->ifp != NULL) {
15927             ether_ifdetach(sc->ifp);
15928         }
15929         ifmedia_removeall(&sc->ifmedia);
15930         bxe_release_mutexes(sc);
15931         bxe_deallocate_bars(sc);
15932         pci_disable_busmaster(dev);
15933         return (ENXIO);
15934     }
15935 
15936     /* allocate ilt */
15937     if (bxe_alloc_ilt_mem(sc) != 0) {
15938 	bxe_free_buf_rings(sc);
15939         bxe_interrupt_free(sc);
15940         bxe_del_cdev(sc);
15941         if (sc->ifp != NULL) {
15942             ether_ifdetach(sc->ifp);
15943         }
15944         ifmedia_removeall(&sc->ifmedia);
15945         bxe_release_mutexes(sc);
15946         bxe_deallocate_bars(sc);
15947         pci_disable_busmaster(dev);
15948         return (ENXIO);
15949     }
15950 
15951     /* allocate the host hardware/software hsi structures */
15952     if (bxe_alloc_hsi_mem(sc) != 0) {
15953         bxe_free_ilt_mem(sc);
15954 	bxe_free_buf_rings(sc);
15955         bxe_interrupt_free(sc);
15956         bxe_del_cdev(sc);
15957         if (sc->ifp != NULL) {
15958             ether_ifdetach(sc->ifp);
15959         }
15960         ifmedia_removeall(&sc->ifmedia);
15961         bxe_release_mutexes(sc);
15962         bxe_deallocate_bars(sc);
15963         pci_disable_busmaster(dev);
15964         return (ENXIO);
15965     }
15966 
15967     /* need to reset chip if UNDI was active */
15968     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
15969         /* init fw_seq */
15970         sc->fw_seq =
15971             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
15972              DRV_MSG_SEQ_NUMBER_MASK);
15973         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
15974         bxe_prev_unload(sc);
15975     }
15976 
15977 #if 1
15978     /* XXX */
15979     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15980 #else
15981     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
15982         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
15983         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
15984         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
15985         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
15986         bxe_dcbx_init_params(sc);
15987     } else {
15988         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15989     }
15990 #endif
15991 
15992     /* calculate qm_cid_count */
15993     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
15994     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
15995 
15996     sc->max_cos = 1;
15997     bxe_init_multi_cos(sc);
15998 
15999     bxe_add_sysctls(sc);
16000 
16001     return (0);
16002 }
16003 
16004 /*
16005  * Device detach function.
16006  *
16007  * Stops the controller, resets the controller, and releases resources.
16008  *
16009  * Returns:
16010  *   0 = Success, >0 = Failure
16011  */
16012 static int
16013 bxe_detach(device_t dev)
16014 {
16015     struct bxe_softc *sc;
16016     if_t ifp;
16017 
16018     sc = device_get_softc(dev);
16019 
16020     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16021 
16022     ifp = sc->ifp;
16023     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16024         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16025         return(EBUSY);
16026     }
16027 
16028     bxe_del_cdev(sc);
16029 
16030     /* stop the periodic callout */
16031     bxe_periodic_stop(sc);
16032 
16033     /* stop the chip taskqueue */
16034     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16035     if (sc->chip_tq) {
16036         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16037         taskqueue_free(sc->chip_tq);
16038         sc->chip_tq = NULL;
16039     }
16040 
16041     /* stop and reset the controller if it was open */
16042     if (sc->state != BXE_STATE_CLOSED) {
16043         BXE_CORE_LOCK(sc);
16044         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16045         sc->state = BXE_STATE_DISABLED;
16046         BXE_CORE_UNLOCK(sc);
16047     }
16048 
16049     /* release the network interface */
16050     if (ifp != NULL) {
16051         ether_ifdetach(ifp);
16052     }
16053     ifmedia_removeall(&sc->ifmedia);
16054 
16055     /* XXX do the following based on driver state... */
16056 
16057     /* free the host hardware/software hsi structures */
16058     bxe_free_hsi_mem(sc);
16059 
16060     /* free ilt */
16061     bxe_free_ilt_mem(sc);
16062 
16063     bxe_free_buf_rings(sc);
16064 
16065     /* release the interrupts */
16066     bxe_interrupt_free(sc);
16067 
16068     /* Release the mutexes*/
16069     bxe_destroy_fp_mutexs(sc);
16070     bxe_release_mutexes(sc);
16071 
16072 
16073     /* Release the PCIe BAR mapped memory */
16074     bxe_deallocate_bars(sc);
16075 
16076     /* Release the FreeBSD interface. */
16077     if (sc->ifp != NULL) {
16078         if_free(sc->ifp);
16079     }
16080 
16081     pci_disable_busmaster(dev);
16082 
16083     return (0);
16084 }
16085 
16086 /*
16087  * Device shutdown function.
16088  *
16089  * Stops and resets the controller.
16090  *
16091  * Returns:
16092  *   Nothing
16093  */
16094 static int
16095 bxe_shutdown(device_t dev)
16096 {
16097     struct bxe_softc *sc;
16098 
16099     sc = device_get_softc(dev);
16100 
16101     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16102 
16103     /* stop the periodic callout */
16104     bxe_periodic_stop(sc);
16105 
16106     BXE_CORE_LOCK(sc);
16107     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16108     BXE_CORE_UNLOCK(sc);
16109 
16110     return (0);
16111 }
16112 
16113 void
16114 bxe_igu_ack_sb(struct bxe_softc *sc,
16115                uint8_t          igu_sb_id,
16116                uint8_t          segment,
16117                uint16_t         index,
16118                uint8_t          op,
16119                uint8_t          update)
16120 {
16121     uint32_t igu_addr = sc->igu_base_addr;
16122     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16123     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16124 }
16125 
16126 static void
16127 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16128                      uint8_t          func,
16129                      uint8_t          idu_sb_id,
16130                      uint8_t          is_pf)
16131 {
16132     uint32_t data, ctl, cnt = 100;
16133     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16134     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16135     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16136     uint32_t sb_bit =  1 << (idu_sb_id%32);
16137     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16138     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16139 
16140     /* Not supported in BC mode */
16141     if (CHIP_INT_MODE_IS_BC(sc)) {
16142         return;
16143     }
16144 
16145     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16146              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16147             IGU_REGULAR_CLEANUP_SET |
16148             IGU_REGULAR_BCLEANUP);
16149 
16150     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16151            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16152            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16153 
16154     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16155             data, igu_addr_data);
16156     REG_WR(sc, igu_addr_data, data);
16157 
16158     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16159                       BUS_SPACE_BARRIER_WRITE);
16160     mb();
16161 
16162     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16163             ctl, igu_addr_ctl);
16164     REG_WR(sc, igu_addr_ctl, ctl);
16165 
16166     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16167                       BUS_SPACE_BARRIER_WRITE);
16168     mb();
16169 
16170     /* wait for clean up to finish */
16171     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16172         DELAY(20000);
16173     }
16174 
16175     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16176         BLOGD(sc, DBG_LOAD,
16177               "Unable to finish IGU cleanup: "
16178               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16179               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16180     }
16181 }
16182 
16183 static void
16184 bxe_igu_clear_sb(struct bxe_softc *sc,
16185                  uint8_t          idu_sb_id)
16186 {
16187     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16188 }
16189 
16190 
16191 
16192 
16193 
16194 
16195 
16196 /*******************/
16197 /* ECORE CALLBACKS */
16198 /*******************/
16199 
16200 static void
16201 bxe_reset_common(struct bxe_softc *sc)
16202 {
16203     uint32_t val = 0x1400;
16204 
16205     /* reset_common */
16206     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16207 
16208     if (CHIP_IS_E3(sc)) {
16209         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16210         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16211     }
16212 
16213     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16214 }
16215 
16216 static void
16217 bxe_common_init_phy(struct bxe_softc *sc)
16218 {
16219     uint32_t shmem_base[2];
16220     uint32_t shmem2_base[2];
16221 
16222     /* Avoid common init in case MFW supports LFA */
16223     if (SHMEM2_RD(sc, size) >
16224         (uint32_t)offsetof(struct shmem2_region,
16225                            lfa_host_addr[SC_PORT(sc)])) {
16226         return;
16227     }
16228 
16229     shmem_base[0]  = sc->devinfo.shmem_base;
16230     shmem2_base[0] = sc->devinfo.shmem2_base;
16231 
16232     if (!CHIP_IS_E1x(sc)) {
16233         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16234         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16235     }
16236 
16237     bxe_acquire_phy_lock(sc);
16238     elink_common_init_phy(sc, shmem_base, shmem2_base,
16239                           sc->devinfo.chip_id, 0);
16240     bxe_release_phy_lock(sc);
16241 }
16242 
16243 static void
16244 bxe_pf_disable(struct bxe_softc *sc)
16245 {
16246     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16247 
16248     val &= ~IGU_PF_CONF_FUNC_EN;
16249 
16250     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16251     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16252     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16253 }
16254 
16255 static void
16256 bxe_init_pxp(struct bxe_softc *sc)
16257 {
16258     uint16_t devctl;
16259     int r_order, w_order;
16260 
16261     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16262 
16263     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16264 
16265     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16266 
16267     if (sc->mrrs == -1) {
16268         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16269     } else {
16270         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16271         r_order = sc->mrrs;
16272     }
16273 
16274     ecore_init_pxp_arb(sc, r_order, w_order);
16275 }
16276 
16277 static uint32_t
16278 bxe_get_pretend_reg(struct bxe_softc *sc)
16279 {
16280     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16281     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16282     return (base + (SC_ABS_FUNC(sc)) * stride);
16283 }
16284 
16285 /*
16286  * Called only on E1H or E2.
16287  * When pretending to be PF, the pretend value is the function number 0..7.
16288  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16289  * combination.
16290  */
16291 static int
16292 bxe_pretend_func(struct bxe_softc *sc,
16293                  uint16_t         pretend_func_val)
16294 {
16295     uint32_t pretend_reg;
16296 
16297     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16298         return (-1);
16299     }
16300 
16301     /* get my own pretend register */
16302     pretend_reg = bxe_get_pretend_reg(sc);
16303     REG_WR(sc, pretend_reg, pretend_func_val);
16304     REG_RD(sc, pretend_reg);
16305     return (0);
16306 }
16307 
16308 static void
16309 bxe_iov_init_dmae(struct bxe_softc *sc)
16310 {
16311     return;
16312 }
16313 
16314 static void
16315 bxe_iov_init_dq(struct bxe_softc *sc)
16316 {
16317     return;
16318 }
16319 
16320 /* send a NIG loopback debug packet */
16321 static void
16322 bxe_lb_pckt(struct bxe_softc *sc)
16323 {
16324     uint32_t wb_write[3];
16325 
16326     /* Ethernet source and destination addresses */
16327     wb_write[0] = 0x55555555;
16328     wb_write[1] = 0x55555555;
16329     wb_write[2] = 0x20;     /* SOP */
16330     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16331 
16332     /* NON-IP protocol */
16333     wb_write[0] = 0x09000000;
16334     wb_write[1] = 0x55555555;
16335     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16336     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16337 }
16338 
16339 /*
16340  * Some of the internal memories are not directly readable from the driver.
16341  * To test them we send debug packets.
16342  */
16343 static int
16344 bxe_int_mem_test(struct bxe_softc *sc)
16345 {
16346     int factor;
16347     int count, i;
16348     uint32_t val = 0;
16349 
16350     if (CHIP_REV_IS_FPGA(sc)) {
16351         factor = 120;
16352     } else if (CHIP_REV_IS_EMUL(sc)) {
16353         factor = 200;
16354     } else {
16355         factor = 1;
16356     }
16357 
16358     /* disable inputs of parser neighbor blocks */
16359     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16360     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16361     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16362     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16363 
16364     /*  write 0 to parser credits for CFC search request */
16365     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16366 
16367     /* send Ethernet packet */
16368     bxe_lb_pckt(sc);
16369 
16370     /* TODO do i reset NIG statistic? */
16371     /* Wait until NIG register shows 1 packet of size 0x10 */
16372     count = 1000 * factor;
16373     while (count) {
16374         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16375         val = *BXE_SP(sc, wb_data[0]);
16376         if (val == 0x10) {
16377             break;
16378         }
16379 
16380         DELAY(10000);
16381         count--;
16382     }
16383 
16384     if (val != 0x10) {
16385         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16386         return (-1);
16387     }
16388 
16389     /* wait until PRS register shows 1 packet */
16390     count = (1000 * factor);
16391     while (count) {
16392         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16393         if (val == 1) {
16394             break;
16395         }
16396 
16397         DELAY(10000);
16398         count--;
16399     }
16400 
16401     if (val != 0x1) {
16402         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16403         return (-2);
16404     }
16405 
16406     /* Reset and init BRB, PRS */
16407     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16408     DELAY(50000);
16409     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16410     DELAY(50000);
16411     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16412     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16413 
16414     /* Disable inputs of parser neighbor blocks */
16415     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16416     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16417     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16418     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16419 
16420     /* Write 0 to parser credits for CFC search request */
16421     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16422 
16423     /* send 10 Ethernet packets */
16424     for (i = 0; i < 10; i++) {
16425         bxe_lb_pckt(sc);
16426     }
16427 
16428     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16429     count = (1000 * factor);
16430     while (count) {
16431         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16432         val = *BXE_SP(sc, wb_data[0]);
16433         if (val == 0xb0) {
16434             break;
16435         }
16436 
16437         DELAY(10000);
16438         count--;
16439     }
16440 
16441     if (val != 0xb0) {
16442         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16443         return (-3);
16444     }
16445 
16446     /* Wait until PRS register shows 2 packets */
16447     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16448     if (val != 2) {
16449         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16450     }
16451 
16452     /* Write 1 to parser credits for CFC search request */
16453     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16454 
16455     /* Wait until PRS register shows 3 packets */
16456     DELAY(10000 * factor);
16457 
16458     /* Wait until NIG register shows 1 packet of size 0x10 */
16459     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16460     if (val != 3) {
16461         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16462     }
16463 
16464     /* clear NIG EOP FIFO */
16465     for (i = 0; i < 11; i++) {
16466         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16467     }
16468 
16469     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16470     if (val != 1) {
16471         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16472         return (-4);
16473     }
16474 
16475     /* Reset and init BRB, PRS, NIG */
16476     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16477     DELAY(50000);
16478     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16479     DELAY(50000);
16480     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16481     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16482     if (!CNIC_SUPPORT(sc)) {
16483         /* set NIC mode */
16484         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16485     }
16486 
16487     /* Enable inputs of parser neighbor blocks */
16488     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16489     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16490     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16491     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16492 
16493     return (0);
16494 }
16495 
16496 static void
16497 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16498 {
16499     int is_required;
16500     uint32_t val;
16501     int port;
16502 
16503     is_required = 0;
16504     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16505            SHARED_HW_CFG_FAN_FAILURE_MASK);
16506 
16507     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16508         is_required = 1;
16509     }
16510     /*
16511      * The fan failure mechanism is usually related to the PHY type since
16512      * the power consumption of the board is affected by the PHY. Currently,
16513      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16514      */
16515     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16516         for (port = PORT_0; port < PORT_MAX; port++) {
16517             is_required |= elink_fan_failure_det_req(sc,
16518                                                      sc->devinfo.shmem_base,
16519                                                      sc->devinfo.shmem2_base,
16520                                                      port);
16521         }
16522     }
16523 
16524     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16525 
16526     if (is_required == 0) {
16527         return;
16528     }
16529 
16530     /* Fan failure is indicated by SPIO 5 */
16531     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16532 
16533     /* set to active low mode */
16534     val = REG_RD(sc, MISC_REG_SPIO_INT);
16535     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16536     REG_WR(sc, MISC_REG_SPIO_INT, val);
16537 
16538     /* enable interrupt to signal the IGU */
16539     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16540     val |= MISC_SPIO_SPIO5;
16541     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16542 }
16543 
16544 static void
16545 bxe_enable_blocks_attention(struct bxe_softc *sc)
16546 {
16547     uint32_t val;
16548 
16549     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16550     if (!CHIP_IS_E1x(sc)) {
16551         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16552     } else {
16553         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16554     }
16555     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16556     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16557     /*
16558      * mask read length error interrupts in brb for parser
16559      * (parsing unit and 'checksum and crc' unit)
16560      * these errors are legal (PU reads fixed length and CAC can cause
16561      * read length error on truncated packets)
16562      */
16563     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16564     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16565     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16566     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16567     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16568     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16569 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16570 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16571     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16572     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16573     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16574 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16575 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16576     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16577     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16578     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16579     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16580 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16581 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16582 
16583     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16584            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16585            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16586     if (!CHIP_IS_E1x(sc)) {
16587         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16588                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16589     }
16590     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16591 
16592     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16593     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16594     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16595 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16596 
16597     if (!CHIP_IS_E1x(sc)) {
16598         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16599         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16600     }
16601 
16602     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16603     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16604 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16605     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16606 }
16607 
16608 /**
16609  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16610  *
16611  * @sc:     driver handle
16612  */
16613 static int
16614 bxe_init_hw_common(struct bxe_softc *sc)
16615 {
16616     uint8_t abs_func_id;
16617     uint32_t val;
16618 
16619     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16620           SC_ABS_FUNC(sc));
16621 
16622     /*
16623      * take the RESET lock to protect undi_unload flow from accessing
16624      * registers while we are resetting the chip
16625      */
16626     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16627 
16628     bxe_reset_common(sc);
16629 
16630     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16631 
16632     val = 0xfffc;
16633     if (CHIP_IS_E3(sc)) {
16634         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16635         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16636     }
16637 
16638     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16639 
16640     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16641 
16642     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16643     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16644 
16645     if (!CHIP_IS_E1x(sc)) {
16646         /*
16647          * 4-port mode or 2-port mode we need to turn off master-enable for
16648          * everyone. After that we turn it back on for self. So, we disregard
16649          * multi-function, and always disable all functions on the given path,
16650          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16651          */
16652         for (abs_func_id = SC_PATH(sc);
16653              abs_func_id < (E2_FUNC_MAX * 2);
16654              abs_func_id += 2) {
16655             if (abs_func_id == SC_ABS_FUNC(sc)) {
16656                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16657                 continue;
16658             }
16659 
16660             bxe_pretend_func(sc, abs_func_id);
16661 
16662             /* clear pf enable */
16663             bxe_pf_disable(sc);
16664 
16665             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16666         }
16667     }
16668 
16669     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16670 
16671     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16672 
16673     if (CHIP_IS_E1(sc)) {
16674         /*
16675          * enable HW interrupt from PXP on USDM overflow
16676          * bit 16 on INT_MASK_0
16677          */
16678         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16679     }
16680 
16681     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16682     bxe_init_pxp(sc);
16683 
16684 #ifdef __BIG_ENDIAN
16685     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16686     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16687     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16688     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16689     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16690     /* make sure this value is 0 */
16691     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16692 
16693     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16694     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16695     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16696     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16697     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16698 #endif
16699 
16700     ecore_ilt_init_page_size(sc, INITOP_SET);
16701 
16702     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16703         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16704     }
16705 
16706     /* let the HW do it's magic... */
16707     DELAY(100000);
16708 
16709     /* finish PXP init */
16710     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16711     if (val != 1) {
16712         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16713             val);
16714         return (-1);
16715     }
16716     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16717     if (val != 1) {
16718         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16719         return (-1);
16720     }
16721 
16722     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16723 
16724     /*
16725      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16726      * entries with value "0" and valid bit on. This needs to be done by the
16727      * first PF that is loaded in a path (i.e. common phase)
16728      */
16729     if (!CHIP_IS_E1x(sc)) {
16730 /*
16731  * In E2 there is a bug in the timers block that can cause function 6 / 7
16732  * (i.e. vnic3) to start even if it is marked as "scan-off".
16733  * This occurs when a different function (func2,3) is being marked
16734  * as "scan-off". Real-life scenario for example: if a driver is being
16735  * load-unloaded while func6,7 are down. This will cause the timer to access
16736  * the ilt, translate to a logical address and send a request to read/write.
16737  * Since the ilt for the function that is down is not valid, this will cause
16738  * a translation error which is unrecoverable.
16739  * The Workaround is intended to make sure that when this happens nothing
16740  * fatal will occur. The workaround:
16741  *  1.  First PF driver which loads on a path will:
16742  *      a.  After taking the chip out of reset, by using pretend,
16743  *          it will write "0" to the following registers of
16744  *          the other vnics.
16745  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16746  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16747  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16748  *          And for itself it will write '1' to
16749  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16750  *          dmae-operations (writing to pram for example.)
16751  *          note: can be done for only function 6,7 but cleaner this
16752  *            way.
16753  *      b.  Write zero+valid to the entire ILT.
16754  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16755  *          VNIC3 (of that port). The range allocated will be the
16756  *          entire ILT. This is needed to prevent  ILT range error.
16757  *  2.  Any PF driver load flow:
16758  *      a.  ILT update with the physical addresses of the allocated
16759  *          logical pages.
16760  *      b.  Wait 20msec. - note that this timeout is needed to make
16761  *          sure there are no requests in one of the PXP internal
16762  *          queues with "old" ILT addresses.
16763  *      c.  PF enable in the PGLC.
16764  *      d.  Clear the was_error of the PF in the PGLC. (could have
16765  *          occurred while driver was down)
16766  *      e.  PF enable in the CFC (WEAK + STRONG)
16767  *      f.  Timers scan enable
16768  *  3.  PF driver unload flow:
16769  *      a.  Clear the Timers scan_en.
16770  *      b.  Polling for scan_on=0 for that PF.
16771  *      c.  Clear the PF enable bit in the PXP.
16772  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16773  *      e.  Write zero+valid to all ILT entries (The valid bit must
16774  *          stay set)
16775  *      f.  If this is VNIC 3 of a port then also init
16776  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16777  *          to the last enrty in the ILT.
16778  *
16779  *      Notes:
16780  *      Currently the PF error in the PGLC is non recoverable.
16781  *      In the future the there will be a recovery routine for this error.
16782  *      Currently attention is masked.
16783  *      Having an MCP lock on the load/unload process does not guarantee that
16784  *      there is no Timer disable during Func6/7 enable. This is because the
16785  *      Timers scan is currently being cleared by the MCP on FLR.
16786  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16787  *      there is error before clearing it. But the flow above is simpler and
16788  *      more general.
16789  *      All ILT entries are written by zero+valid and not just PF6/7
16790  *      ILT entries since in the future the ILT entries allocation for
16791  *      PF-s might be dynamic.
16792  */
16793         struct ilt_client_info ilt_cli;
16794         struct ecore_ilt ilt;
16795 
16796         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16797         memset(&ilt, 0, sizeof(struct ecore_ilt));
16798 
16799         /* initialize dummy TM client */
16800         ilt_cli.start      = 0;
16801         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16802         ilt_cli.client_num = ILT_CLIENT_TM;
16803 
16804         /*
16805          * Step 1: set zeroes to all ilt page entries with valid bit on
16806          * Step 2: set the timers first/last ilt entry to point
16807          * to the entire range to prevent ILT range error for 3rd/4th
16808          * vnic (this code assumes existence of the vnic)
16809          *
16810          * both steps performed by call to ecore_ilt_client_init_op()
16811          * with dummy TM client
16812          *
16813          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16814          * and his brother are split registers
16815          */
16816 
16817         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16818         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16819         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16820 
16821         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16822         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16823         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16824     }
16825 
16826     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16827     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16828 
16829     if (!CHIP_IS_E1x(sc)) {
16830         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16831                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16832 
16833         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16834         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16835 
16836         /* let the HW do it's magic... */
16837         do {
16838             DELAY(200000);
16839             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16840         } while (factor-- && (val != 1));
16841 
16842         if (val != 1) {
16843             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16844             return (-1);
16845         }
16846     }
16847 
16848     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16849 
16850     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16851 
16852     bxe_iov_init_dmae(sc);
16853 
16854     /* clean the DMAE memory */
16855     sc->dmae_ready = 1;
16856     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16857 
16858     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16859 
16860     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16861 
16862     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16863 
16864     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16865 
16866     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16867     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
16868     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
16869     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
16870 
16871     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
16872 
16873     /* QM queues pointers table */
16874     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
16875 
16876     /* soft reset pulse */
16877     REG_WR(sc, QM_REG_SOFT_RESET, 1);
16878     REG_WR(sc, QM_REG_SOFT_RESET, 0);
16879 
16880     if (CNIC_SUPPORT(sc))
16881         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
16882 
16883     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
16884     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
16885     if (!CHIP_REV_IS_SLOW(sc)) {
16886         /* enable hw interrupt from doorbell Q */
16887         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16888     }
16889 
16890     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16891 
16892     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16893     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
16894 
16895     if (!CHIP_IS_E1(sc)) {
16896         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
16897     }
16898 
16899     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
16900         if (IS_MF_AFEX(sc)) {
16901             /*
16902              * configure that AFEX and VLAN headers must be
16903              * received in AFEX mode
16904              */
16905             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
16906             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
16907             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
16908             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
16909             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
16910         } else {
16911             /*
16912              * Bit-map indicating which L2 hdrs may appear
16913              * after the basic Ethernet header
16914              */
16915             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
16916                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16917         }
16918     }
16919 
16920     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
16921     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
16922     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
16923     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
16924 
16925     if (!CHIP_IS_E1x(sc)) {
16926         /* reset VFC memories */
16927         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16928                VFC_MEMORIES_RST_REG_CAM_RST |
16929                VFC_MEMORIES_RST_REG_RAM_RST);
16930         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16931                VFC_MEMORIES_RST_REG_CAM_RST |
16932                VFC_MEMORIES_RST_REG_RAM_RST);
16933 
16934         DELAY(20000);
16935     }
16936 
16937     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
16938     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
16939     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
16940     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
16941 
16942     /* sync semi rtc */
16943     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
16944            0x80000000);
16945     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
16946            0x80000000);
16947 
16948     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
16949     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
16950     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
16951 
16952     if (!CHIP_IS_E1x(sc)) {
16953         if (IS_MF_AFEX(sc)) {
16954             /*
16955              * configure that AFEX and VLAN headers must be
16956              * sent in AFEX mode
16957              */
16958             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
16959             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
16960             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
16961             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
16962             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
16963         } else {
16964             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
16965                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16966         }
16967     }
16968 
16969     REG_WR(sc, SRC_REG_SOFT_RST, 1);
16970 
16971     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
16972 
16973     if (CNIC_SUPPORT(sc)) {
16974         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
16975         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
16976         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
16977         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
16978         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
16979         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
16980         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
16981         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
16982         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
16983         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
16984     }
16985     REG_WR(sc, SRC_REG_SOFT_RST, 0);
16986 
16987     if (sizeof(union cdu_context) != 1024) {
16988         /* we currently assume that a context is 1024 bytes */
16989         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
16990               (long)sizeof(union cdu_context));
16991     }
16992 
16993     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
16994     val = (4 << 24) + (0 << 12) + 1024;
16995     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
16996 
16997     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
16998 
16999     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17000     /* enable context validation interrupt from CFC */
17001     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17002 
17003     /* set the thresholds to prevent CFC/CDU race */
17004     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17005     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17006 
17007     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17008         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17009     }
17010 
17011     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17012     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17013 
17014     /* Reset PCIE errors for debug */
17015     REG_WR(sc, 0x2814, 0xffffffff);
17016     REG_WR(sc, 0x3820, 0xffffffff);
17017 
17018     if (!CHIP_IS_E1x(sc)) {
17019         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17020                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17021                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17022         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17023                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17024                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17025                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17026         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17027                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17028                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17029                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17030     }
17031 
17032     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17033 
17034     if (!CHIP_IS_E1(sc)) {
17035         /* in E3 this done in per-port section */
17036         if (!CHIP_IS_E3(sc))
17037             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17038     }
17039 
17040     if (CHIP_IS_E1H(sc)) {
17041         /* not applicable for E2 (and above ...) */
17042         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17043     }
17044 
17045     if (CHIP_REV_IS_SLOW(sc)) {
17046         DELAY(200000);
17047     }
17048 
17049     /* finish CFC init */
17050     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17051     if (val != 1) {
17052         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17053         return (-1);
17054     }
17055     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17056     if (val != 1) {
17057         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17058         return (-1);
17059     }
17060     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17061     if (val != 1) {
17062         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17063         return (-1);
17064     }
17065     REG_WR(sc, CFC_REG_DEBUG0, 0);
17066 
17067     if (CHIP_IS_E1(sc)) {
17068         /* read NIG statistic to see if this is our first up since powerup */
17069         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17070         val = *BXE_SP(sc, wb_data[0]);
17071 
17072         /* do internal memory self test */
17073         if ((val == 0) && bxe_int_mem_test(sc)) {
17074             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17075             return (-1);
17076         }
17077     }
17078 
17079     bxe_setup_fan_failure_detection(sc);
17080 
17081     /* clear PXP2 attentions */
17082     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17083 
17084     bxe_enable_blocks_attention(sc);
17085 
17086     if (!CHIP_REV_IS_SLOW(sc)) {
17087         ecore_enable_blocks_parity(sc);
17088     }
17089 
17090     if (!BXE_NOMCP(sc)) {
17091         if (CHIP_IS_E1x(sc)) {
17092             bxe_common_init_phy(sc);
17093         }
17094     }
17095 
17096     return (0);
17097 }
17098 
17099 /**
17100  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17101  *
17102  * @sc:     driver handle
17103  */
17104 static int
17105 bxe_init_hw_common_chip(struct bxe_softc *sc)
17106 {
17107     int rc = bxe_init_hw_common(sc);
17108 
17109     if (rc) {
17110         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17111         return (rc);
17112     }
17113 
17114     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17115     if (!BXE_NOMCP(sc)) {
17116         bxe_common_init_phy(sc);
17117     }
17118 
17119     return (0);
17120 }
17121 
17122 static int
17123 bxe_init_hw_port(struct bxe_softc *sc)
17124 {
17125     int port = SC_PORT(sc);
17126     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17127     uint32_t low, high;
17128     uint32_t val;
17129 
17130     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17131 
17132     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17133 
17134     ecore_init_block(sc, BLOCK_MISC, init_phase);
17135     ecore_init_block(sc, BLOCK_PXP, init_phase);
17136     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17137 
17138     /*
17139      * Timers bug workaround: disables the pf_master bit in pglue at
17140      * common phase, we need to enable it here before any dmae access are
17141      * attempted. Therefore we manually added the enable-master to the
17142      * port phase (it also happens in the function phase)
17143      */
17144     if (!CHIP_IS_E1x(sc)) {
17145         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17146     }
17147 
17148     ecore_init_block(sc, BLOCK_ATC, init_phase);
17149     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17150     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17151     ecore_init_block(sc, BLOCK_QM, init_phase);
17152 
17153     ecore_init_block(sc, BLOCK_TCM, init_phase);
17154     ecore_init_block(sc, BLOCK_UCM, init_phase);
17155     ecore_init_block(sc, BLOCK_CCM, init_phase);
17156     ecore_init_block(sc, BLOCK_XCM, init_phase);
17157 
17158     /* QM cid (connection) count */
17159     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17160 
17161     if (CNIC_SUPPORT(sc)) {
17162         ecore_init_block(sc, BLOCK_TM, init_phase);
17163         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17164         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17165     }
17166 
17167     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17168 
17169     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17170 
17171     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17172         if (IS_MF(sc)) {
17173             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17174         } else if (sc->mtu > 4096) {
17175             if (BXE_ONE_PORT(sc)) {
17176                 low = 160;
17177             } else {
17178                 val = sc->mtu;
17179                 /* (24*1024 + val*4)/256 */
17180                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17181             }
17182         } else {
17183             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17184         }
17185         high = (low + 56); /* 14*1024/256 */
17186         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17187         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17188     }
17189 
17190     if (CHIP_IS_MODE_4_PORT(sc)) {
17191         REG_WR(sc, SC_PORT(sc) ?
17192                BRB1_REG_MAC_GUARANTIED_1 :
17193                BRB1_REG_MAC_GUARANTIED_0, 40);
17194     }
17195 
17196     ecore_init_block(sc, BLOCK_PRS, init_phase);
17197     if (CHIP_IS_E3B0(sc)) {
17198         if (IS_MF_AFEX(sc)) {
17199             /* configure headers for AFEX mode */
17200             REG_WR(sc, SC_PORT(sc) ?
17201                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17202                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17203             REG_WR(sc, SC_PORT(sc) ?
17204                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17205                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17206             REG_WR(sc, SC_PORT(sc) ?
17207                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17208                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17209         } else {
17210             /* Ovlan exists only if we are in multi-function +
17211              * switch-dependent mode, in switch-independent there
17212              * is no ovlan headers
17213              */
17214             REG_WR(sc, SC_PORT(sc) ?
17215                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17216                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17217                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17218         }
17219     }
17220 
17221     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17222     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17223     ecore_init_block(sc, BLOCK_USDM, init_phase);
17224     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17225 
17226     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17227     ecore_init_block(sc, BLOCK_USEM, init_phase);
17228     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17229     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17230 
17231     ecore_init_block(sc, BLOCK_UPB, init_phase);
17232     ecore_init_block(sc, BLOCK_XPB, init_phase);
17233 
17234     ecore_init_block(sc, BLOCK_PBF, init_phase);
17235 
17236     if (CHIP_IS_E1x(sc)) {
17237         /* configure PBF to work without PAUSE mtu 9000 */
17238         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17239 
17240         /* update threshold */
17241         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17242         /* update init credit */
17243         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17244 
17245         /* probe changes */
17246         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17247         DELAY(50);
17248         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17249     }
17250 
17251     if (CNIC_SUPPORT(sc)) {
17252         ecore_init_block(sc, BLOCK_SRC, init_phase);
17253     }
17254 
17255     ecore_init_block(sc, BLOCK_CDU, init_phase);
17256     ecore_init_block(sc, BLOCK_CFC, init_phase);
17257 
17258     if (CHIP_IS_E1(sc)) {
17259         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17260         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17261     }
17262     ecore_init_block(sc, BLOCK_HC, init_phase);
17263 
17264     ecore_init_block(sc, BLOCK_IGU, init_phase);
17265 
17266     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17267     /* init aeu_mask_attn_func_0/1:
17268      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17269      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17270      *             bits 4-7 are used for "per vn group attention" */
17271     val = IS_MF(sc) ? 0xF7 : 0x7;
17272     /* Enable DCBX attention for all but E1 */
17273     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17274     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17275 
17276     ecore_init_block(sc, BLOCK_NIG, init_phase);
17277 
17278     if (!CHIP_IS_E1x(sc)) {
17279         /* Bit-map indicating which L2 hdrs may appear after the
17280          * basic Ethernet header
17281          */
17282         if (IS_MF_AFEX(sc)) {
17283             REG_WR(sc, SC_PORT(sc) ?
17284                    NIG_REG_P1_HDRS_AFTER_BASIC :
17285                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17286         } else {
17287             REG_WR(sc, SC_PORT(sc) ?
17288                    NIG_REG_P1_HDRS_AFTER_BASIC :
17289                    NIG_REG_P0_HDRS_AFTER_BASIC,
17290                    IS_MF_SD(sc) ? 7 : 6);
17291         }
17292 
17293         if (CHIP_IS_E3(sc)) {
17294             REG_WR(sc, SC_PORT(sc) ?
17295                    NIG_REG_LLH1_MF_MODE :
17296                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17297         }
17298     }
17299     if (!CHIP_IS_E3(sc)) {
17300         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17301     }
17302 
17303     if (!CHIP_IS_E1(sc)) {
17304         /* 0x2 disable mf_ov, 0x1 enable */
17305         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17306                (IS_MF_SD(sc) ? 0x1 : 0x2));
17307 
17308         if (!CHIP_IS_E1x(sc)) {
17309             val = 0;
17310             switch (sc->devinfo.mf_info.mf_mode) {
17311             case MULTI_FUNCTION_SD:
17312                 val = 1;
17313                 break;
17314             case MULTI_FUNCTION_SI:
17315             case MULTI_FUNCTION_AFEX:
17316                 val = 2;
17317                 break;
17318             }
17319 
17320             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17321                         NIG_REG_LLH0_CLS_TYPE), val);
17322         }
17323         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17324         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17325         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17326     }
17327 
17328     /* If SPIO5 is set to generate interrupts, enable it for this port */
17329     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17330     if (val & MISC_SPIO_SPIO5) {
17331         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17332                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17333         val = REG_RD(sc, reg_addr);
17334         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17335         REG_WR(sc, reg_addr, val);
17336     }
17337 
17338     return (0);
17339 }
17340 
17341 static uint32_t
17342 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17343                        uint32_t         reg,
17344                        uint32_t         expected,
17345                        uint32_t         poll_count)
17346 {
17347     uint32_t cur_cnt = poll_count;
17348     uint32_t val;
17349 
17350     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17351         DELAY(FLR_WAIT_INTERVAL);
17352     }
17353 
17354     return (val);
17355 }
17356 
17357 static int
17358 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17359                               uint32_t         reg,
17360                               char             *msg,
17361                               uint32_t         poll_cnt)
17362 {
17363     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17364 
17365     if (val != 0) {
17366         BLOGE(sc, "%s usage count=%d\n", msg, val);
17367         return (1);
17368     }
17369 
17370     return (0);
17371 }
17372 
17373 /* Common routines with VF FLR cleanup */
17374 static uint32_t
17375 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17376 {
17377     /* adjust polling timeout */
17378     if (CHIP_REV_IS_EMUL(sc)) {
17379         return (FLR_POLL_CNT * 2000);
17380     }
17381 
17382     if (CHIP_REV_IS_FPGA(sc)) {
17383         return (FLR_POLL_CNT * 120);
17384     }
17385 
17386     return (FLR_POLL_CNT);
17387 }
17388 
17389 static int
17390 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17391                            uint32_t         poll_cnt)
17392 {
17393     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17394     if (bxe_flr_clnup_poll_hw_counter(sc,
17395                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17396                                       "CFC PF usage counter timed out",
17397                                       poll_cnt)) {
17398         return (1);
17399     }
17400 
17401     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17402     if (bxe_flr_clnup_poll_hw_counter(sc,
17403                                       DORQ_REG_PF_USAGE_CNT,
17404                                       "DQ PF usage counter timed out",
17405                                       poll_cnt)) {
17406         return (1);
17407     }
17408 
17409     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17410     if (bxe_flr_clnup_poll_hw_counter(sc,
17411                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17412                                       "QM PF usage counter timed out",
17413                                       poll_cnt)) {
17414         return (1);
17415     }
17416 
17417     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17418     if (bxe_flr_clnup_poll_hw_counter(sc,
17419                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17420                                       "Timers VNIC usage counter timed out",
17421                                       poll_cnt)) {
17422         return (1);
17423     }
17424 
17425     if (bxe_flr_clnup_poll_hw_counter(sc,
17426                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17427                                       "Timers NUM_SCANS usage counter timed out",
17428                                       poll_cnt)) {
17429         return (1);
17430     }
17431 
17432     /* Wait DMAE PF usage counter to zero */
17433     if (bxe_flr_clnup_poll_hw_counter(sc,
17434                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17435                                       "DMAE dommand register timed out",
17436                                       poll_cnt)) {
17437         return (1);
17438     }
17439 
17440     return (0);
17441 }
17442 
17443 #define OP_GEN_PARAM(param)                                            \
17444     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17445 #define OP_GEN_TYPE(type)                                           \
17446     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17447 #define OP_GEN_AGG_VECT(index)                                             \
17448     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17449 
17450 static int
17451 bxe_send_final_clnup(struct bxe_softc *sc,
17452                      uint8_t          clnup_func,
17453                      uint32_t         poll_cnt)
17454 {
17455     uint32_t op_gen_command = 0;
17456     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17457                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17458     int ret = 0;
17459 
17460     if (REG_RD(sc, comp_addr)) {
17461         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17462         return (1);
17463     }
17464 
17465     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17466     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17467     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17468     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17469 
17470     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17471     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17472 
17473     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17474         BLOGE(sc, "FW final cleanup did not succeed\n");
17475         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17476               (REG_RD(sc, comp_addr)));
17477         bxe_panic(sc, ("FLR cleanup failed\n"));
17478         return (1);
17479     }
17480 
17481     /* Zero completion for nxt FLR */
17482     REG_WR(sc, comp_addr, 0);
17483 
17484     return (ret);
17485 }
17486 
17487 static void
17488 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17489                        struct pbf_pN_buf_regs *regs,
17490                        uint32_t               poll_count)
17491 {
17492     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17493     uint32_t cur_cnt = poll_count;
17494 
17495     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17496     crd = crd_start = REG_RD(sc, regs->crd);
17497     init_crd = REG_RD(sc, regs->init_crd);
17498 
17499     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17500     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17501     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17502 
17503     while ((crd != init_crd) &&
17504            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17505             (init_crd - crd_start))) {
17506         if (cur_cnt--) {
17507             DELAY(FLR_WAIT_INTERVAL);
17508             crd = REG_RD(sc, regs->crd);
17509             crd_freed = REG_RD(sc, regs->crd_freed);
17510         } else {
17511             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17512             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17513             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17514             break;
17515         }
17516     }
17517 
17518     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17519           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17520 }
17521 
17522 static void
17523 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17524                        struct pbf_pN_cmd_regs *regs,
17525                        uint32_t               poll_count)
17526 {
17527     uint32_t occup, to_free, freed, freed_start;
17528     uint32_t cur_cnt = poll_count;
17529 
17530     occup = to_free = REG_RD(sc, regs->lines_occup);
17531     freed = freed_start = REG_RD(sc, regs->lines_freed);
17532 
17533     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17534     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17535 
17536     while (occup &&
17537            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17538         if (cur_cnt--) {
17539             DELAY(FLR_WAIT_INTERVAL);
17540             occup = REG_RD(sc, regs->lines_occup);
17541             freed = REG_RD(sc, regs->lines_freed);
17542         } else {
17543             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17544             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17545             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17546             break;
17547         }
17548     }
17549 
17550     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17551           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17552 }
17553 
17554 static void
17555 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17556 {
17557     struct pbf_pN_cmd_regs cmd_regs[] = {
17558         {0, (CHIP_IS_E3B0(sc)) ?
17559             PBF_REG_TQ_OCCUPANCY_Q0 :
17560             PBF_REG_P0_TQ_OCCUPANCY,
17561             (CHIP_IS_E3B0(sc)) ?
17562             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17563             PBF_REG_P0_TQ_LINES_FREED_CNT},
17564         {1, (CHIP_IS_E3B0(sc)) ?
17565             PBF_REG_TQ_OCCUPANCY_Q1 :
17566             PBF_REG_P1_TQ_OCCUPANCY,
17567             (CHIP_IS_E3B0(sc)) ?
17568             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17569             PBF_REG_P1_TQ_LINES_FREED_CNT},
17570         {4, (CHIP_IS_E3B0(sc)) ?
17571             PBF_REG_TQ_OCCUPANCY_LB_Q :
17572             PBF_REG_P4_TQ_OCCUPANCY,
17573             (CHIP_IS_E3B0(sc)) ?
17574             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17575             PBF_REG_P4_TQ_LINES_FREED_CNT}
17576     };
17577 
17578     struct pbf_pN_buf_regs buf_regs[] = {
17579         {0, (CHIP_IS_E3B0(sc)) ?
17580             PBF_REG_INIT_CRD_Q0 :
17581             PBF_REG_P0_INIT_CRD ,
17582             (CHIP_IS_E3B0(sc)) ?
17583             PBF_REG_CREDIT_Q0 :
17584             PBF_REG_P0_CREDIT,
17585             (CHIP_IS_E3B0(sc)) ?
17586             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17587             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17588         {1, (CHIP_IS_E3B0(sc)) ?
17589             PBF_REG_INIT_CRD_Q1 :
17590             PBF_REG_P1_INIT_CRD,
17591             (CHIP_IS_E3B0(sc)) ?
17592             PBF_REG_CREDIT_Q1 :
17593             PBF_REG_P1_CREDIT,
17594             (CHIP_IS_E3B0(sc)) ?
17595             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17596             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17597         {4, (CHIP_IS_E3B0(sc)) ?
17598             PBF_REG_INIT_CRD_LB_Q :
17599             PBF_REG_P4_INIT_CRD,
17600             (CHIP_IS_E3B0(sc)) ?
17601             PBF_REG_CREDIT_LB_Q :
17602             PBF_REG_P4_CREDIT,
17603             (CHIP_IS_E3B0(sc)) ?
17604             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17605             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17606     };
17607 
17608     int i;
17609 
17610     /* Verify the command queues are flushed P0, P1, P4 */
17611     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17612         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17613     }
17614 
17615     /* Verify the transmission buffers are flushed P0, P1, P4 */
17616     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17617         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17618     }
17619 }
17620 
17621 static void
17622 bxe_hw_enable_status(struct bxe_softc *sc)
17623 {
17624     uint32_t val;
17625 
17626     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17627     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17628 
17629     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17630     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17631 
17632     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17633     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17634 
17635     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17636     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17637 
17638     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17639     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17640 
17641     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17642     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17643 
17644     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17645     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17646 
17647     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17648     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17649 }
17650 
17651 static int
17652 bxe_pf_flr_clnup(struct bxe_softc *sc)
17653 {
17654     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17655 
17656     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17657 
17658     /* Re-enable PF target read access */
17659     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17660 
17661     /* Poll HW usage counters */
17662     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17663     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17664         return (-1);
17665     }
17666 
17667     /* Zero the igu 'trailing edge' and 'leading edge' */
17668 
17669     /* Send the FW cleanup command */
17670     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17671         return (-1);
17672     }
17673 
17674     /* ATC cleanup */
17675 
17676     /* Verify TX hw is flushed */
17677     bxe_tx_hw_flushed(sc, poll_cnt);
17678 
17679     /* Wait 100ms (not adjusted according to platform) */
17680     DELAY(100000);
17681 
17682     /* Verify no pending pci transactions */
17683     if (bxe_is_pcie_pending(sc)) {
17684         BLOGE(sc, "PCIE Transactions still pending\n");
17685     }
17686 
17687     /* Debug */
17688     bxe_hw_enable_status(sc);
17689 
17690     /*
17691      * Master enable - Due to WB DMAE writes performed before this
17692      * register is re-initialized as part of the regular function init
17693      */
17694     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17695 
17696     return (0);
17697 }
17698 
17699 static int
17700 bxe_init_hw_func(struct bxe_softc *sc)
17701 {
17702     int port = SC_PORT(sc);
17703     int func = SC_FUNC(sc);
17704     int init_phase = PHASE_PF0 + func;
17705     struct ecore_ilt *ilt = sc->ilt;
17706     uint16_t cdu_ilt_start;
17707     uint32_t addr, val;
17708     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17709     int i, main_mem_width, rc;
17710 
17711     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17712 
17713     /* FLR cleanup */
17714     if (!CHIP_IS_E1x(sc)) {
17715         rc = bxe_pf_flr_clnup(sc);
17716         if (rc) {
17717             BLOGE(sc, "FLR cleanup failed!\n");
17718             // XXX bxe_fw_dump(sc);
17719             // XXX bxe_idle_chk(sc);
17720             return (rc);
17721         }
17722     }
17723 
17724     /* set MSI reconfigure capability */
17725     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17726         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17727         val = REG_RD(sc, addr);
17728         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17729         REG_WR(sc, addr, val);
17730     }
17731 
17732     ecore_init_block(sc, BLOCK_PXP, init_phase);
17733     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17734 
17735     ilt = sc->ilt;
17736     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17737 
17738     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17739         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17740         ilt->lines[cdu_ilt_start + i].page_mapping =
17741             sc->context[i].vcxt_dma.paddr;
17742         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17743     }
17744     ecore_ilt_init_op(sc, INITOP_SET);
17745 
17746     /* Set NIC mode */
17747     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17748     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17749 
17750     if (!CHIP_IS_E1x(sc)) {
17751         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17752 
17753         /* Turn on a single ISR mode in IGU if driver is going to use
17754          * INT#x or MSI
17755          */
17756         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17757             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17758         }
17759 
17760         /*
17761          * Timers workaround bug: function init part.
17762          * Need to wait 20msec after initializing ILT,
17763          * needed to make sure there are no requests in
17764          * one of the PXP internal queues with "old" ILT addresses
17765          */
17766         DELAY(20000);
17767 
17768         /*
17769          * Master enable - Due to WB DMAE writes performed before this
17770          * register is re-initialized as part of the regular function
17771          * init
17772          */
17773         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17774         /* Enable the function in IGU */
17775         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17776     }
17777 
17778     sc->dmae_ready = 1;
17779 
17780     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17781 
17782     if (!CHIP_IS_E1x(sc))
17783         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17784 
17785     ecore_init_block(sc, BLOCK_ATC, init_phase);
17786     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17787     ecore_init_block(sc, BLOCK_NIG, init_phase);
17788     ecore_init_block(sc, BLOCK_SRC, init_phase);
17789     ecore_init_block(sc, BLOCK_MISC, init_phase);
17790     ecore_init_block(sc, BLOCK_TCM, init_phase);
17791     ecore_init_block(sc, BLOCK_UCM, init_phase);
17792     ecore_init_block(sc, BLOCK_CCM, init_phase);
17793     ecore_init_block(sc, BLOCK_XCM, init_phase);
17794     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17795     ecore_init_block(sc, BLOCK_USEM, init_phase);
17796     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17797     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17798 
17799     if (!CHIP_IS_E1x(sc))
17800         REG_WR(sc, QM_REG_PF_EN, 1);
17801 
17802     if (!CHIP_IS_E1x(sc)) {
17803         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17804         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17805         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17806         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17807     }
17808     ecore_init_block(sc, BLOCK_QM, init_phase);
17809 
17810     ecore_init_block(sc, BLOCK_TM, init_phase);
17811     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17812 
17813     bxe_iov_init_dq(sc);
17814 
17815     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17816     ecore_init_block(sc, BLOCK_PRS, init_phase);
17817     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17818     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17819     ecore_init_block(sc, BLOCK_USDM, init_phase);
17820     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17821     ecore_init_block(sc, BLOCK_UPB, init_phase);
17822     ecore_init_block(sc, BLOCK_XPB, init_phase);
17823     ecore_init_block(sc, BLOCK_PBF, init_phase);
17824     if (!CHIP_IS_E1x(sc))
17825         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17826 
17827     ecore_init_block(sc, BLOCK_CDU, init_phase);
17828 
17829     ecore_init_block(sc, BLOCK_CFC, init_phase);
17830 
17831     if (!CHIP_IS_E1x(sc))
17832         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17833 
17834     if (IS_MF(sc)) {
17835         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17836         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17837     }
17838 
17839     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17840 
17841     /* HC init per function */
17842     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17843         if (CHIP_IS_E1H(sc)) {
17844             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17845 
17846             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17847             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17848         }
17849         ecore_init_block(sc, BLOCK_HC, init_phase);
17850 
17851     } else {
17852         int num_segs, sb_idx, prod_offset;
17853 
17854         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17855 
17856         if (!CHIP_IS_E1x(sc)) {
17857             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17858             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17859         }
17860 
17861         ecore_init_block(sc, BLOCK_IGU, init_phase);
17862 
17863         if (!CHIP_IS_E1x(sc)) {
17864             int dsb_idx = 0;
17865             /**
17866              * Producer memory:
17867              * E2 mode: address 0-135 match to the mapping memory;
17868              * 136 - PF0 default prod; 137 - PF1 default prod;
17869              * 138 - PF2 default prod; 139 - PF3 default prod;
17870              * 140 - PF0 attn prod;    141 - PF1 attn prod;
17871              * 142 - PF2 attn prod;    143 - PF3 attn prod;
17872              * 144-147 reserved.
17873              *
17874              * E1.5 mode - In backward compatible mode;
17875              * for non default SB; each even line in the memory
17876              * holds the U producer and each odd line hold
17877              * the C producer. The first 128 producers are for
17878              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
17879              * producers are for the DSB for each PF.
17880              * Each PF has five segments: (the order inside each
17881              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
17882              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
17883              * 144-147 attn prods;
17884              */
17885             /* non-default-status-blocks */
17886             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17887                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
17888             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
17889                 prod_offset = (sc->igu_base_sb + sb_idx) *
17890                     num_segs;
17891 
17892                 for (i = 0; i < num_segs; i++) {
17893                     addr = IGU_REG_PROD_CONS_MEMORY +
17894                             (prod_offset + i) * 4;
17895                     REG_WR(sc, addr, 0);
17896                 }
17897                 /* send consumer update with value 0 */
17898                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
17899                            USTORM_ID, 0, IGU_INT_NOP, 1);
17900                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
17901             }
17902 
17903             /* default-status-blocks */
17904             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17905                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
17906 
17907             if (CHIP_IS_MODE_4_PORT(sc))
17908                 dsb_idx = SC_FUNC(sc);
17909             else
17910                 dsb_idx = SC_VN(sc);
17911 
17912             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
17913                        IGU_BC_BASE_DSB_PROD + dsb_idx :
17914                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
17915 
17916             /*
17917              * igu prods come in chunks of E1HVN_MAX (4) -
17918              * does not matters what is the current chip mode
17919              */
17920             for (i = 0; i < (num_segs * E1HVN_MAX);
17921                  i += E1HVN_MAX) {
17922                 addr = IGU_REG_PROD_CONS_MEMORY +
17923                             (prod_offset + i)*4;
17924                 REG_WR(sc, addr, 0);
17925             }
17926             /* send consumer update with 0 */
17927             if (CHIP_INT_MODE_IS_BC(sc)) {
17928                 bxe_ack_sb(sc, sc->igu_dsb_id,
17929                            USTORM_ID, 0, IGU_INT_NOP, 1);
17930                 bxe_ack_sb(sc, sc->igu_dsb_id,
17931                            CSTORM_ID, 0, IGU_INT_NOP, 1);
17932                 bxe_ack_sb(sc, sc->igu_dsb_id,
17933                            XSTORM_ID, 0, IGU_INT_NOP, 1);
17934                 bxe_ack_sb(sc, sc->igu_dsb_id,
17935                            TSTORM_ID, 0, IGU_INT_NOP, 1);
17936                 bxe_ack_sb(sc, sc->igu_dsb_id,
17937                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17938             } else {
17939                 bxe_ack_sb(sc, sc->igu_dsb_id,
17940                            USTORM_ID, 0, IGU_INT_NOP, 1);
17941                 bxe_ack_sb(sc, sc->igu_dsb_id,
17942                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17943             }
17944             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
17945 
17946             /* !!! these should become driver const once
17947                rf-tool supports split-68 const */
17948             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
17949             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
17950             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
17951             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
17952             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
17953             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
17954         }
17955     }
17956 
17957     /* Reset PCIE errors for debug */
17958     REG_WR(sc, 0x2114, 0xffffffff);
17959     REG_WR(sc, 0x2120, 0xffffffff);
17960 
17961     if (CHIP_IS_E1x(sc)) {
17962         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
17963         main_mem_base = HC_REG_MAIN_MEMORY +
17964                 SC_PORT(sc) * (main_mem_size * 4);
17965         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
17966         main_mem_width = 8;
17967 
17968         val = REG_RD(sc, main_mem_prty_clr);
17969         if (val) {
17970             BLOGD(sc, DBG_LOAD,
17971                   "Parity errors in HC block during function init (0x%x)!\n",
17972                   val);
17973         }
17974 
17975         /* Clear "false" parity errors in MSI-X table */
17976         for (i = main_mem_base;
17977              i < main_mem_base + main_mem_size * 4;
17978              i += main_mem_width) {
17979             bxe_read_dmae(sc, i, main_mem_width / 4);
17980             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
17981                            i, main_mem_width / 4);
17982         }
17983         /* Clear HC parity attention */
17984         REG_RD(sc, main_mem_prty_clr);
17985     }
17986 
17987 #if 1
17988     /* Enable STORMs SP logging */
17989     REG_WR8(sc, BAR_USTRORM_INTMEM +
17990            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17991     REG_WR8(sc, BAR_TSTRORM_INTMEM +
17992            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17993     REG_WR8(sc, BAR_CSTRORM_INTMEM +
17994            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17995     REG_WR8(sc, BAR_XSTRORM_INTMEM +
17996            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17997 #endif
17998 
17999     elink_phy_probe(&sc->link_params);
18000 
18001     return (0);
18002 }
18003 
18004 static void
18005 bxe_link_reset(struct bxe_softc *sc)
18006 {
18007     if (!BXE_NOMCP(sc)) {
18008 	bxe_acquire_phy_lock(sc);
18009         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18010 	bxe_release_phy_lock(sc);
18011     } else {
18012         if (!CHIP_REV_IS_SLOW(sc)) {
18013             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18014         }
18015     }
18016 }
18017 
18018 static void
18019 bxe_reset_port(struct bxe_softc *sc)
18020 {
18021     int port = SC_PORT(sc);
18022     uint32_t val;
18023 
18024     /* reset physical Link */
18025     bxe_link_reset(sc);
18026 
18027     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18028 
18029     /* Do not rcv packets to BRB */
18030     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18031     /* Do not direct rcv packets that are not for MCP to the BRB */
18032     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18033                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18034 
18035     /* Configure AEU */
18036     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18037 
18038     DELAY(100000);
18039 
18040     /* Check for BRB port occupancy */
18041     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18042     if (val) {
18043         BLOGD(sc, DBG_LOAD,
18044               "BRB1 is not empty, %d blocks are occupied\n", val);
18045     }
18046 
18047     /* TODO: Close Doorbell port? */
18048 }
18049 
18050 static void
18051 bxe_ilt_wr(struct bxe_softc *sc,
18052            uint32_t         index,
18053            bus_addr_t       addr)
18054 {
18055     int reg;
18056     uint32_t wb_write[2];
18057 
18058     if (CHIP_IS_E1(sc)) {
18059         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18060     } else {
18061         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18062     }
18063 
18064     wb_write[0] = ONCHIP_ADDR1(addr);
18065     wb_write[1] = ONCHIP_ADDR2(addr);
18066     REG_WR_DMAE(sc, reg, wb_write, 2);
18067 }
18068 
18069 static void
18070 bxe_clear_func_ilt(struct bxe_softc *sc,
18071                    uint32_t         func)
18072 {
18073     uint32_t i, base = FUNC_ILT_BASE(func);
18074     for (i = base; i < base + ILT_PER_FUNC; i++) {
18075         bxe_ilt_wr(sc, i, 0);
18076     }
18077 }
18078 
18079 static void
18080 bxe_reset_func(struct bxe_softc *sc)
18081 {
18082     struct bxe_fastpath *fp;
18083     int port = SC_PORT(sc);
18084     int func = SC_FUNC(sc);
18085     int i;
18086 
18087     /* Disable the function in the FW */
18088     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18089     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18090     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18091     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18092 
18093     /* FP SBs */
18094     FOR_EACH_ETH_QUEUE(sc, i) {
18095         fp = &sc->fp[i];
18096         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18097                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18098                 SB_DISABLED);
18099     }
18100 
18101     /* SP SB */
18102     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18103             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18104             SB_DISABLED);
18105 
18106     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18107         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18108     }
18109 
18110     /* Configure IGU */
18111     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18112         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18113         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18114     } else {
18115         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18116         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18117     }
18118 
18119     if (CNIC_LOADED(sc)) {
18120         /* Disable Timer scan */
18121         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18122         /*
18123          * Wait for at least 10ms and up to 2 second for the timers
18124          * scan to complete
18125          */
18126         for (i = 0; i < 200; i++) {
18127             DELAY(10000);
18128             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18129                 break;
18130         }
18131     }
18132 
18133     /* Clear ILT */
18134     bxe_clear_func_ilt(sc, func);
18135 
18136     /*
18137      * Timers workaround bug for E2: if this is vnic-3,
18138      * we need to set the entire ilt range for this timers.
18139      */
18140     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18141         struct ilt_client_info ilt_cli;
18142         /* use dummy TM client */
18143         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18144         ilt_cli.start = 0;
18145         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18146         ilt_cli.client_num = ILT_CLIENT_TM;
18147 
18148         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18149     }
18150 
18151     /* this assumes that reset_port() called before reset_func()*/
18152     if (!CHIP_IS_E1x(sc)) {
18153         bxe_pf_disable(sc);
18154     }
18155 
18156     sc->dmae_ready = 0;
18157 }
18158 
18159 static int
18160 bxe_gunzip_init(struct bxe_softc *sc)
18161 {
18162     return (0);
18163 }
18164 
18165 static void
18166 bxe_gunzip_end(struct bxe_softc *sc)
18167 {
18168     return;
18169 }
18170 
18171 static int
18172 bxe_init_firmware(struct bxe_softc *sc)
18173 {
18174     if (CHIP_IS_E1(sc)) {
18175         ecore_init_e1_firmware(sc);
18176         sc->iro_array = e1_iro_arr;
18177     } else if (CHIP_IS_E1H(sc)) {
18178         ecore_init_e1h_firmware(sc);
18179         sc->iro_array = e1h_iro_arr;
18180     } else if (!CHIP_IS_E1x(sc)) {
18181         ecore_init_e2_firmware(sc);
18182         sc->iro_array = e2_iro_arr;
18183     } else {
18184         BLOGE(sc, "Unsupported chip revision\n");
18185         return (-1);
18186     }
18187 
18188     return (0);
18189 }
18190 
18191 static void
18192 bxe_release_firmware(struct bxe_softc *sc)
18193 {
18194     /* Do nothing */
18195     return;
18196 }
18197 
18198 static int
18199 ecore_gunzip(struct bxe_softc *sc,
18200              const uint8_t    *zbuf,
18201              int              len)
18202 {
18203     /* XXX : Implement... */
18204     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18205     return (FALSE);
18206 }
18207 
18208 static void
18209 ecore_reg_wr_ind(struct bxe_softc *sc,
18210                  uint32_t         addr,
18211                  uint32_t         val)
18212 {
18213     bxe_reg_wr_ind(sc, addr, val);
18214 }
18215 
18216 static void
18217 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18218                           bus_addr_t       phys_addr,
18219                           uint32_t         addr,
18220                           uint32_t         len)
18221 {
18222     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18223 }
18224 
18225 void
18226 ecore_storm_memset_struct(struct bxe_softc *sc,
18227                           uint32_t         addr,
18228                           size_t           size,
18229                           uint32_t         *data)
18230 {
18231     uint8_t i;
18232     for (i = 0; i < size/4; i++) {
18233         REG_WR(sc, addr + (i * 4), data[i]);
18234     }
18235 }
18236 
18237 
18238 /*
18239  * character device - ioctl interface definitions
18240  */
18241 
18242 
18243 #include "bxe_dump.h"
18244 #include "bxe_ioctl.h"
18245 #include <sys/conf.h>
18246 
18247 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18248                 struct thread *td);
18249 
18250 static struct cdevsw bxe_cdevsw = {
18251     .d_version = D_VERSION,
18252     .d_ioctl = bxe_eioctl,
18253     .d_name = "bxecnic",
18254 };
18255 
18256 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18257 
18258 
18259 #define DUMP_ALL_PRESETS        0x1FFF
18260 #define DUMP_MAX_PRESETS        13
18261 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18262 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18263 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18264 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18265 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18266 
18267 #define IS_REG_IN_PRESET(presets, idx)  \
18268                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18269 
18270 
18271 static int
18272 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18273 {
18274     if (CHIP_IS_E1(sc))
18275         return dump_num_registers[0][preset-1];
18276     else if (CHIP_IS_E1H(sc))
18277         return dump_num_registers[1][preset-1];
18278     else if (CHIP_IS_E2(sc))
18279         return dump_num_registers[2][preset-1];
18280     else if (CHIP_IS_E3A0(sc))
18281         return dump_num_registers[3][preset-1];
18282     else if (CHIP_IS_E3B0(sc))
18283         return dump_num_registers[4][preset-1];
18284     else
18285         return 0;
18286 }
18287 
18288 static int
18289 bxe_get_total_regs_len32(struct bxe_softc *sc)
18290 {
18291     uint32_t preset_idx;
18292     int regdump_len32 = 0;
18293 
18294 
18295     /* Calculate the total preset regs length */
18296     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18297         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18298     }
18299 
18300     return regdump_len32;
18301 }
18302 
18303 static const uint32_t *
18304 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18305 {
18306     if (CHIP_IS_E2(sc))
18307         return page_vals_e2;
18308     else if (CHIP_IS_E3(sc))
18309         return page_vals_e3;
18310     else
18311         return NULL;
18312 }
18313 
18314 static uint32_t
18315 __bxe_get_page_reg_num(struct bxe_softc *sc)
18316 {
18317     if (CHIP_IS_E2(sc))
18318         return PAGE_MODE_VALUES_E2;
18319     else if (CHIP_IS_E3(sc))
18320         return PAGE_MODE_VALUES_E3;
18321     else
18322         return 0;
18323 }
18324 
18325 static const uint32_t *
18326 __bxe_get_page_write_ar(struct bxe_softc *sc)
18327 {
18328     if (CHIP_IS_E2(sc))
18329         return page_write_regs_e2;
18330     else if (CHIP_IS_E3(sc))
18331         return page_write_regs_e3;
18332     else
18333         return NULL;
18334 }
18335 
18336 static uint32_t
18337 __bxe_get_page_write_num(struct bxe_softc *sc)
18338 {
18339     if (CHIP_IS_E2(sc))
18340         return PAGE_WRITE_REGS_E2;
18341     else if (CHIP_IS_E3(sc))
18342         return PAGE_WRITE_REGS_E3;
18343     else
18344         return 0;
18345 }
18346 
18347 static const struct reg_addr *
18348 __bxe_get_page_read_ar(struct bxe_softc *sc)
18349 {
18350     if (CHIP_IS_E2(sc))
18351         return page_read_regs_e2;
18352     else if (CHIP_IS_E3(sc))
18353         return page_read_regs_e3;
18354     else
18355         return NULL;
18356 }
18357 
18358 static uint32_t
18359 __bxe_get_page_read_num(struct bxe_softc *sc)
18360 {
18361     if (CHIP_IS_E2(sc))
18362         return PAGE_READ_REGS_E2;
18363     else if (CHIP_IS_E3(sc))
18364         return PAGE_READ_REGS_E3;
18365     else
18366         return 0;
18367 }
18368 
18369 static bool
18370 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18371 {
18372     if (CHIP_IS_E1(sc))
18373         return IS_E1_REG(reg_info->chips);
18374     else if (CHIP_IS_E1H(sc))
18375         return IS_E1H_REG(reg_info->chips);
18376     else if (CHIP_IS_E2(sc))
18377         return IS_E2_REG(reg_info->chips);
18378     else if (CHIP_IS_E3A0(sc))
18379         return IS_E3A0_REG(reg_info->chips);
18380     else if (CHIP_IS_E3B0(sc))
18381         return IS_E3B0_REG(reg_info->chips);
18382     else
18383         return 0;
18384 }
18385 
18386 static bool
18387 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18388 {
18389     if (CHIP_IS_E1(sc))
18390         return IS_E1_REG(wreg_info->chips);
18391     else if (CHIP_IS_E1H(sc))
18392         return IS_E1H_REG(wreg_info->chips);
18393     else if (CHIP_IS_E2(sc))
18394         return IS_E2_REG(wreg_info->chips);
18395     else if (CHIP_IS_E3A0(sc))
18396         return IS_E3A0_REG(wreg_info->chips);
18397     else if (CHIP_IS_E3B0(sc))
18398         return IS_E3B0_REG(wreg_info->chips);
18399     else
18400         return 0;
18401 }
18402 
18403 /**
18404  * bxe_read_pages_regs - read "paged" registers
18405  *
18406  * @bp          device handle
18407  * @p           output buffer
18408  *
18409  * Reads "paged" memories: memories that may only be read by first writing to a
18410  * specific address ("write address") and then reading from a specific address
18411  * ("read address"). There may be more than one write address per "page" and
18412  * more than one read address per write address.
18413  */
18414 static void
18415 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18416 {
18417     uint32_t i, j, k, n;
18418 
18419     /* addresses of the paged registers */
18420     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18421     /* number of paged registers */
18422     int num_pages = __bxe_get_page_reg_num(sc);
18423     /* write addresses */
18424     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18425     /* number of write addresses */
18426     int write_num = __bxe_get_page_write_num(sc);
18427     /* read addresses info */
18428     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18429     /* number of read addresses */
18430     int read_num = __bxe_get_page_read_num(sc);
18431     uint32_t addr, size;
18432 
18433     for (i = 0; i < num_pages; i++) {
18434         for (j = 0; j < write_num; j++) {
18435             REG_WR(sc, write_addr[j], page_addr[i]);
18436 
18437             for (k = 0; k < read_num; k++) {
18438                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18439                     size = read_addr[k].size;
18440                     for (n = 0; n < size; n++) {
18441                         addr = read_addr[k].addr + n*4;
18442                         *p++ = REG_RD(sc, addr);
18443                     }
18444                 }
18445             }
18446         }
18447     }
18448     return;
18449 }
18450 
18451 
18452 static int
18453 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18454 {
18455     uint32_t i, j, addr;
18456     const struct wreg_addr *wreg_addr_p = NULL;
18457 
18458     if (CHIP_IS_E1(sc))
18459         wreg_addr_p = &wreg_addr_e1;
18460     else if (CHIP_IS_E1H(sc))
18461         wreg_addr_p = &wreg_addr_e1h;
18462     else if (CHIP_IS_E2(sc))
18463         wreg_addr_p = &wreg_addr_e2;
18464     else if (CHIP_IS_E3A0(sc))
18465         wreg_addr_p = &wreg_addr_e3;
18466     else if (CHIP_IS_E3B0(sc))
18467         wreg_addr_p = &wreg_addr_e3b0;
18468     else
18469         return (-1);
18470 
18471     /* Read the idle_chk registers */
18472     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18473         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18474             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18475             for (j = 0; j < idle_reg_addrs[i].size; j++)
18476                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18477         }
18478     }
18479 
18480     /* Read the regular registers */
18481     for (i = 0; i < REGS_COUNT; i++) {
18482         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18483             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18484             for (j = 0; j < reg_addrs[i].size; j++)
18485                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18486         }
18487     }
18488 
18489     /* Read the CAM registers */
18490     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18491         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18492         for (i = 0; i < wreg_addr_p->size; i++) {
18493             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18494 
18495             /* In case of wreg_addr register, read additional
18496                registers from read_regs array
18497              */
18498             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18499                 addr = *(wreg_addr_p->read_regs);
18500                 *p++ = REG_RD(sc, addr + j*4);
18501             }
18502         }
18503     }
18504 
18505     /* Paged registers are supported in E2 & E3 only */
18506     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18507         /* Read "paged" registers */
18508         bxe_read_pages_regs(sc, p, preset);
18509     }
18510 
18511     return 0;
18512 }
18513 
18514 int
18515 bxe_grc_dump(struct bxe_softc *sc)
18516 {
18517     int rval = 0;
18518     uint32_t preset_idx;
18519     uint8_t *buf;
18520     uint32_t size;
18521     struct  dump_header *d_hdr;
18522     uint32_t i;
18523     uint32_t reg_val;
18524     uint32_t reg_addr;
18525     uint32_t cmd_offset;
18526     int context_size;
18527     int allocated;
18528     struct ecore_ilt *ilt = SC_ILT(sc);
18529     struct bxe_fastpath *fp;
18530     struct ilt_client_info *ilt_cli;
18531     int grc_dump_size;
18532 
18533 
18534     if (sc->grcdump_done || sc->grcdump_started)
18535 	return (rval);
18536 
18537     sc->grcdump_started = 1;
18538     BLOGI(sc, "Started collecting grcdump\n");
18539 
18540     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18541                 sizeof(struct  dump_header);
18542 
18543     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18544 
18545     if (sc->grc_dump == NULL) {
18546         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18547         return(ENOMEM);
18548     }
18549 
18550 
18551 
18552     /* Disable parity attentions as long as following dump may
18553      * cause false alarms by reading never written registers. We
18554      * will re-enable parity attentions right after the dump.
18555      */
18556 
18557     /* Disable parity on path 0 */
18558     bxe_pretend_func(sc, 0);
18559 
18560     ecore_disable_blocks_parity(sc);
18561 
18562     /* Disable parity on path 1 */
18563     bxe_pretend_func(sc, 1);
18564     ecore_disable_blocks_parity(sc);
18565 
18566     /* Return to current function */
18567     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18568 
18569     buf = sc->grc_dump;
18570     d_hdr = sc->grc_dump;
18571 
18572     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18573     d_hdr->version = BNX2X_DUMP_VERSION;
18574     d_hdr->preset = DUMP_ALL_PRESETS;
18575 
18576     if (CHIP_IS_E1(sc)) {
18577         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18578     } else if (CHIP_IS_E1H(sc)) {
18579         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18580     } else if (CHIP_IS_E2(sc)) {
18581         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18582                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18583     } else if (CHIP_IS_E3A0(sc)) {
18584         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18585                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18586     } else if (CHIP_IS_E3B0(sc)) {
18587         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18588                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18589     }
18590 
18591     buf += sizeof(struct  dump_header);
18592 
18593     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18594 
18595         /* Skip presets with IOR */
18596         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18597             (preset_idx == 11))
18598             continue;
18599 
18600         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18601 
18602 	if (rval)
18603             break;
18604 
18605         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18606 
18607         buf += size;
18608     }
18609 
18610     bxe_pretend_func(sc, 0);
18611     ecore_clear_blocks_parity(sc);
18612     ecore_enable_blocks_parity(sc);
18613 
18614     bxe_pretend_func(sc, 1);
18615     ecore_clear_blocks_parity(sc);
18616     ecore_enable_blocks_parity(sc);
18617 
18618     /* Return to current function */
18619     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18620 
18621 
18622     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
18623     for (i = 0, allocated = 0; allocated < context_size; i++) {
18624 
18625         BLOGI(sc, "cdu_context i %d paddr %#jx vaddr %p size 0x%zx\n", i,
18626             (uintmax_t)sc->context[i].vcxt_dma.paddr,
18627             sc->context[i].vcxt_dma.vaddr,
18628             sc->context[i].size);
18629         allocated += sc->context[i].size;
18630     }
18631     BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18632         (uintmax_t)sc->fw_stats_req_mapping,
18633         (uintmax_t)sc->fw_stats_data_mapping,
18634         sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18635     BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18636         (void *)sc->def_sb_dma.paddr, sc->def_sb,
18637         sizeof(struct host_sp_status_block));
18638     BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18639         (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18640     BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18641         (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18642         sizeof(struct bxe_slowpath));
18643     BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18644         (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18645     BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18646         (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18647         FW_BUF_SIZE);
18648     for (i = 0; i < sc->num_queues; i++) {
18649         fp = &sc->fp[i];
18650         BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18651             (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18652             sizeof(union bxe_host_hc_status_block));
18653         BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18654             (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18655             (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18656         BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18657             (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18658             (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18659         BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18660             (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18661             (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18662         BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18663             (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18664             (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18665     }
18666 
18667     ilt_cli = &ilt->clients[1];
18668     for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18669         BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18670             (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18671             ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18672     }
18673 
18674 
18675     cmd_offset = DMAE_REG_CMD_MEM;
18676     for (i = 0; i < 224; i++) {
18677         reg_addr = (cmd_offset +(i * 4));
18678         reg_val = REG_RD(sc, reg_addr);
18679         BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18680             reg_addr, reg_val);
18681     }
18682 
18683 
18684     BLOGI(sc, "Collection of grcdump done\n");
18685     sc->grcdump_done = 1;
18686     return(rval);
18687 }
18688 
18689 static int
18690 bxe_add_cdev(struct bxe_softc *sc)
18691 {
18692     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18693 
18694     if (sc->eeprom == NULL) {
18695         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18696         return (-1);
18697     }
18698 
18699     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18700                             sc->ifp->if_dunit,
18701                             UID_ROOT,
18702                             GID_WHEEL,
18703                             0600,
18704                             "%s",
18705                             if_name(sc->ifp));
18706 
18707     if (sc->ioctl_dev == NULL) {
18708         free(sc->eeprom, M_DEVBUF);
18709         sc->eeprom = NULL;
18710         return (-1);
18711     }
18712 
18713     sc->ioctl_dev->si_drv1 = sc;
18714 
18715     return (0);
18716 }
18717 
18718 static void
18719 bxe_del_cdev(struct bxe_softc *sc)
18720 {
18721     if (sc->ioctl_dev != NULL)
18722         destroy_dev(sc->ioctl_dev);
18723 
18724     if (sc->eeprom != NULL) {
18725         free(sc->eeprom, M_DEVBUF);
18726         sc->eeprom = NULL;
18727     }
18728     sc->ioctl_dev = NULL;
18729 
18730     return;
18731 }
18732 
18733 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18734 {
18735 
18736     if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
18737         return FALSE;
18738 
18739     return TRUE;
18740 }
18741 
18742 
18743 static int
18744 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18745 {
18746     int rval = 0;
18747 
18748     if(!bxe_is_nvram_accessible(sc)) {
18749         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18750         return (-EAGAIN);
18751     }
18752     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18753 
18754 
18755    return (rval);
18756 }
18757 
18758 static int
18759 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18760 {
18761     int rval = 0;
18762 
18763     if(!bxe_is_nvram_accessible(sc)) {
18764         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18765         return (-EAGAIN);
18766     }
18767     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18768 
18769    return (rval);
18770 }
18771 
18772 static int
18773 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18774 {
18775     int rval = 0;
18776 
18777     switch (eeprom->eeprom_cmd) {
18778 
18779     case BXE_EEPROM_CMD_SET_EEPROM:
18780 
18781         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18782                        eeprom->eeprom_data_len);
18783 
18784         if (rval)
18785             break;
18786 
18787         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18788                        eeprom->eeprom_data_len);
18789         break;
18790 
18791     case BXE_EEPROM_CMD_GET_EEPROM:
18792 
18793         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18794                        eeprom->eeprom_data_len);
18795 
18796         if (rval) {
18797             break;
18798         }
18799 
18800         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18801                        eeprom->eeprom_data_len);
18802         break;
18803 
18804     default:
18805             rval = EINVAL;
18806             break;
18807     }
18808 
18809     if (rval) {
18810         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18811     }
18812 
18813     return (rval);
18814 }
18815 
18816 static int
18817 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18818 {
18819     uint32_t ext_phy_config;
18820     int port = SC_PORT(sc);
18821     int cfg_idx = bxe_get_link_cfg_idx(sc);
18822 
18823     dev_p->supported = sc->port.supported[cfg_idx] |
18824             (sc->port.supported[cfg_idx ^ 1] &
18825             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18826     dev_p->advertising = sc->port.advertising[cfg_idx];
18827     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18828         ELINK_ETH_PHY_SFP_1G_FIBER) {
18829         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18830         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18831     }
18832     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18833         !(sc->flags & BXE_MF_FUNC_DIS)) {
18834         dev_p->duplex = sc->link_vars.duplex;
18835         if (IS_MF(sc) && !BXE_NOMCP(sc))
18836             dev_p->speed = bxe_get_mf_speed(sc);
18837         else
18838             dev_p->speed = sc->link_vars.line_speed;
18839     } else {
18840         dev_p->duplex = DUPLEX_UNKNOWN;
18841         dev_p->speed = SPEED_UNKNOWN;
18842     }
18843 
18844     dev_p->port = bxe_media_detect(sc);
18845 
18846     ext_phy_config = SHMEM_RD(sc,
18847                          dev_info.port_hw_config[port].external_phy_config);
18848     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
18849         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
18850         dev_p->phy_address =  sc->port.phy_addr;
18851     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18852             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
18853         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18854             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
18855         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
18856     else
18857         dev_p->phy_address = 0;
18858 
18859     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
18860         dev_p->autoneg = AUTONEG_ENABLE;
18861     else
18862        dev_p->autoneg = AUTONEG_DISABLE;
18863 
18864 
18865     return 0;
18866 }
18867 
18868 static int
18869 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18870         struct thread *td)
18871 {
18872     struct bxe_softc    *sc;
18873     int                 rval = 0;
18874     device_t            pci_dev;
18875     bxe_grcdump_t       *dump = NULL;
18876     int grc_dump_size;
18877     bxe_drvinfo_t   *drv_infop = NULL;
18878     bxe_dev_setting_t  *dev_p;
18879     bxe_dev_setting_t  dev_set;
18880     bxe_get_regs_t  *reg_p;
18881     bxe_reg_rdw_t *reg_rdw_p;
18882     bxe_pcicfg_rdw_t *cfg_rdw_p;
18883     bxe_perm_mac_addr_t *mac_addr_p;
18884 
18885 
18886     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18887         return ENXIO;
18888 
18889     pci_dev= sc->dev;
18890 
18891     dump = (bxe_grcdump_t *)data;
18892 
18893     switch(cmd) {
18894 
18895         case BXE_GRC_DUMP_SIZE:
18896             dump->pci_func = sc->pcie_func;
18897             dump->grcdump_size =
18898                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18899                      sizeof(struct  dump_header);
18900             break;
18901 
18902         case BXE_GRC_DUMP:
18903 
18904             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18905                                 sizeof(struct  dump_header);
18906             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
18907                 (dump->grcdump_size < grc_dump_size)) {
18908                 rval = EINVAL;
18909                 break;
18910             }
18911 
18912             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
18913                 (!sc->grcdump_started)) {
18914                 rval =  bxe_grc_dump(sc);
18915             }
18916 
18917             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
18918                 (sc->grc_dump != NULL))  {
18919                 dump->grcdump_dwords = grc_dump_size >> 2;
18920                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18921                 free(sc->grc_dump, M_DEVBUF);
18922                 sc->grc_dump = NULL;
18923                 sc->grcdump_started = 0;
18924                 sc->grcdump_done = 0;
18925             }
18926 
18927             break;
18928 
18929         case BXE_DRV_INFO:
18930             drv_infop = (bxe_drvinfo_t *)data;
18931             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
18932             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
18933                 BXE_DRIVER_VERSION);
18934             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
18935                 sc->devinfo.bc_ver_str);
18936             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
18937                 "%s", sc->fw_ver_str);
18938             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
18939             drv_infop->reg_dump_len =
18940                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
18941                     + sizeof(struct  dump_header);
18942             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
18943                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
18944             break;
18945 
18946         case BXE_DEV_SETTING:
18947             dev_p = (bxe_dev_setting_t *)data;
18948             bxe_get_settings(sc, &dev_set);
18949             dev_p->supported = dev_set.supported;
18950             dev_p->advertising = dev_set.advertising;
18951             dev_p->speed = dev_set.speed;
18952             dev_p->duplex = dev_set.duplex;
18953             dev_p->port = dev_set.port;
18954             dev_p->phy_address = dev_set.phy_address;
18955             dev_p->autoneg = dev_set.autoneg;
18956 
18957             break;
18958 
18959         case BXE_GET_REGS:
18960 
18961             reg_p = (bxe_get_regs_t *)data;
18962             grc_dump_size = reg_p->reg_buf_len;
18963 
18964             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
18965                 bxe_grc_dump(sc);
18966             }
18967             if((sc->grcdump_done) && (sc->grcdump_started) &&
18968                 (sc->grc_dump != NULL))  {
18969                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
18970                 free(sc->grc_dump, M_DEVBUF);
18971                 sc->grc_dump = NULL;
18972                 sc->grcdump_started = 0;
18973                 sc->grcdump_done = 0;
18974             }
18975 
18976             break;
18977 
18978         case BXE_RDW_REG:
18979             reg_rdw_p = (bxe_reg_rdw_t *)data;
18980             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
18981                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18982                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
18983 
18984             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
18985                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18986                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
18987 
18988             break;
18989 
18990         case BXE_RDW_PCICFG:
18991             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
18992             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
18993 
18994                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
18995                                          cfg_rdw_p->cfg_width);
18996 
18997             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
18998                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
18999                             cfg_rdw_p->cfg_width);
19000             } else {
19001                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19002             }
19003             break;
19004 
19005         case BXE_MAC_ADDR:
19006             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19007             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19008                 sc->mac_addr_str);
19009             break;
19010 
19011         case BXE_EEPROM:
19012             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19013             break;
19014 
19015 
19016         default:
19017             break;
19018     }
19019 
19020     return (rval);
19021 }
19022