xref: /freebsd/sys/dev/bxe/bxe.c (revision 780fb4a2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  * THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #define BXE_DRIVER_VERSION "1.78.91"
33 
34 #include "bxe.h"
35 #include "ecore_sp.h"
36 #include "ecore_init.h"
37 #include "ecore_init_ops.h"
38 
39 #include "57710_int_offsets.h"
40 #include "57711_int_offsets.h"
41 #include "57712_int_offsets.h"
42 
43 /*
44  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
45  * explicitly here for older kernels that don't include this changeset.
46  */
47 #ifndef CTLTYPE_U64
48 #define CTLTYPE_U64      CTLTYPE_QUAD
49 #define sysctl_handle_64 sysctl_handle_quad
50 #endif
51 
52 /*
53  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
54  * here as zero(0) for older kernels that don't include this changeset
55  * thereby masking the functionality.
56  */
57 #ifndef CSUM_TCP_IPV6
58 #define CSUM_TCP_IPV6 0
59 #define CSUM_UDP_IPV6 0
60 #endif
61 
62 /*
63  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
64  * for older kernels that don't include this changeset.
65  */
66 #if __FreeBSD_version < 900035
67 #define pci_find_cap pci_find_extcap
68 #endif
69 
70 #define BXE_DEF_SB_ATT_IDX 0x0001
71 #define BXE_DEF_SB_IDX     0x0002
72 
73 /*
74  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
75  * function HW initialization.
76  */
77 #define FLR_WAIT_USEC     10000 /* 10 msecs */
78 #define FLR_WAIT_INTERVAL 50    /* usecs */
79 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
80 
81 struct pbf_pN_buf_regs {
82     int pN;
83     uint32_t init_crd;
84     uint32_t crd;
85     uint32_t crd_freed;
86 };
87 
88 struct pbf_pN_cmd_regs {
89     int pN;
90     uint32_t lines_occup;
91     uint32_t lines_freed;
92 };
93 
94 /*
95  * PCI Device ID Table used by bxe_probe().
96  */
97 #define BXE_DEVDESC_MAX 64
98 static struct bxe_device_type bxe_devs[] = {
99     {
100         BRCM_VENDORID,
101         CHIP_NUM_57710,
102         PCI_ANY_ID, PCI_ANY_ID,
103         "QLogic NetXtreme II BCM57710 10GbE"
104     },
105     {
106         BRCM_VENDORID,
107         CHIP_NUM_57711,
108         PCI_ANY_ID, PCI_ANY_ID,
109         "QLogic NetXtreme II BCM57711 10GbE"
110     },
111     {
112         BRCM_VENDORID,
113         CHIP_NUM_57711E,
114         PCI_ANY_ID, PCI_ANY_ID,
115         "QLogic NetXtreme II BCM57711E 10GbE"
116     },
117     {
118         BRCM_VENDORID,
119         CHIP_NUM_57712,
120         PCI_ANY_ID, PCI_ANY_ID,
121         "QLogic NetXtreme II BCM57712 10GbE"
122     },
123     {
124         BRCM_VENDORID,
125         CHIP_NUM_57712_MF,
126         PCI_ANY_ID, PCI_ANY_ID,
127         "QLogic NetXtreme II BCM57712 MF 10GbE"
128     },
129     {
130         BRCM_VENDORID,
131         CHIP_NUM_57800,
132         PCI_ANY_ID, PCI_ANY_ID,
133         "QLogic NetXtreme II BCM57800 10GbE"
134     },
135     {
136         BRCM_VENDORID,
137         CHIP_NUM_57800_MF,
138         PCI_ANY_ID, PCI_ANY_ID,
139         "QLogic NetXtreme II BCM57800 MF 10GbE"
140     },
141     {
142         BRCM_VENDORID,
143         CHIP_NUM_57810,
144         PCI_ANY_ID, PCI_ANY_ID,
145         "QLogic NetXtreme II BCM57810 10GbE"
146     },
147     {
148         BRCM_VENDORID,
149         CHIP_NUM_57810_MF,
150         PCI_ANY_ID, PCI_ANY_ID,
151         "QLogic NetXtreme II BCM57810 MF 10GbE"
152     },
153     {
154         BRCM_VENDORID,
155         CHIP_NUM_57811,
156         PCI_ANY_ID, PCI_ANY_ID,
157         "QLogic NetXtreme II BCM57811 10GbE"
158     },
159     {
160         BRCM_VENDORID,
161         CHIP_NUM_57811_MF,
162         PCI_ANY_ID, PCI_ANY_ID,
163         "QLogic NetXtreme II BCM57811 MF 10GbE"
164     },
165     {
166         BRCM_VENDORID,
167         CHIP_NUM_57840_4_10,
168         PCI_ANY_ID, PCI_ANY_ID,
169         "QLogic NetXtreme II BCM57840 4x10GbE"
170     },
171     {
172         QLOGIC_VENDORID,
173         CHIP_NUM_57840_4_10,
174         PCI_ANY_ID, PCI_ANY_ID,
175         "QLogic NetXtreme II BCM57840 4x10GbE"
176     },
177     {
178         BRCM_VENDORID,
179         CHIP_NUM_57840_2_20,
180         PCI_ANY_ID, PCI_ANY_ID,
181         "QLogic NetXtreme II BCM57840 2x20GbE"
182     },
183     {
184         BRCM_VENDORID,
185         CHIP_NUM_57840_MF,
186         PCI_ANY_ID, PCI_ANY_ID,
187         "QLogic NetXtreme II BCM57840 MF 10GbE"
188     },
189     {
190         0, 0, 0, 0, NULL
191     }
192 };
193 
194 MALLOC_DECLARE(M_BXE_ILT);
195 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
196 
197 /*
198  * FreeBSD device entry points.
199  */
200 static int bxe_probe(device_t);
201 static int bxe_attach(device_t);
202 static int bxe_detach(device_t);
203 static int bxe_shutdown(device_t);
204 
205 /*
206  * FreeBSD KLD module/device interface event handler method.
207  */
208 static device_method_t bxe_methods[] = {
209     /* Device interface (device_if.h) */
210     DEVMETHOD(device_probe,     bxe_probe),
211     DEVMETHOD(device_attach,    bxe_attach),
212     DEVMETHOD(device_detach,    bxe_detach),
213     DEVMETHOD(device_shutdown,  bxe_shutdown),
214     /* Bus interface (bus_if.h) */
215     DEVMETHOD(bus_print_child,  bus_generic_print_child),
216     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
217     KOBJMETHOD_END
218 };
219 
220 /*
221  * FreeBSD KLD Module data declaration
222  */
223 static driver_t bxe_driver = {
224     "bxe",                   /* module name */
225     bxe_methods,             /* event handler */
226     sizeof(struct bxe_softc) /* extra data */
227 };
228 
229 /*
230  * FreeBSD dev class is needed to manage dev instances and
231  * to associate with a bus type
232  */
233 static devclass_t bxe_devclass;
234 
235 MODULE_DEPEND(bxe, pci, 1, 1, 1);
236 MODULE_DEPEND(bxe, ether, 1, 1, 1);
237 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
238 
239 NETDUMP_DEFINE(bxe);
240 
241 /* resources needed for unloading a previously loaded device */
242 
243 #define BXE_PREV_WAIT_NEEDED 1
244 struct mtx bxe_prev_mtx;
245 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
246 struct bxe_prev_list_node {
247     LIST_ENTRY(bxe_prev_list_node) node;
248     uint8_t bus;
249     uint8_t slot;
250     uint8_t path;
251     uint8_t aer; /* XXX automatic error recovery */
252     uint8_t undi;
253 };
254 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
255 
256 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
257 
258 /* Tunable device values... */
259 
260 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
261 
262 /* Debug */
263 unsigned long bxe_debug = 0;
264 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
265              &bxe_debug, 0, "Debug logging mode");
266 
267 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
268 static int bxe_interrupt_mode = INTR_MODE_MSIX;
269 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
270            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
271 
272 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
273 static int bxe_queue_count = 4;
274 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
275            &bxe_queue_count, 0, "Multi-Queue queue count");
276 
277 /* max number of buffers per queue (default RX_BD_USABLE) */
278 static int bxe_max_rx_bufs = 0;
279 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
280            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
281 
282 /* Host interrupt coalescing RX tick timer (usecs) */
283 static int bxe_hc_rx_ticks = 25;
284 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
285            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
286 
287 /* Host interrupt coalescing TX tick timer (usecs) */
288 static int bxe_hc_tx_ticks = 50;
289 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
290            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
291 
292 /* Maximum number of Rx packets to process at a time */
293 static int bxe_rx_budget = 0xffffffff;
294 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
295            &bxe_rx_budget, 0, "Rx processing budget");
296 
297 /* Maximum LRO aggregation size */
298 static int bxe_max_aggregation_size = 0;
299 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
300            &bxe_max_aggregation_size, 0, "max aggregation size");
301 
302 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
303 static int bxe_mrrs = -1;
304 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
305            &bxe_mrrs, 0, "PCIe maximum read request size");
306 
307 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
308 static int bxe_autogreeen = 0;
309 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
310            &bxe_autogreeen, 0, "AutoGrEEEn support");
311 
312 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
313 static int bxe_udp_rss = 0;
314 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
315            &bxe_udp_rss, 0, "UDP RSS support");
316 
317 
318 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
319 
320 #define STATS_OFFSET32(stat_name)                   \
321     (offsetof(struct bxe_eth_stats, stat_name) / 4)
322 
323 #define Q_STATS_OFFSET32(stat_name)                   \
324     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
325 
326 static const struct {
327     uint32_t offset;
328     uint32_t size;
329     uint32_t flags;
330 #define STATS_FLAGS_PORT  1
331 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
332 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
333     char string[STAT_NAME_LEN];
334 } bxe_eth_stats_arr[] = {
335     { STATS_OFFSET32(total_bytes_received_hi),
336                 8, STATS_FLAGS_BOTH, "rx_bytes" },
337     { STATS_OFFSET32(error_bytes_received_hi),
338                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
339     { STATS_OFFSET32(total_unicast_packets_received_hi),
340                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
341     { STATS_OFFSET32(total_multicast_packets_received_hi),
342                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
343     { STATS_OFFSET32(total_broadcast_packets_received_hi),
344                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
345     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
346                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
347     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
348                 8, STATS_FLAGS_PORT, "rx_align_errors" },
349     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
350                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
351     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
352                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
353     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
354                 8, STATS_FLAGS_PORT, "rx_fragments" },
355     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
356                 8, STATS_FLAGS_PORT, "rx_jabbers" },
357     { STATS_OFFSET32(no_buff_discard_hi),
358                 8, STATS_FLAGS_BOTH, "rx_discards" },
359     { STATS_OFFSET32(mac_filter_discard),
360                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
361     { STATS_OFFSET32(mf_tag_discard),
362                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
363     { STATS_OFFSET32(pfc_frames_received_hi),
364                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
365     { STATS_OFFSET32(pfc_frames_sent_hi),
366                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
367     { STATS_OFFSET32(brb_drop_hi),
368                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
369     { STATS_OFFSET32(brb_truncate_hi),
370                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
371     { STATS_OFFSET32(pause_frames_received_hi),
372                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
373     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
374                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
375     { STATS_OFFSET32(nig_timer_max),
376                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
377     { STATS_OFFSET32(total_bytes_transmitted_hi),
378                 8, STATS_FLAGS_BOTH, "tx_bytes" },
379     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
380                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
381     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
382                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
383     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
384                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
385     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
386                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
387     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
388                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
389     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
390                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
391     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
392                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
393     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
394                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
395     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
396                 8, STATS_FLAGS_PORT, "tx_deferred" },
397     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
398                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
399     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
400                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
401     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
402                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
403     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
404                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
405     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
406                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
407     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
408                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
409     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
410                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
411     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
412                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
413     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
414                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
415     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
416                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
417     { STATS_OFFSET32(pause_frames_sent_hi),
418                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
419     { STATS_OFFSET32(total_tpa_aggregations_hi),
420                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
421     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
422                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
423     { STATS_OFFSET32(total_tpa_bytes_hi),
424                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
425     { STATS_OFFSET32(eee_tx_lpi),
426                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
427     { STATS_OFFSET32(rx_calls),
428                 4, STATS_FLAGS_FUNC, "rx_calls"},
429     { STATS_OFFSET32(rx_pkts),
430                 4, STATS_FLAGS_FUNC, "rx_pkts"},
431     { STATS_OFFSET32(rx_tpa_pkts),
432                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
433     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
434                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
435     { STATS_OFFSET32(rx_bxe_service_rxsgl),
436                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
437     { STATS_OFFSET32(rx_jumbo_sge_pkts),
438                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
439     { STATS_OFFSET32(rx_soft_errors),
440                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
441     { STATS_OFFSET32(rx_hw_csum_errors),
442                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
443     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
444                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
445     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
446                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
447     { STATS_OFFSET32(rx_budget_reached),
448                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
449     { STATS_OFFSET32(tx_pkts),
450                 4, STATS_FLAGS_FUNC, "tx_pkts"},
451     { STATS_OFFSET32(tx_soft_errors),
452                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
453     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
454                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
455     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
456                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
457     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
458                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
459     { STATS_OFFSET32(tx_ofld_frames_lso),
460                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
461     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
462                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
463     { STATS_OFFSET32(tx_encap_failures),
464                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
465     { STATS_OFFSET32(tx_hw_queue_full),
466                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
467     { STATS_OFFSET32(tx_hw_max_queue_depth),
468                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
469     { STATS_OFFSET32(tx_dma_mapping_failure),
470                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
471     { STATS_OFFSET32(tx_max_drbr_queue_depth),
472                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
473     { STATS_OFFSET32(tx_window_violation_std),
474                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
475     { STATS_OFFSET32(tx_window_violation_tso),
476                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
477     { STATS_OFFSET32(tx_chain_lost_mbuf),
478                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
479     { STATS_OFFSET32(tx_frames_deferred),
480                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
481     { STATS_OFFSET32(tx_queue_xoff),
482                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
483     { STATS_OFFSET32(mbuf_defrag_attempts),
484                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
485     { STATS_OFFSET32(mbuf_defrag_failures),
486                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
487     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
488                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
489     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
490                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
491     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
492                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
493     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
494                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
495     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
496                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
497     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
498                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
499     { STATS_OFFSET32(mbuf_alloc_tx),
500                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
501     { STATS_OFFSET32(mbuf_alloc_rx),
502                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
503     { STATS_OFFSET32(mbuf_alloc_sge),
504                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
505     { STATS_OFFSET32(mbuf_alloc_tpa),
506                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
507     { STATS_OFFSET32(tx_queue_full_return),
508                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
509     { STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
510                 4, STATS_FLAGS_FUNC, "bxe_tx_mq_sc_state_failures"},
511     { STATS_OFFSET32(tx_request_link_down_failures),
512                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
513     { STATS_OFFSET32(bd_avail_too_less_failures),
514                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
515     { STATS_OFFSET32(tx_mq_not_empty),
516                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"},
517     { STATS_OFFSET32(nsegs_path1_errors),
518                 4, STATS_FLAGS_FUNC, "nsegs_path1_errors"},
519     { STATS_OFFSET32(nsegs_path2_errors),
520                 4, STATS_FLAGS_FUNC, "nsegs_path2_errors"}
521 
522 
523 };
524 
525 static const struct {
526     uint32_t offset;
527     uint32_t size;
528     char string[STAT_NAME_LEN];
529 } bxe_eth_q_stats_arr[] = {
530     { Q_STATS_OFFSET32(total_bytes_received_hi),
531                 8, "rx_bytes" },
532     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
533                 8, "rx_ucast_packets" },
534     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
535                 8, "rx_mcast_packets" },
536     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
537                 8, "rx_bcast_packets" },
538     { Q_STATS_OFFSET32(no_buff_discard_hi),
539                 8, "rx_discards" },
540     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
541                 8, "tx_bytes" },
542     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
543                 8, "tx_ucast_packets" },
544     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
545                 8, "tx_mcast_packets" },
546     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
547                 8, "tx_bcast_packets" },
548     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
549                 8, "tpa_aggregations" },
550     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
551                 8, "tpa_aggregated_frames"},
552     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
553                 8, "tpa_bytes"},
554     { Q_STATS_OFFSET32(rx_calls),
555                 4, "rx_calls"},
556     { Q_STATS_OFFSET32(rx_pkts),
557                 4, "rx_pkts"},
558     { Q_STATS_OFFSET32(rx_tpa_pkts),
559                 4, "rx_tpa_pkts"},
560     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
561                 4, "rx_erroneous_jumbo_sge_pkts"},
562     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
563                 4, "rx_bxe_service_rxsgl"},
564     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
565                 4, "rx_jumbo_sge_pkts"},
566     { Q_STATS_OFFSET32(rx_soft_errors),
567                 4, "rx_soft_errors"},
568     { Q_STATS_OFFSET32(rx_hw_csum_errors),
569                 4, "rx_hw_csum_errors"},
570     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
571                 4, "rx_ofld_frames_csum_ip"},
572     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
573                 4, "rx_ofld_frames_csum_tcp_udp"},
574     { Q_STATS_OFFSET32(rx_budget_reached),
575                 4, "rx_budget_reached"},
576     { Q_STATS_OFFSET32(tx_pkts),
577                 4, "tx_pkts"},
578     { Q_STATS_OFFSET32(tx_soft_errors),
579                 4, "tx_soft_errors"},
580     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
581                 4, "tx_ofld_frames_csum_ip"},
582     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
583                 4, "tx_ofld_frames_csum_tcp"},
584     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
585                 4, "tx_ofld_frames_csum_udp"},
586     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
587                 4, "tx_ofld_frames_lso"},
588     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
589                 4, "tx_ofld_frames_lso_hdr_splits"},
590     { Q_STATS_OFFSET32(tx_encap_failures),
591                 4, "tx_encap_failures"},
592     { Q_STATS_OFFSET32(tx_hw_queue_full),
593                 4, "tx_hw_queue_full"},
594     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
595                 4, "tx_hw_max_queue_depth"},
596     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
597                 4, "tx_dma_mapping_failure"},
598     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
599                 4, "tx_max_drbr_queue_depth"},
600     { Q_STATS_OFFSET32(tx_window_violation_std),
601                 4, "tx_window_violation_std"},
602     { Q_STATS_OFFSET32(tx_window_violation_tso),
603                 4, "tx_window_violation_tso"},
604     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
605                 4, "tx_chain_lost_mbuf"},
606     { Q_STATS_OFFSET32(tx_frames_deferred),
607                 4, "tx_frames_deferred"},
608     { Q_STATS_OFFSET32(tx_queue_xoff),
609                 4, "tx_queue_xoff"},
610     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
611                 4, "mbuf_defrag_attempts"},
612     { Q_STATS_OFFSET32(mbuf_defrag_failures),
613                 4, "mbuf_defrag_failures"},
614     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
615                 4, "mbuf_rx_bd_alloc_failed"},
616     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
617                 4, "mbuf_rx_bd_mapping_failed"},
618     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
619                 4, "mbuf_rx_tpa_alloc_failed"},
620     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
621                 4, "mbuf_rx_tpa_mapping_failed"},
622     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
623                 4, "mbuf_rx_sge_alloc_failed"},
624     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
625                 4, "mbuf_rx_sge_mapping_failed"},
626     { Q_STATS_OFFSET32(mbuf_alloc_tx),
627                 4, "mbuf_alloc_tx"},
628     { Q_STATS_OFFSET32(mbuf_alloc_rx),
629                 4, "mbuf_alloc_rx"},
630     { Q_STATS_OFFSET32(mbuf_alloc_sge),
631                 4, "mbuf_alloc_sge"},
632     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
633                 4, "mbuf_alloc_tpa"},
634     { Q_STATS_OFFSET32(tx_queue_full_return),
635                 4, "tx_queue_full_return"},
636     { Q_STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
637                 4, "bxe_tx_mq_sc_state_failures"},
638     { Q_STATS_OFFSET32(tx_request_link_down_failures),
639                 4, "tx_request_link_down_failures"},
640     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
641                 4, "bd_avail_too_less_failures"},
642     { Q_STATS_OFFSET32(tx_mq_not_empty),
643                 4, "tx_mq_not_empty"},
644     { Q_STATS_OFFSET32(nsegs_path1_errors),
645                 4, "nsegs_path1_errors"},
646     { Q_STATS_OFFSET32(nsegs_path2_errors),
647                 4, "nsegs_path2_errors"}
648 
649 
650 };
651 
652 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
653 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
654 
655 
656 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
657                                  uint8_t          read_cfg,
658                                  uint8_t          cmng_type);
659 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
660 static void    storm_memset_cmng(struct bxe_softc *sc,
661                                  struct cmng_init *cmng,
662                                  uint8_t          port);
663 static void    bxe_set_reset_global(struct bxe_softc *sc);
664 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
665 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
666                                  int              engine);
667 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
668 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
669                                    uint8_t          *global,
670                                    uint8_t          print);
671 static void    bxe_int_disable(struct bxe_softc *sc);
672 static int     bxe_release_leader_lock(struct bxe_softc *sc);
673 static void    bxe_pf_disable(struct bxe_softc *sc);
674 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
675 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
676                                       struct bxe_fastpath *fp,
677                                       uint16_t            rx_bd_prod,
678                                       uint16_t            rx_cq_prod,
679                                       uint16_t            rx_sge_prod);
680 static void    bxe_link_report_locked(struct bxe_softc *sc);
681 static void    bxe_link_report(struct bxe_softc *sc);
682 static void    bxe_link_status_update(struct bxe_softc *sc);
683 static void    bxe_periodic_callout_func(void *xsc);
684 static void    bxe_periodic_start(struct bxe_softc *sc);
685 static void    bxe_periodic_stop(struct bxe_softc *sc);
686 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
687                                     uint16_t prev_index,
688                                     uint16_t index);
689 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
690                                      int                 queue);
691 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
692                                      uint16_t            index);
693 static uint8_t bxe_txeof(struct bxe_softc *sc,
694                          struct bxe_fastpath *fp);
695 static void    bxe_task_fp(struct bxe_fastpath *fp);
696 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
697                                      struct mbuf      *m,
698                                      uint8_t          contents);
699 static int     bxe_alloc_mem(struct bxe_softc *sc);
700 static void    bxe_free_mem(struct bxe_softc *sc);
701 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
702 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
703 static int     bxe_interrupt_attach(struct bxe_softc *sc);
704 static void    bxe_interrupt_detach(struct bxe_softc *sc);
705 static void    bxe_set_rx_mode(struct bxe_softc *sc);
706 static int     bxe_init_locked(struct bxe_softc *sc);
707 static int     bxe_stop_locked(struct bxe_softc *sc);
708 static __noinline int bxe_nic_load(struct bxe_softc *sc,
709                                    int              load_mode);
710 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
711                                      uint32_t         unload_mode,
712                                      uint8_t          keep_link);
713 
714 static void bxe_handle_sp_tq(void *context, int pending);
715 static void bxe_handle_fp_tq(void *context, int pending);
716 
717 static int bxe_add_cdev(struct bxe_softc *sc);
718 static void bxe_del_cdev(struct bxe_softc *sc);
719 int bxe_grc_dump(struct bxe_softc *sc);
720 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
721 static void bxe_free_buf_rings(struct bxe_softc *sc);
722 
723 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
724 uint32_t
725 calc_crc32(uint8_t  *crc32_packet,
726            uint32_t crc32_length,
727            uint32_t crc32_seed,
728            uint8_t  complement)
729 {
730    uint32_t byte         = 0;
731    uint32_t bit          = 0;
732    uint8_t  msb          = 0;
733    uint32_t temp         = 0;
734    uint32_t shft         = 0;
735    uint8_t  current_byte = 0;
736    uint32_t crc32_result = crc32_seed;
737    const uint32_t CRC32_POLY = 0x1edc6f41;
738 
739    if ((crc32_packet == NULL) ||
740        (crc32_length == 0) ||
741        ((crc32_length % 8) != 0))
742     {
743         return (crc32_result);
744     }
745 
746     for (byte = 0; byte < crc32_length; byte = byte + 1)
747     {
748         current_byte = crc32_packet[byte];
749         for (bit = 0; bit < 8; bit = bit + 1)
750         {
751             /* msb = crc32_result[31]; */
752             msb = (uint8_t)(crc32_result >> 31);
753 
754             crc32_result = crc32_result << 1;
755 
756             /* it (msb != current_byte[bit]) */
757             if (msb != (0x1 & (current_byte >> bit)))
758             {
759                 crc32_result = crc32_result ^ CRC32_POLY;
760                 /* crc32_result[0] = 1 */
761                 crc32_result |= 1;
762             }
763         }
764     }
765 
766     /* Last step is to:
767      * 1. "mirror" every bit
768      * 2. swap the 4 bytes
769      * 3. complement each bit
770      */
771 
772     /* Mirror */
773     temp = crc32_result;
774     shft = sizeof(crc32_result) * 8 - 1;
775 
776     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
777     {
778         temp <<= 1;
779         temp |= crc32_result & 1;
780         shft-- ;
781     }
782 
783     /* temp[31-bit] = crc32_result[bit] */
784     temp <<= shft;
785 
786     /* Swap */
787     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
788     {
789         uint32_t t0, t1, t2, t3;
790         t0 = (0x000000ff & (temp >> 24));
791         t1 = (0x0000ff00 & (temp >> 8));
792         t2 = (0x00ff0000 & (temp << 8));
793         t3 = (0xff000000 & (temp << 24));
794         crc32_result = t0 | t1 | t2 | t3;
795     }
796 
797     /* Complement */
798     if (complement)
799     {
800         crc32_result = ~crc32_result;
801     }
802 
803     return (crc32_result);
804 }
805 
806 int
807 bxe_test_bit(int                    nr,
808              volatile unsigned long *addr)
809 {
810     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
811 }
812 
813 void
814 bxe_set_bit(unsigned int           nr,
815             volatile unsigned long *addr)
816 {
817     atomic_set_acq_long(addr, (1 << nr));
818 }
819 
820 void
821 bxe_clear_bit(int                    nr,
822               volatile unsigned long *addr)
823 {
824     atomic_clear_acq_long(addr, (1 << nr));
825 }
826 
827 int
828 bxe_test_and_set_bit(int                    nr,
829                        volatile unsigned long *addr)
830 {
831     unsigned long x;
832     nr = (1 << nr);
833     do {
834         x = *addr;
835     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
836     // if (x & nr) bit_was_set; else bit_was_not_set;
837     return (x & nr);
838 }
839 
840 int
841 bxe_test_and_clear_bit(int                    nr,
842                        volatile unsigned long *addr)
843 {
844     unsigned long x;
845     nr = (1 << nr);
846     do {
847         x = *addr;
848     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
849     // if (x & nr) bit_was_set; else bit_was_not_set;
850     return (x & nr);
851 }
852 
853 int
854 bxe_cmpxchg(volatile int *addr,
855             int          old,
856             int          new)
857 {
858     int x;
859     do {
860         x = *addr;
861     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
862     return (x);
863 }
864 
865 /*
866  * Get DMA memory from the OS.
867  *
868  * Validates that the OS has provided DMA buffers in response to a
869  * bus_dmamap_load call and saves the physical address of those buffers.
870  * When the callback is used the OS will return 0 for the mapping function
871  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
872  * failures back to the caller.
873  *
874  * Returns:
875  *   Nothing.
876  */
877 static void
878 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
879 {
880     struct bxe_dma *dma = arg;
881 
882     if (error) {
883         dma->paddr = 0;
884         dma->nseg  = 0;
885         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
886     } else {
887         dma->paddr = segs->ds_addr;
888         dma->nseg  = nseg;
889     }
890 }
891 
892 /*
893  * Allocate a block of memory and map it for DMA. No partial completions
894  * allowed and release any resources acquired if we can't acquire all
895  * resources.
896  *
897  * Returns:
898  *   0 = Success, !0 = Failure
899  */
900 int
901 bxe_dma_alloc(struct bxe_softc *sc,
902               bus_size_t       size,
903               struct bxe_dma   *dma,
904               const char       *msg)
905 {
906     int rc;
907 
908     if (dma->size > 0) {
909         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
910               (unsigned long)dma->size);
911         return (1);
912     }
913 
914     memset(dma, 0, sizeof(*dma)); /* sanity */
915     dma->sc   = sc;
916     dma->size = size;
917     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
918 
919     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
920                             BCM_PAGE_SIZE,      /* alignment */
921                             0,                  /* boundary limit */
922                             BUS_SPACE_MAXADDR,  /* restricted low */
923                             BUS_SPACE_MAXADDR,  /* restricted hi */
924                             NULL,               /* addr filter() */
925                             NULL,               /* addr filter() arg */
926                             size,               /* max map size */
927                             1,                  /* num discontinuous */
928                             size,               /* max seg size */
929                             BUS_DMA_ALLOCNOW,   /* flags */
930                             NULL,               /* lock() */
931                             NULL,               /* lock() arg */
932                             &dma->tag);         /* returned dma tag */
933     if (rc != 0) {
934         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
935         memset(dma, 0, sizeof(*dma));
936         return (1);
937     }
938 
939     rc = bus_dmamem_alloc(dma->tag,
940                           (void **)&dma->vaddr,
941                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
942                           &dma->map);
943     if (rc != 0) {
944         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
945         bus_dma_tag_destroy(dma->tag);
946         memset(dma, 0, sizeof(*dma));
947         return (1);
948     }
949 
950     rc = bus_dmamap_load(dma->tag,
951                          dma->map,
952                          dma->vaddr,
953                          size,
954                          bxe_dma_map_addr, /* BLOGD in here */
955                          dma,
956                          BUS_DMA_NOWAIT);
957     if (rc != 0) {
958         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
959         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
960         bus_dma_tag_destroy(dma->tag);
961         memset(dma, 0, sizeof(*dma));
962         return (1);
963     }
964 
965     return (0);
966 }
967 
968 void
969 bxe_dma_free(struct bxe_softc *sc,
970              struct bxe_dma   *dma)
971 {
972     if (dma->size > 0) {
973         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
974 
975         bus_dmamap_sync(dma->tag, dma->map,
976                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
977         bus_dmamap_unload(dma->tag, dma->map);
978         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
979         bus_dma_tag_destroy(dma->tag);
980     }
981 
982     memset(dma, 0, sizeof(*dma));
983 }
984 
985 /*
986  * These indirect read and write routines are only during init.
987  * The locking is handled by the MCP.
988  */
989 
990 void
991 bxe_reg_wr_ind(struct bxe_softc *sc,
992                uint32_t         addr,
993                uint32_t         val)
994 {
995     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
996     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
997     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
998 }
999 
1000 uint32_t
1001 bxe_reg_rd_ind(struct bxe_softc *sc,
1002                uint32_t         addr)
1003 {
1004     uint32_t val;
1005 
1006     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1007     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1008     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1009 
1010     return (val);
1011 }
1012 
1013 static int
1014 bxe_acquire_hw_lock(struct bxe_softc *sc,
1015                     uint32_t         resource)
1016 {
1017     uint32_t lock_status;
1018     uint32_t resource_bit = (1 << resource);
1019     int func = SC_FUNC(sc);
1020     uint32_t hw_lock_control_reg;
1021     int cnt;
1022 
1023     /* validate the resource is within range */
1024     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1025         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1026             " resource_bit 0x%x\n", resource, resource_bit);
1027         return (-1);
1028     }
1029 
1030     if (func <= 5) {
1031         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1032     } else {
1033         hw_lock_control_reg =
1034                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1035     }
1036 
1037     /* validate the resource is not already taken */
1038     lock_status = REG_RD(sc, hw_lock_control_reg);
1039     if (lock_status & resource_bit) {
1040         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1041               resource, lock_status, resource_bit);
1042         return (-1);
1043     }
1044 
1045     /* try every 5ms for 5 seconds */
1046     for (cnt = 0; cnt < 1000; cnt++) {
1047         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1048         lock_status = REG_RD(sc, hw_lock_control_reg);
1049         if (lock_status & resource_bit) {
1050             return (0);
1051         }
1052         DELAY(5000);
1053     }
1054 
1055     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1056         resource, resource_bit);
1057     return (-1);
1058 }
1059 
1060 static int
1061 bxe_release_hw_lock(struct bxe_softc *sc,
1062                     uint32_t         resource)
1063 {
1064     uint32_t lock_status;
1065     uint32_t resource_bit = (1 << resource);
1066     int func = SC_FUNC(sc);
1067     uint32_t hw_lock_control_reg;
1068 
1069     /* validate the resource is within range */
1070     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1071         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1072             " resource_bit 0x%x\n", resource, resource_bit);
1073         return (-1);
1074     }
1075 
1076     if (func <= 5) {
1077         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1078     } else {
1079         hw_lock_control_reg =
1080                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1081     }
1082 
1083     /* validate the resource is currently taken */
1084     lock_status = REG_RD(sc, hw_lock_control_reg);
1085     if (!(lock_status & resource_bit)) {
1086         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1087               resource, lock_status, resource_bit);
1088         return (-1);
1089     }
1090 
1091     REG_WR(sc, hw_lock_control_reg, resource_bit);
1092     return (0);
1093 }
1094 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1095 {
1096 	BXE_PHY_LOCK(sc);
1097 	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1098 }
1099 
1100 static void bxe_release_phy_lock(struct bxe_softc *sc)
1101 {
1102 	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1103 	BXE_PHY_UNLOCK(sc);
1104 }
1105 /*
1106  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1107  * had we done things the other way around, if two pfs from the same port
1108  * would attempt to access nvram at the same time, we could run into a
1109  * scenario such as:
1110  * pf A takes the port lock.
1111  * pf B succeeds in taking the same lock since they are from the same port.
1112  * pf A takes the per pf misc lock. Performs eeprom access.
1113  * pf A finishes. Unlocks the per pf misc lock.
1114  * Pf B takes the lock and proceeds to perform it's own access.
1115  * pf A unlocks the per port lock, while pf B is still working (!).
1116  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1117  * access corrupted by pf B).*
1118  */
1119 static int
1120 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1121 {
1122     int port = SC_PORT(sc);
1123     int count, i;
1124     uint32_t val = 0;
1125 
1126     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1127     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1128 
1129     /* adjust timeout for emulation/FPGA */
1130     count = NVRAM_TIMEOUT_COUNT;
1131     if (CHIP_REV_IS_SLOW(sc)) {
1132         count *= 100;
1133     }
1134 
1135     /* request access to nvram interface */
1136     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1137            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1138 
1139     for (i = 0; i < count*10; i++) {
1140         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1141         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1142             break;
1143         }
1144 
1145         DELAY(5);
1146     }
1147 
1148     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1149         BLOGE(sc, "Cannot get access to nvram interface "
1150             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1151             port, val);
1152         return (-1);
1153     }
1154 
1155     return (0);
1156 }
1157 
1158 static int
1159 bxe_release_nvram_lock(struct bxe_softc *sc)
1160 {
1161     int port = SC_PORT(sc);
1162     int count, i;
1163     uint32_t val = 0;
1164 
1165     /* adjust timeout for emulation/FPGA */
1166     count = NVRAM_TIMEOUT_COUNT;
1167     if (CHIP_REV_IS_SLOW(sc)) {
1168         count *= 100;
1169     }
1170 
1171     /* relinquish nvram interface */
1172     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1173            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1174 
1175     for (i = 0; i < count*10; i++) {
1176         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1177         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1178             break;
1179         }
1180 
1181         DELAY(5);
1182     }
1183 
1184     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1185         BLOGE(sc, "Cannot free access to nvram interface "
1186             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1187             port, val);
1188         return (-1);
1189     }
1190 
1191     /* release HW lock: protect against other PFs in PF Direct Assignment */
1192     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1193 
1194     return (0);
1195 }
1196 
1197 static void
1198 bxe_enable_nvram_access(struct bxe_softc *sc)
1199 {
1200     uint32_t val;
1201 
1202     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1203 
1204     /* enable both bits, even on read */
1205     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1206            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1207 }
1208 
1209 static void
1210 bxe_disable_nvram_access(struct bxe_softc *sc)
1211 {
1212     uint32_t val;
1213 
1214     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1215 
1216     /* disable both bits, even after read */
1217     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1218            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1219                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1220 }
1221 
1222 static int
1223 bxe_nvram_read_dword(struct bxe_softc *sc,
1224                      uint32_t         offset,
1225                      uint32_t         *ret_val,
1226                      uint32_t         cmd_flags)
1227 {
1228     int count, i, rc;
1229     uint32_t val;
1230 
1231     /* build the command word */
1232     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1233 
1234     /* need to clear DONE bit separately */
1235     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1236 
1237     /* address of the NVRAM to read from */
1238     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1239            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1240 
1241     /* issue a read command */
1242     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1243 
1244     /* adjust timeout for emulation/FPGA */
1245     count = NVRAM_TIMEOUT_COUNT;
1246     if (CHIP_REV_IS_SLOW(sc)) {
1247         count *= 100;
1248     }
1249 
1250     /* wait for completion */
1251     *ret_val = 0;
1252     rc = -1;
1253     for (i = 0; i < count; i++) {
1254         DELAY(5);
1255         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1256 
1257         if (val & MCPR_NVM_COMMAND_DONE) {
1258             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1259             /* we read nvram data in cpu order
1260              * but ethtool sees it as an array of bytes
1261              * converting to big-endian will do the work
1262              */
1263             *ret_val = htobe32(val);
1264             rc = 0;
1265             break;
1266         }
1267     }
1268 
1269     if (rc == -1) {
1270         BLOGE(sc, "nvram read timeout expired "
1271             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1272             offset, cmd_flags, val);
1273     }
1274 
1275     return (rc);
1276 }
1277 
1278 static int
1279 bxe_nvram_read(struct bxe_softc *sc,
1280                uint32_t         offset,
1281                uint8_t          *ret_buf,
1282                int              buf_size)
1283 {
1284     uint32_t cmd_flags;
1285     uint32_t val;
1286     int rc;
1287 
1288     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1289         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1290               offset, buf_size);
1291         return (-1);
1292     }
1293 
1294     if ((offset + buf_size) > sc->devinfo.flash_size) {
1295         BLOGE(sc, "Invalid parameter, "
1296                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1297               offset, buf_size, sc->devinfo.flash_size);
1298         return (-1);
1299     }
1300 
1301     /* request access to nvram interface */
1302     rc = bxe_acquire_nvram_lock(sc);
1303     if (rc) {
1304         return (rc);
1305     }
1306 
1307     /* enable access to nvram interface */
1308     bxe_enable_nvram_access(sc);
1309 
1310     /* read the first word(s) */
1311     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1312     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1313         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1314         memcpy(ret_buf, &val, 4);
1315 
1316         /* advance to the next dword */
1317         offset += sizeof(uint32_t);
1318         ret_buf += sizeof(uint32_t);
1319         buf_size -= sizeof(uint32_t);
1320         cmd_flags = 0;
1321     }
1322 
1323     if (rc == 0) {
1324         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1325         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1326         memcpy(ret_buf, &val, 4);
1327     }
1328 
1329     /* disable access to nvram interface */
1330     bxe_disable_nvram_access(sc);
1331     bxe_release_nvram_lock(sc);
1332 
1333     return (rc);
1334 }
1335 
1336 static int
1337 bxe_nvram_write_dword(struct bxe_softc *sc,
1338                       uint32_t         offset,
1339                       uint32_t         val,
1340                       uint32_t         cmd_flags)
1341 {
1342     int count, i, rc;
1343 
1344     /* build the command word */
1345     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1346 
1347     /* need to clear DONE bit separately */
1348     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1349 
1350     /* write the data */
1351     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1352 
1353     /* address of the NVRAM to write to */
1354     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1355            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1356 
1357     /* issue the write command */
1358     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1359 
1360     /* adjust timeout for emulation/FPGA */
1361     count = NVRAM_TIMEOUT_COUNT;
1362     if (CHIP_REV_IS_SLOW(sc)) {
1363         count *= 100;
1364     }
1365 
1366     /* wait for completion */
1367     rc = -1;
1368     for (i = 0; i < count; i++) {
1369         DELAY(5);
1370         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1371         if (val & MCPR_NVM_COMMAND_DONE) {
1372             rc = 0;
1373             break;
1374         }
1375     }
1376 
1377     if (rc == -1) {
1378         BLOGE(sc, "nvram write timeout expired "
1379             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1380             offset, cmd_flags, val);
1381     }
1382 
1383     return (rc);
1384 }
1385 
1386 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1387 
1388 static int
1389 bxe_nvram_write1(struct bxe_softc *sc,
1390                  uint32_t         offset,
1391                  uint8_t          *data_buf,
1392                  int              buf_size)
1393 {
1394     uint32_t cmd_flags;
1395     uint32_t align_offset;
1396     uint32_t val;
1397     int rc;
1398 
1399     if ((offset + buf_size) > sc->devinfo.flash_size) {
1400         BLOGE(sc, "Invalid parameter, "
1401                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1402               offset, buf_size, sc->devinfo.flash_size);
1403         return (-1);
1404     }
1405 
1406     /* request access to nvram interface */
1407     rc = bxe_acquire_nvram_lock(sc);
1408     if (rc) {
1409         return (rc);
1410     }
1411 
1412     /* enable access to nvram interface */
1413     bxe_enable_nvram_access(sc);
1414 
1415     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1416     align_offset = (offset & ~0x03);
1417     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1418 
1419     if (rc == 0) {
1420         val &= ~(0xff << BYTE_OFFSET(offset));
1421         val |= (*data_buf << BYTE_OFFSET(offset));
1422 
1423         /* nvram data is returned as an array of bytes
1424          * convert it back to cpu order
1425          */
1426         val = be32toh(val);
1427 
1428         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1429     }
1430 
1431     /* disable access to nvram interface */
1432     bxe_disable_nvram_access(sc);
1433     bxe_release_nvram_lock(sc);
1434 
1435     return (rc);
1436 }
1437 
1438 static int
1439 bxe_nvram_write(struct bxe_softc *sc,
1440                 uint32_t         offset,
1441                 uint8_t          *data_buf,
1442                 int              buf_size)
1443 {
1444     uint32_t cmd_flags;
1445     uint32_t val;
1446     uint32_t written_so_far;
1447     int rc;
1448 
1449     if (buf_size == 1) {
1450         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1451     }
1452 
1453     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1454         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1455               offset, buf_size);
1456         return (-1);
1457     }
1458 
1459     if (buf_size == 0) {
1460         return (0); /* nothing to do */
1461     }
1462 
1463     if ((offset + buf_size) > sc->devinfo.flash_size) {
1464         BLOGE(sc, "Invalid parameter, "
1465                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1466               offset, buf_size, sc->devinfo.flash_size);
1467         return (-1);
1468     }
1469 
1470     /* request access to nvram interface */
1471     rc = bxe_acquire_nvram_lock(sc);
1472     if (rc) {
1473         return (rc);
1474     }
1475 
1476     /* enable access to nvram interface */
1477     bxe_enable_nvram_access(sc);
1478 
1479     written_so_far = 0;
1480     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1481     while ((written_so_far < buf_size) && (rc == 0)) {
1482         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1483             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1484         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1485             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1486         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1487             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1488         }
1489 
1490         memcpy(&val, data_buf, 4);
1491 
1492         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1493 
1494         /* advance to the next dword */
1495         offset += sizeof(uint32_t);
1496         data_buf += sizeof(uint32_t);
1497         written_so_far += sizeof(uint32_t);
1498         cmd_flags = 0;
1499     }
1500 
1501     /* disable access to nvram interface */
1502     bxe_disable_nvram_access(sc);
1503     bxe_release_nvram_lock(sc);
1504 
1505     return (rc);
1506 }
1507 
1508 /* copy command into DMAE command memory and set DMAE command Go */
1509 void
1510 bxe_post_dmae(struct bxe_softc    *sc,
1511               struct dmae_cmd *dmae,
1512               int                 idx)
1513 {
1514     uint32_t cmd_offset;
1515     int i;
1516 
1517     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1518     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1519         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1520     }
1521 
1522     REG_WR(sc, dmae_reg_go_c[idx], 1);
1523 }
1524 
1525 uint32_t
1526 bxe_dmae_opcode_add_comp(uint32_t opcode,
1527                          uint8_t  comp_type)
1528 {
1529     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1530                       DMAE_CMD_C_TYPE_ENABLE));
1531 }
1532 
1533 uint32_t
1534 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1535 {
1536     return (opcode & ~DMAE_CMD_SRC_RESET);
1537 }
1538 
1539 uint32_t
1540 bxe_dmae_opcode(struct bxe_softc *sc,
1541                 uint8_t          src_type,
1542                 uint8_t          dst_type,
1543                 uint8_t          with_comp,
1544                 uint8_t          comp_type)
1545 {
1546     uint32_t opcode = 0;
1547 
1548     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1549                (dst_type << DMAE_CMD_DST_SHIFT));
1550 
1551     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1552 
1553     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1554 
1555     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1556                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1557 
1558     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1559 
1560 #ifdef __BIG_ENDIAN
1561     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1562 #else
1563     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1564 #endif
1565 
1566     if (with_comp) {
1567         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1568     }
1569 
1570     return (opcode);
1571 }
1572 
1573 static void
1574 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1575                         struct dmae_cmd *dmae,
1576                         uint8_t             src_type,
1577                         uint8_t             dst_type)
1578 {
1579     memset(dmae, 0, sizeof(struct dmae_cmd));
1580 
1581     /* set the opcode */
1582     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1583                                    TRUE, DMAE_COMP_PCI);
1584 
1585     /* fill in the completion parameters */
1586     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1587     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1588     dmae->comp_val     = DMAE_COMP_VAL;
1589 }
1590 
1591 /* issue a DMAE command over the init channel and wait for completion */
1592 static int
1593 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1594                          struct dmae_cmd *dmae)
1595 {
1596     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1597     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1598 
1599     BXE_DMAE_LOCK(sc);
1600 
1601     /* reset completion */
1602     *wb_comp = 0;
1603 
1604     /* post the command on the channel used for initializations */
1605     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1606 
1607     /* wait for completion */
1608     DELAY(5);
1609 
1610     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1611         if (!timeout ||
1612             (sc->recovery_state != BXE_RECOVERY_DONE &&
1613              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1614             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1615                 *wb_comp, sc->recovery_state);
1616             BXE_DMAE_UNLOCK(sc);
1617             return (DMAE_TIMEOUT);
1618         }
1619 
1620         timeout--;
1621         DELAY(50);
1622     }
1623 
1624     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1625         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1626                 *wb_comp, sc->recovery_state);
1627         BXE_DMAE_UNLOCK(sc);
1628         return (DMAE_PCI_ERROR);
1629     }
1630 
1631     BXE_DMAE_UNLOCK(sc);
1632     return (0);
1633 }
1634 
1635 void
1636 bxe_read_dmae(struct bxe_softc *sc,
1637               uint32_t         src_addr,
1638               uint32_t         len32)
1639 {
1640     struct dmae_cmd dmae;
1641     uint32_t *data;
1642     int i, rc;
1643 
1644     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1645 
1646     if (!sc->dmae_ready) {
1647         data = BXE_SP(sc, wb_data[0]);
1648 
1649         for (i = 0; i < len32; i++) {
1650             data[i] = (CHIP_IS_E1(sc)) ?
1651                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1652                           REG_RD(sc, (src_addr + (i * 4)));
1653         }
1654 
1655         return;
1656     }
1657 
1658     /* set opcode and fixed command fields */
1659     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1660 
1661     /* fill in addresses and len */
1662     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1663     dmae.src_addr_hi = 0;
1664     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1665     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1666     dmae.len         = len32;
1667 
1668     /* issue the command and wait for completion */
1669     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1670         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1671     }
1672 }
1673 
1674 void
1675 bxe_write_dmae(struct bxe_softc *sc,
1676                bus_addr_t       dma_addr,
1677                uint32_t         dst_addr,
1678                uint32_t         len32)
1679 {
1680     struct dmae_cmd dmae;
1681     int rc;
1682 
1683     if (!sc->dmae_ready) {
1684         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1685 
1686         if (CHIP_IS_E1(sc)) {
1687             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1688         } else {
1689             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1690         }
1691 
1692         return;
1693     }
1694 
1695     /* set opcode and fixed command fields */
1696     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1697 
1698     /* fill in addresses and len */
1699     dmae.src_addr_lo = U64_LO(dma_addr);
1700     dmae.src_addr_hi = U64_HI(dma_addr);
1701     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1702     dmae.dst_addr_hi = 0;
1703     dmae.len         = len32;
1704 
1705     /* issue the command and wait for completion */
1706     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1707         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1708     }
1709 }
1710 
1711 void
1712 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1713                         bus_addr_t       phys_addr,
1714                         uint32_t         addr,
1715                         uint32_t         len)
1716 {
1717     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1718     int offset = 0;
1719 
1720     while (len > dmae_wr_max) {
1721         bxe_write_dmae(sc,
1722                        (phys_addr + offset), /* src DMA address */
1723                        (addr + offset),      /* dst GRC address */
1724                        dmae_wr_max);
1725         offset += (dmae_wr_max * 4);
1726         len -= dmae_wr_max;
1727     }
1728 
1729     bxe_write_dmae(sc,
1730                    (phys_addr + offset), /* src DMA address */
1731                    (addr + offset),      /* dst GRC address */
1732                    len);
1733 }
1734 
1735 void
1736 bxe_set_ctx_validation(struct bxe_softc   *sc,
1737                        struct eth_context *cxt,
1738                        uint32_t           cid)
1739 {
1740     /* ustorm cxt validation */
1741     cxt->ustorm_ag_context.cdu_usage =
1742         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1743             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1744     /* xcontext validation */
1745     cxt->xstorm_ag_context.cdu_reserved =
1746         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1747             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1748 }
1749 
1750 static void
1751 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1752                             uint8_t          port,
1753                             uint8_t          fw_sb_id,
1754                             uint8_t          sb_index,
1755                             uint8_t          ticks)
1756 {
1757     uint32_t addr =
1758         (BAR_CSTRORM_INTMEM +
1759          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1760 
1761     REG_WR8(sc, addr, ticks);
1762 
1763     BLOGD(sc, DBG_LOAD,
1764           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1765           port, fw_sb_id, sb_index, ticks);
1766 }
1767 
1768 static void
1769 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1770                             uint8_t          port,
1771                             uint16_t         fw_sb_id,
1772                             uint8_t          sb_index,
1773                             uint8_t          disable)
1774 {
1775     uint32_t enable_flag =
1776         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1777     uint32_t addr =
1778         (BAR_CSTRORM_INTMEM +
1779          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1780     uint8_t flags;
1781 
1782     /* clear and set */
1783     flags = REG_RD8(sc, addr);
1784     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1785     flags |= enable_flag;
1786     REG_WR8(sc, addr, flags);
1787 
1788     BLOGD(sc, DBG_LOAD,
1789           "port %d fw_sb_id %d sb_index %d disable %d\n",
1790           port, fw_sb_id, sb_index, disable);
1791 }
1792 
1793 void
1794 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1795                              uint8_t          fw_sb_id,
1796                              uint8_t          sb_index,
1797                              uint8_t          disable,
1798                              uint16_t         usec)
1799 {
1800     int port = SC_PORT(sc);
1801     uint8_t ticks = (usec / 4); /* XXX ??? */
1802 
1803     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1804 
1805     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1806     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1807 }
1808 
1809 void
1810 elink_cb_udelay(struct bxe_softc *sc,
1811                 uint32_t         usecs)
1812 {
1813     DELAY(usecs);
1814 }
1815 
1816 uint32_t
1817 elink_cb_reg_read(struct bxe_softc *sc,
1818                   uint32_t         reg_addr)
1819 {
1820     return (REG_RD(sc, reg_addr));
1821 }
1822 
1823 void
1824 elink_cb_reg_write(struct bxe_softc *sc,
1825                    uint32_t         reg_addr,
1826                    uint32_t         val)
1827 {
1828     REG_WR(sc, reg_addr, val);
1829 }
1830 
1831 void
1832 elink_cb_reg_wb_write(struct bxe_softc *sc,
1833                       uint32_t         offset,
1834                       uint32_t         *wb_write,
1835                       uint16_t         len)
1836 {
1837     REG_WR_DMAE(sc, offset, wb_write, len);
1838 }
1839 
1840 void
1841 elink_cb_reg_wb_read(struct bxe_softc *sc,
1842                      uint32_t         offset,
1843                      uint32_t         *wb_write,
1844                      uint16_t         len)
1845 {
1846     REG_RD_DMAE(sc, offset, wb_write, len);
1847 }
1848 
1849 uint8_t
1850 elink_cb_path_id(struct bxe_softc *sc)
1851 {
1852     return (SC_PATH(sc));
1853 }
1854 
1855 void
1856 elink_cb_event_log(struct bxe_softc     *sc,
1857                    const elink_log_id_t elink_log_id,
1858                    ...)
1859 {
1860     /* XXX */
1861     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1862 }
1863 
1864 static int
1865 bxe_set_spio(struct bxe_softc *sc,
1866              int              spio,
1867              uint32_t         mode)
1868 {
1869     uint32_t spio_reg;
1870 
1871     /* Only 2 SPIOs are configurable */
1872     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1873         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1874         return (-1);
1875     }
1876 
1877     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1878 
1879     /* read SPIO and mask except the float bits */
1880     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1881 
1882     switch (mode) {
1883     case MISC_SPIO_OUTPUT_LOW:
1884         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1885         /* clear FLOAT and set CLR */
1886         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1887         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1888         break;
1889 
1890     case MISC_SPIO_OUTPUT_HIGH:
1891         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1892         /* clear FLOAT and set SET */
1893         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1894         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1895         break;
1896 
1897     case MISC_SPIO_INPUT_HI_Z:
1898         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1899         /* set FLOAT */
1900         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1901         break;
1902 
1903     default:
1904         break;
1905     }
1906 
1907     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1908     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1909 
1910     return (0);
1911 }
1912 
1913 static int
1914 bxe_gpio_read(struct bxe_softc *sc,
1915               int              gpio_num,
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 port 0x%x gpio_port %d gpio_shift %d"
1928             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1929             gpio_mask);
1930         return (-1);
1931     }
1932 
1933     /* read GPIO value */
1934     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1935 
1936     /* get the requested pin value */
1937     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1938 }
1939 
1940 static int
1941 bxe_gpio_write(struct bxe_softc *sc,
1942                int              gpio_num,
1943                uint32_t         mode,
1944                uint8_t          port)
1945 {
1946     /* The GPIO should be swapped if swap register is set and active */
1947     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1948                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1949     int gpio_shift = (gpio_num +
1950                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1951     uint32_t gpio_mask = (1 << gpio_shift);
1952     uint32_t gpio_reg;
1953 
1954     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1955         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1956             " gpio_shift %d gpio_mask 0x%x\n",
1957             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1958         return (-1);
1959     }
1960 
1961     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1962 
1963     /* read GPIO and mask except the float bits */
1964     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1965 
1966     switch (mode) {
1967     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1968         BLOGD(sc, DBG_PHY,
1969               "Set GPIO %d (shift %d) -> output low\n",
1970               gpio_num, gpio_shift);
1971         /* clear FLOAT and set CLR */
1972         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1973         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1974         break;
1975 
1976     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1977         BLOGD(sc, DBG_PHY,
1978               "Set GPIO %d (shift %d) -> output high\n",
1979               gpio_num, gpio_shift);
1980         /* clear FLOAT and set SET */
1981         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1982         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1983         break;
1984 
1985     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1986         BLOGD(sc, DBG_PHY,
1987               "Set GPIO %d (shift %d) -> input\n",
1988               gpio_num, gpio_shift);
1989         /* set FLOAT */
1990         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1991         break;
1992 
1993     default:
1994         break;
1995     }
1996 
1997     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1998     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1999 
2000     return (0);
2001 }
2002 
2003 static int
2004 bxe_gpio_mult_write(struct bxe_softc *sc,
2005                     uint8_t          pins,
2006                     uint32_t         mode)
2007 {
2008     uint32_t gpio_reg;
2009 
2010     /* any port swapping should be handled by caller */
2011 
2012     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2013 
2014     /* read GPIO and mask except the float bits */
2015     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2016     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2017     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2018     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2019 
2020     switch (mode) {
2021     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2022         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2023         /* set CLR */
2024         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2025         break;
2026 
2027     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2028         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2029         /* set SET */
2030         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2031         break;
2032 
2033     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2034         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2035         /* set FLOAT */
2036         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2037         break;
2038 
2039     default:
2040         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2041             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2042         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2043         return (-1);
2044     }
2045 
2046     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2047     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2048 
2049     return (0);
2050 }
2051 
2052 static int
2053 bxe_gpio_int_write(struct bxe_softc *sc,
2054                    int              gpio_num,
2055                    uint32_t         mode,
2056                    uint8_t          port)
2057 {
2058     /* The GPIO should be swapped if swap register is set and active */
2059     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2060                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2061     int gpio_shift = (gpio_num +
2062                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2063     uint32_t gpio_mask = (1 << gpio_shift);
2064     uint32_t gpio_reg;
2065 
2066     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2067         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2068             " gpio_shift %d gpio_mask 0x%x\n",
2069             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2070         return (-1);
2071     }
2072 
2073     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2074 
2075     /* read GPIO int */
2076     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2077 
2078     switch (mode) {
2079     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2080         BLOGD(sc, DBG_PHY,
2081               "Clear GPIO INT %d (shift %d) -> output low\n",
2082               gpio_num, gpio_shift);
2083         /* clear SET and set CLR */
2084         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2085         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2086         break;
2087 
2088     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2089         BLOGD(sc, DBG_PHY,
2090               "Set GPIO INT %d (shift %d) -> output high\n",
2091               gpio_num, gpio_shift);
2092         /* clear CLR and set SET */
2093         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2094         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2095         break;
2096 
2097     default:
2098         break;
2099     }
2100 
2101     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2102     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2103 
2104     return (0);
2105 }
2106 
2107 uint32_t
2108 elink_cb_gpio_read(struct bxe_softc *sc,
2109                    uint16_t         gpio_num,
2110                    uint8_t          port)
2111 {
2112     return (bxe_gpio_read(sc, gpio_num, port));
2113 }
2114 
2115 uint8_t
2116 elink_cb_gpio_write(struct bxe_softc *sc,
2117                     uint16_t         gpio_num,
2118                     uint8_t          mode, /* 0=low 1=high */
2119                     uint8_t          port)
2120 {
2121     return (bxe_gpio_write(sc, gpio_num, mode, port));
2122 }
2123 
2124 uint8_t
2125 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2126                          uint8_t          pins,
2127                          uint8_t          mode) /* 0=low 1=high */
2128 {
2129     return (bxe_gpio_mult_write(sc, pins, mode));
2130 }
2131 
2132 uint8_t
2133 elink_cb_gpio_int_write(struct bxe_softc *sc,
2134                         uint16_t         gpio_num,
2135                         uint8_t          mode, /* 0=low 1=high */
2136                         uint8_t          port)
2137 {
2138     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2139 }
2140 
2141 void
2142 elink_cb_notify_link_changed(struct bxe_softc *sc)
2143 {
2144     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2145                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2146 }
2147 
2148 /* send the MCP a request, block until there is a reply */
2149 uint32_t
2150 elink_cb_fw_command(struct bxe_softc *sc,
2151                     uint32_t         command,
2152                     uint32_t         param)
2153 {
2154     int mb_idx = SC_FW_MB_IDX(sc);
2155     uint32_t seq;
2156     uint32_t rc = 0;
2157     uint32_t cnt = 1;
2158     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2159 
2160     BXE_FWMB_LOCK(sc);
2161 
2162     seq = ++sc->fw_seq;
2163     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2164     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2165 
2166     BLOGD(sc, DBG_PHY,
2167           "wrote command 0x%08x to FW MB param 0x%08x\n",
2168           (command | seq), param);
2169 
2170     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2171     do {
2172         DELAY(delay * 1000);
2173         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2174     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2175 
2176     BLOGD(sc, DBG_PHY,
2177           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2178           cnt*delay, rc, seq);
2179 
2180     /* is this a reply to our command? */
2181     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2182         rc &= FW_MSG_CODE_MASK;
2183     } else {
2184         /* Ruh-roh! */
2185         BLOGE(sc, "FW failed to respond!\n");
2186         // XXX bxe_fw_dump(sc);
2187         rc = 0;
2188     }
2189 
2190     BXE_FWMB_UNLOCK(sc);
2191     return (rc);
2192 }
2193 
2194 static uint32_t
2195 bxe_fw_command(struct bxe_softc *sc,
2196                uint32_t         command,
2197                uint32_t         param)
2198 {
2199     return (elink_cb_fw_command(sc, command, param));
2200 }
2201 
2202 static void
2203 __storm_memset_dma_mapping(struct bxe_softc *sc,
2204                            uint32_t         addr,
2205                            bus_addr_t       mapping)
2206 {
2207     REG_WR(sc, addr, U64_LO(mapping));
2208     REG_WR(sc, (addr + 4), U64_HI(mapping));
2209 }
2210 
2211 static void
2212 storm_memset_spq_addr(struct bxe_softc *sc,
2213                       bus_addr_t       mapping,
2214                       uint16_t         abs_fid)
2215 {
2216     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2217                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2218     __storm_memset_dma_mapping(sc, addr, mapping);
2219 }
2220 
2221 static void
2222 storm_memset_vf_to_pf(struct bxe_softc *sc,
2223                       uint16_t         abs_fid,
2224                       uint16_t         pf_id)
2225 {
2226     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2227     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2228     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2229     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2230 }
2231 
2232 static void
2233 storm_memset_func_en(struct bxe_softc *sc,
2234                      uint16_t         abs_fid,
2235                      uint8_t          enable)
2236 {
2237     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2238     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2239     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2240     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2241 }
2242 
2243 static void
2244 storm_memset_eq_data(struct bxe_softc       *sc,
2245                      struct event_ring_data *eq_data,
2246                      uint16_t               pfid)
2247 {
2248     uint32_t addr;
2249     size_t size;
2250 
2251     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2252     size = sizeof(struct event_ring_data);
2253     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2254 }
2255 
2256 static void
2257 storm_memset_eq_prod(struct bxe_softc *sc,
2258                      uint16_t         eq_prod,
2259                      uint16_t         pfid)
2260 {
2261     uint32_t addr = (BAR_CSTRORM_INTMEM +
2262                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2263     REG_WR16(sc, addr, eq_prod);
2264 }
2265 
2266 /*
2267  * Post a slowpath command.
2268  *
2269  * A slowpath command is used to propagate a configuration change through
2270  * the controller in a controlled manner, allowing each STORM processor and
2271  * other H/W blocks to phase in the change.  The commands sent on the
2272  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2273  * completion of the ramrod will occur in different ways.  Here's a
2274  * breakdown of ramrods and how they complete:
2275  *
2276  * RAMROD_CMD_ID_ETH_PORT_SETUP
2277  *   Used to setup the leading connection on a port.  Completes on the
2278  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2279  *
2280  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2281  *   Used to setup an additional connection on a port.  Completes on the
2282  *   RCQ of the multi-queue/RSS connection being initialized.
2283  *
2284  * RAMROD_CMD_ID_ETH_STAT_QUERY
2285  *   Used to force the storm processors to update the statistics database
2286  *   in host memory.  This ramrod is send on the leading connection CID and
2287  *   completes as an index increment of the CSTORM on the default status
2288  *   block.
2289  *
2290  * RAMROD_CMD_ID_ETH_UPDATE
2291  *   Used to update the state of the leading connection, usually to udpate
2292  *   the RSS indirection table.  Completes on the RCQ of the leading
2293  *   connection. (Not currently used under FreeBSD until OS support becomes
2294  *   available.)
2295  *
2296  * RAMROD_CMD_ID_ETH_HALT
2297  *   Used when tearing down a connection prior to driver unload.  Completes
2298  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2299  *   use this on the leading connection.
2300  *
2301  * RAMROD_CMD_ID_ETH_SET_MAC
2302  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2303  *   the RCQ of the leading connection.
2304  *
2305  * RAMROD_CMD_ID_ETH_CFC_DEL
2306  *   Used when tearing down a conneciton prior to driver unload.  Completes
2307  *   on the RCQ of the leading connection (since the current connection
2308  *   has been completely removed from controller memory).
2309  *
2310  * RAMROD_CMD_ID_ETH_PORT_DEL
2311  *   Used to tear down the leading connection prior to driver unload,
2312  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2313  *   default status block.
2314  *
2315  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2316  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2317  *   RSS connection that is being offloaded.  (Not currently used under
2318  *   FreeBSD.)
2319  *
2320  * There can only be one command pending per function.
2321  *
2322  * Returns:
2323  *   0 = Success, !0 = Failure.
2324  */
2325 
2326 /* must be called under the spq lock */
2327 static inline
2328 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2329 {
2330     struct eth_spe *next_spe = sc->spq_prod_bd;
2331 
2332     if (sc->spq_prod_bd == sc->spq_last_bd) {
2333         /* wrap back to the first eth_spq */
2334         sc->spq_prod_bd = sc->spq;
2335         sc->spq_prod_idx = 0;
2336     } else {
2337         sc->spq_prod_bd++;
2338         sc->spq_prod_idx++;
2339     }
2340 
2341     return (next_spe);
2342 }
2343 
2344 /* must be called under the spq lock */
2345 static inline
2346 void bxe_sp_prod_update(struct bxe_softc *sc)
2347 {
2348     int func = SC_FUNC(sc);
2349 
2350     /*
2351      * Make sure that BD data is updated before writing the producer.
2352      * BD data is written to the memory, the producer is read from the
2353      * memory, thus we need a full memory barrier to ensure the ordering.
2354      */
2355     mb();
2356 
2357     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2358              sc->spq_prod_idx);
2359 
2360     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2361                       BUS_SPACE_BARRIER_WRITE);
2362 }
2363 
2364 /**
2365  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2366  *
2367  * @cmd:      command to check
2368  * @cmd_type: command type
2369  */
2370 static inline
2371 int bxe_is_contextless_ramrod(int cmd,
2372                               int cmd_type)
2373 {
2374     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2375         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2376         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2377         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2378         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2379         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2380         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2381         return (TRUE);
2382     } else {
2383         return (FALSE);
2384     }
2385 }
2386 
2387 /**
2388  * bxe_sp_post - place a single command on an SP ring
2389  *
2390  * @sc:         driver handle
2391  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2392  * @cid:        SW CID the command is related to
2393  * @data_hi:    command private data address (high 32 bits)
2394  * @data_lo:    command private data address (low 32 bits)
2395  * @cmd_type:   command type (e.g. NONE, ETH)
2396  *
2397  * SP data is handled as if it's always an address pair, thus data fields are
2398  * not swapped to little endian in upper functions. Instead this function swaps
2399  * data as if it's two uint32 fields.
2400  */
2401 int
2402 bxe_sp_post(struct bxe_softc *sc,
2403             int              command,
2404             int              cid,
2405             uint32_t         data_hi,
2406             uint32_t         data_lo,
2407             int              cmd_type)
2408 {
2409     struct eth_spe *spe;
2410     uint16_t type;
2411     int common;
2412 
2413     common = bxe_is_contextless_ramrod(command, cmd_type);
2414 
2415     BXE_SP_LOCK(sc);
2416 
2417     if (common) {
2418         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2419             BLOGE(sc, "EQ ring is full!\n");
2420             BXE_SP_UNLOCK(sc);
2421             return (-1);
2422         }
2423     } else {
2424         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2425             BLOGE(sc, "SPQ ring is full!\n");
2426             BXE_SP_UNLOCK(sc);
2427             return (-1);
2428         }
2429     }
2430 
2431     spe = bxe_sp_get_next(sc);
2432 
2433     /* CID needs port number to be encoded int it */
2434     spe->hdr.conn_and_cmd_data =
2435         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2436 
2437     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2438 
2439     /* TBD: Check if it works for VFs */
2440     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2441              SPE_HDR_T_FUNCTION_ID);
2442 
2443     spe->hdr.type = htole16(type);
2444 
2445     spe->data.update_data_addr.hi = htole32(data_hi);
2446     spe->data.update_data_addr.lo = htole32(data_lo);
2447 
2448     /*
2449      * It's ok if the actual decrement is issued towards the memory
2450      * somewhere between the lock and unlock. Thus no more explict
2451      * memory barrier is needed.
2452      */
2453     if (common) {
2454         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2455     } else {
2456         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2457     }
2458 
2459     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2460     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2461           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2462     BLOGD(sc, DBG_SP,
2463           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2464           sc->spq_prod_idx,
2465           (uint32_t)U64_HI(sc->spq_dma.paddr),
2466           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2467           command,
2468           common,
2469           HW_CID(sc, cid),
2470           data_hi,
2471           data_lo,
2472           type,
2473           atomic_load_acq_long(&sc->cq_spq_left),
2474           atomic_load_acq_long(&sc->eq_spq_left));
2475 
2476     bxe_sp_prod_update(sc);
2477 
2478     BXE_SP_UNLOCK(sc);
2479     return (0);
2480 }
2481 
2482 /**
2483  * bxe_debug_print_ind_table - prints the indirection table configuration.
2484  *
2485  * @sc: driver hanlde
2486  * @p:  pointer to rss configuration
2487  */
2488 
2489 /*
2490  * FreeBSD Device probe function.
2491  *
2492  * Compares the device found to the driver's list of supported devices and
2493  * reports back to the bsd loader whether this is the right driver for the device.
2494  * This is the driver entry function called from the "kldload" command.
2495  *
2496  * Returns:
2497  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2498  */
2499 static int
2500 bxe_probe(device_t dev)
2501 {
2502     struct bxe_device_type *t;
2503     char *descbuf;
2504     uint16_t did, sdid, svid, vid;
2505 
2506     /* Find our device structure */
2507     t = bxe_devs;
2508 
2509     /* Get the data for the device to be probed. */
2510     vid  = pci_get_vendor(dev);
2511     did  = pci_get_device(dev);
2512     svid = pci_get_subvendor(dev);
2513     sdid = pci_get_subdevice(dev);
2514 
2515     /* Look through the list of known devices for a match. */
2516     while (t->bxe_name != NULL) {
2517         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2518             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2519             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2520             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2521             if (descbuf == NULL)
2522                 return (ENOMEM);
2523 
2524             /* Print out the device identity. */
2525             snprintf(descbuf, BXE_DEVDESC_MAX,
2526                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2527                      (((pci_read_config(dev, PCIR_REVID, 4) &
2528                         0xf0) >> 4) + 'A'),
2529                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2530                      BXE_DRIVER_VERSION);
2531 
2532             device_set_desc_copy(dev, descbuf);
2533             free(descbuf, M_TEMP);
2534             return (BUS_PROBE_DEFAULT);
2535         }
2536         t++;
2537     }
2538 
2539     return (ENXIO);
2540 }
2541 
2542 static void
2543 bxe_init_mutexes(struct bxe_softc *sc)
2544 {
2545 #ifdef BXE_CORE_LOCK_SX
2546     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2547              "bxe%d_core_lock", sc->unit);
2548     sx_init(&sc->core_sx, sc->core_sx_name);
2549 #else
2550     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2551              "bxe%d_core_lock", sc->unit);
2552     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2553 #endif
2554 
2555     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2556              "bxe%d_sp_lock", sc->unit);
2557     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2558 
2559     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2560              "bxe%d_dmae_lock", sc->unit);
2561     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2562 
2563     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2564              "bxe%d_phy_lock", sc->unit);
2565     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2566 
2567     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2568              "bxe%d_fwmb_lock", sc->unit);
2569     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2570 
2571     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2572              "bxe%d_print_lock", sc->unit);
2573     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2574 
2575     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2576              "bxe%d_stats_lock", sc->unit);
2577     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2578 
2579     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2580              "bxe%d_mcast_lock", sc->unit);
2581     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2582 }
2583 
2584 static void
2585 bxe_release_mutexes(struct bxe_softc *sc)
2586 {
2587 #ifdef BXE_CORE_LOCK_SX
2588     sx_destroy(&sc->core_sx);
2589 #else
2590     if (mtx_initialized(&sc->core_mtx)) {
2591         mtx_destroy(&sc->core_mtx);
2592     }
2593 #endif
2594 
2595     if (mtx_initialized(&sc->sp_mtx)) {
2596         mtx_destroy(&sc->sp_mtx);
2597     }
2598 
2599     if (mtx_initialized(&sc->dmae_mtx)) {
2600         mtx_destroy(&sc->dmae_mtx);
2601     }
2602 
2603     if (mtx_initialized(&sc->port.phy_mtx)) {
2604         mtx_destroy(&sc->port.phy_mtx);
2605     }
2606 
2607     if (mtx_initialized(&sc->fwmb_mtx)) {
2608         mtx_destroy(&sc->fwmb_mtx);
2609     }
2610 
2611     if (mtx_initialized(&sc->print_mtx)) {
2612         mtx_destroy(&sc->print_mtx);
2613     }
2614 
2615     if (mtx_initialized(&sc->stats_mtx)) {
2616         mtx_destroy(&sc->stats_mtx);
2617     }
2618 
2619     if (mtx_initialized(&sc->mcast_mtx)) {
2620         mtx_destroy(&sc->mcast_mtx);
2621     }
2622 }
2623 
2624 static void
2625 bxe_tx_disable(struct bxe_softc* sc)
2626 {
2627     if_t ifp = sc->ifp;
2628 
2629     /* tell the stack the driver is stopped and TX queue is full */
2630     if (ifp !=  NULL) {
2631         if_setdrvflags(ifp, 0);
2632     }
2633 }
2634 
2635 static void
2636 bxe_drv_pulse(struct bxe_softc *sc)
2637 {
2638     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2639              sc->fw_drv_pulse_wr_seq);
2640 }
2641 
2642 static inline uint16_t
2643 bxe_tx_avail(struct bxe_softc *sc,
2644              struct bxe_fastpath *fp)
2645 {
2646     int16_t  used;
2647     uint16_t prod;
2648     uint16_t cons;
2649 
2650     prod = fp->tx_bd_prod;
2651     cons = fp->tx_bd_cons;
2652 
2653     used = SUB_S16(prod, cons);
2654 
2655     return (int16_t)(sc->tx_ring_size) - used;
2656 }
2657 
2658 static inline int
2659 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2660 {
2661     uint16_t hw_cons;
2662 
2663     mb(); /* status block fields can change */
2664     hw_cons = le16toh(*fp->tx_cons_sb);
2665     return (hw_cons != fp->tx_pkt_cons);
2666 }
2667 
2668 static inline uint8_t
2669 bxe_has_tx_work(struct bxe_fastpath *fp)
2670 {
2671     /* expand this for multi-cos if ever supported */
2672     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2673 }
2674 
2675 static inline int
2676 bxe_has_rx_work(struct bxe_fastpath *fp)
2677 {
2678     uint16_t rx_cq_cons_sb;
2679 
2680     mb(); /* status block fields can change */
2681     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2682     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2683         rx_cq_cons_sb++;
2684     return (fp->rx_cq_cons != rx_cq_cons_sb);
2685 }
2686 
2687 static void
2688 bxe_sp_event(struct bxe_softc    *sc,
2689              struct bxe_fastpath *fp,
2690              union eth_rx_cqe    *rr_cqe)
2691 {
2692     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2693     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2694     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2695     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2696 
2697     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2698           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2699 
2700     switch (command) {
2701     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2702         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2703         drv_cmd = ECORE_Q_CMD_UPDATE;
2704         break;
2705 
2706     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2707         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2708         drv_cmd = ECORE_Q_CMD_SETUP;
2709         break;
2710 
2711     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2712         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2713         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2714         break;
2715 
2716     case (RAMROD_CMD_ID_ETH_HALT):
2717         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2718         drv_cmd = ECORE_Q_CMD_HALT;
2719         break;
2720 
2721     case (RAMROD_CMD_ID_ETH_TERMINATE):
2722         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2723         drv_cmd = ECORE_Q_CMD_TERMINATE;
2724         break;
2725 
2726     case (RAMROD_CMD_ID_ETH_EMPTY):
2727         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2728         drv_cmd = ECORE_Q_CMD_EMPTY;
2729         break;
2730 
2731     default:
2732         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2733               command, fp->index);
2734         return;
2735     }
2736 
2737     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2738         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2739         /*
2740          * q_obj->complete_cmd() failure means that this was
2741          * an unexpected completion.
2742          *
2743          * In this case we don't want to increase the sc->spq_left
2744          * because apparently we haven't sent this command the first
2745          * place.
2746          */
2747         // bxe_panic(sc, ("Unexpected SP completion\n"));
2748         return;
2749     }
2750 
2751     atomic_add_acq_long(&sc->cq_spq_left, 1);
2752 
2753     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2754           atomic_load_acq_long(&sc->cq_spq_left));
2755 }
2756 
2757 /*
2758  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2759  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2760  * the current aggregation queue as in-progress.
2761  */
2762 static void
2763 bxe_tpa_start(struct bxe_softc            *sc,
2764               struct bxe_fastpath         *fp,
2765               uint16_t                    queue,
2766               uint16_t                    cons,
2767               uint16_t                    prod,
2768               struct eth_fast_path_rx_cqe *cqe)
2769 {
2770     struct bxe_sw_rx_bd tmp_bd;
2771     struct bxe_sw_rx_bd *rx_buf;
2772     struct eth_rx_bd *rx_bd;
2773     int max_agg_queues;
2774     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2775     uint16_t index;
2776 
2777     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2778                        "cons=%d prod=%d\n",
2779           fp->index, queue, cons, prod);
2780 
2781     max_agg_queues = MAX_AGG_QS(sc);
2782 
2783     KASSERT((queue < max_agg_queues),
2784             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2785              fp->index, queue, max_agg_queues));
2786 
2787     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2788             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2789              fp->index, queue));
2790 
2791     /* copy the existing mbuf and mapping from the TPA pool */
2792     tmp_bd = tpa_info->bd;
2793 
2794     if (tmp_bd.m == NULL) {
2795         uint32_t *tmp;
2796 
2797         tmp = (uint32_t *)cqe;
2798 
2799         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2800               fp->index, queue, cons, prod);
2801         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2802             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2803 
2804         /* XXX Error handling? */
2805         return;
2806     }
2807 
2808     /* change the TPA queue to the start state */
2809     tpa_info->state            = BXE_TPA_STATE_START;
2810     tpa_info->placement_offset = cqe->placement_offset;
2811     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2812     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2813     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2814 
2815     fp->rx_tpa_queue_used |= (1 << queue);
2816 
2817     /*
2818      * If all the buffer descriptors are filled with mbufs then fill in
2819      * the current consumer index with a new BD. Else if a maximum Rx
2820      * buffer limit is imposed then fill in the next producer index.
2821      */
2822     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2823                 prod : cons;
2824 
2825     /* move the received mbuf and mapping to TPA pool */
2826     tpa_info->bd = fp->rx_mbuf_chain[cons];
2827 
2828     /* release any existing RX BD mbuf mappings */
2829     if (cons != index) {
2830         rx_buf = &fp->rx_mbuf_chain[cons];
2831 
2832         if (rx_buf->m_map != NULL) {
2833             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2834                             BUS_DMASYNC_POSTREAD);
2835             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2836         }
2837 
2838         /*
2839          * We get here when the maximum number of rx buffers is less than
2840          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2841          * it out here without concern of a memory leak.
2842          */
2843         fp->rx_mbuf_chain[cons].m = NULL;
2844     }
2845 
2846     /* update the Rx SW BD with the mbuf info from the TPA pool */
2847     fp->rx_mbuf_chain[index] = tmp_bd;
2848 
2849     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2850     rx_bd = &fp->rx_chain[index];
2851     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2852     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2853 }
2854 
2855 /*
2856  * When a TPA aggregation is completed, loop through the individual mbufs
2857  * of the aggregation, combining them into a single mbuf which will be sent
2858  * up the stack. Refill all freed SGEs with mbufs as we go along.
2859  */
2860 static int
2861 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2862                    struct bxe_fastpath       *fp,
2863                    struct bxe_sw_tpa_info    *tpa_info,
2864                    uint16_t                  queue,
2865                    uint16_t                  pages,
2866                    struct mbuf               *m,
2867 			       struct eth_end_agg_rx_cqe *cqe,
2868                    uint16_t                  cqe_idx)
2869 {
2870     struct mbuf *m_frag;
2871     uint32_t frag_len, frag_size, i;
2872     uint16_t sge_idx;
2873     int rc = 0;
2874     int j;
2875 
2876     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2877 
2878     BLOGD(sc, DBG_LRO,
2879           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2880           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2881 
2882     /* make sure the aggregated frame is not too big to handle */
2883     if (pages > 8 * PAGES_PER_SGE) {
2884 
2885         uint32_t *tmp = (uint32_t *)cqe;
2886 
2887         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2888                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2889               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2890               tpa_info->len_on_bd, frag_size);
2891 
2892         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2893             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2894 
2895         bxe_panic(sc, ("sge page count error\n"));
2896         return (EINVAL);
2897     }
2898 
2899     /*
2900      * Scan through the scatter gather list pulling individual mbufs into a
2901      * single mbuf for the host stack.
2902      */
2903     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2904         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2905 
2906         /*
2907          * Firmware gives the indices of the SGE as if the ring is an array
2908          * (meaning that the "next" element will consume 2 indices).
2909          */
2910         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2911 
2912         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2913                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2914               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2915 
2916         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2917 
2918         /* allocate a new mbuf for the SGE */
2919         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2920         if (rc) {
2921             /* Leave all remaining SGEs in the ring! */
2922             return (rc);
2923         }
2924 
2925         /* update the fragment length */
2926         m_frag->m_len = frag_len;
2927 
2928         /* concatenate the fragment to the head mbuf */
2929         m_cat(m, m_frag);
2930         fp->eth_q_stats.mbuf_alloc_sge--;
2931 
2932         /* update the TPA mbuf size and remaining fragment size */
2933         m->m_pkthdr.len += frag_len;
2934         frag_size -= frag_len;
2935     }
2936 
2937     BLOGD(sc, DBG_LRO,
2938           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2939           fp->index, queue, frag_size);
2940 
2941     return (rc);
2942 }
2943 
2944 static inline void
2945 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2946 {
2947     int i, j;
2948 
2949     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2950         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2951 
2952         for (j = 0; j < 2; j++) {
2953             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2954             idx--;
2955         }
2956     }
2957 }
2958 
2959 static inline void
2960 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2961 {
2962     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2963     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2964 
2965     /*
2966      * Clear the two last indices in the page to 1. These are the indices that
2967      * correspond to the "next" element, hence will never be indicated and
2968      * should be removed from the calculations.
2969      */
2970     bxe_clear_sge_mask_next_elems(fp);
2971 }
2972 
2973 static inline void
2974 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2975                         uint16_t            idx)
2976 {
2977     uint16_t last_max = fp->last_max_sge;
2978 
2979     if (SUB_S16(idx, last_max) > 0) {
2980         fp->last_max_sge = idx;
2981     }
2982 }
2983 
2984 static inline void
2985 bxe_update_sge_prod(struct bxe_softc          *sc,
2986                     struct bxe_fastpath       *fp,
2987                     uint16_t                  sge_len,
2988                     union eth_sgl_or_raw_data *cqe)
2989 {
2990     uint16_t last_max, last_elem, first_elem;
2991     uint16_t delta = 0;
2992     uint16_t i;
2993 
2994     if (!sge_len) {
2995         return;
2996     }
2997 
2998     /* first mark all used pages */
2999     for (i = 0; i < sge_len; i++) {
3000         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3001                             RX_SGE(le16toh(cqe->sgl[i])));
3002     }
3003 
3004     BLOGD(sc, DBG_LRO,
3005           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3006           fp->index, sge_len - 1,
3007           le16toh(cqe->sgl[sge_len - 1]));
3008 
3009     /* assume that the last SGE index is the biggest */
3010     bxe_update_last_max_sge(fp,
3011                             le16toh(cqe->sgl[sge_len - 1]));
3012 
3013     last_max = RX_SGE(fp->last_max_sge);
3014     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3015     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3016 
3017     /* if ring is not full */
3018     if (last_elem + 1 != first_elem) {
3019         last_elem++;
3020     }
3021 
3022     /* now update the prod */
3023     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3024         if (__predict_true(fp->sge_mask[i])) {
3025             break;
3026         }
3027 
3028         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3029         delta += BIT_VEC64_ELEM_SZ;
3030     }
3031 
3032     if (delta > 0) {
3033         fp->rx_sge_prod += delta;
3034         /* clear page-end entries */
3035         bxe_clear_sge_mask_next_elems(fp);
3036     }
3037 
3038     BLOGD(sc, DBG_LRO,
3039           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3040           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3041 }
3042 
3043 /*
3044  * The aggregation on the current TPA queue has completed. Pull the individual
3045  * mbuf fragments together into a single mbuf, perform all necessary checksum
3046  * calculations, and send the resuting mbuf to the stack.
3047  */
3048 static void
3049 bxe_tpa_stop(struct bxe_softc          *sc,
3050              struct bxe_fastpath       *fp,
3051              struct bxe_sw_tpa_info    *tpa_info,
3052              uint16_t                  queue,
3053              uint16_t                  pages,
3054 			 struct eth_end_agg_rx_cqe *cqe,
3055              uint16_t                  cqe_idx)
3056 {
3057     if_t ifp = sc->ifp;
3058     struct mbuf *m;
3059     int rc = 0;
3060 
3061     BLOGD(sc, DBG_LRO,
3062           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3063           fp->index, queue, tpa_info->placement_offset,
3064           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3065 
3066     m = tpa_info->bd.m;
3067 
3068     /* allocate a replacement before modifying existing mbuf */
3069     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3070     if (rc) {
3071         /* drop the frame and log an error */
3072         fp->eth_q_stats.rx_soft_errors++;
3073         goto bxe_tpa_stop_exit;
3074     }
3075 
3076     /* we have a replacement, fixup the current mbuf */
3077     m_adj(m, tpa_info->placement_offset);
3078     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3079 
3080     /* mark the checksums valid (taken care of by the firmware) */
3081     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3082     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3083     m->m_pkthdr.csum_data = 0xffff;
3084     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3085                                CSUM_IP_VALID   |
3086                                CSUM_DATA_VALID |
3087                                CSUM_PSEUDO_HDR);
3088 
3089     /* aggregate all of the SGEs into a single mbuf */
3090     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3091     if (rc) {
3092         /* drop the packet and log an error */
3093         fp->eth_q_stats.rx_soft_errors++;
3094         m_freem(m);
3095     } else {
3096         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3097             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3098             m->m_flags |= M_VLANTAG;
3099         }
3100 
3101         /* assign packet to this interface interface */
3102         if_setrcvif(m, ifp);
3103 
3104 #if __FreeBSD_version >= 800000
3105         /* specify what RSS queue was used for this flow */
3106         m->m_pkthdr.flowid = fp->index;
3107         BXE_SET_FLOWID(m);
3108 #endif
3109 
3110         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3111         fp->eth_q_stats.rx_tpa_pkts++;
3112 
3113         /* pass the frame to the stack */
3114         if_input(ifp, m);
3115     }
3116 
3117     /* we passed an mbuf up the stack or dropped the frame */
3118     fp->eth_q_stats.mbuf_alloc_tpa--;
3119 
3120 bxe_tpa_stop_exit:
3121 
3122     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3123     fp->rx_tpa_queue_used &= ~(1 << queue);
3124 }
3125 
3126 static uint8_t
3127 bxe_service_rxsgl(
3128                  struct bxe_fastpath *fp,
3129                  uint16_t len,
3130                  uint16_t lenonbd,
3131                  struct mbuf *m,
3132                  struct eth_fast_path_rx_cqe *cqe_fp)
3133 {
3134     struct mbuf *m_frag;
3135     uint16_t frags, frag_len;
3136     uint16_t sge_idx = 0;
3137     uint16_t j;
3138     uint8_t i, rc = 0;
3139     uint32_t frag_size;
3140 
3141     /* adjust the mbuf */
3142     m->m_len = lenonbd;
3143 
3144     frag_size =  len - lenonbd;
3145     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3146 
3147     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3148         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3149 
3150         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3151         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3152         m_frag->m_len = frag_len;
3153 
3154        /* allocate a new mbuf for the SGE */
3155         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3156         if (rc) {
3157             /* Leave all remaining SGEs in the ring! */
3158             return (rc);
3159         }
3160         fp->eth_q_stats.mbuf_alloc_sge--;
3161 
3162         /* concatenate the fragment to the head mbuf */
3163         m_cat(m, m_frag);
3164 
3165         frag_size -= frag_len;
3166     }
3167 
3168     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3169 
3170     return rc;
3171 }
3172 
3173 static uint8_t
3174 bxe_rxeof(struct bxe_softc    *sc,
3175           struct bxe_fastpath *fp)
3176 {
3177     if_t ifp = sc->ifp;
3178     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3179     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3180     int rx_pkts = 0;
3181     int rc = 0;
3182 
3183     BXE_FP_RX_LOCK(fp);
3184 
3185     /* CQ "next element" is of the size of the regular element */
3186     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3187     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3188         hw_cq_cons++;
3189     }
3190 
3191     bd_cons = fp->rx_bd_cons;
3192     bd_prod = fp->rx_bd_prod;
3193     bd_prod_fw = bd_prod;
3194     sw_cq_cons = fp->rx_cq_cons;
3195     sw_cq_prod = fp->rx_cq_prod;
3196 
3197     /*
3198      * Memory barrier necessary as speculative reads of the rx
3199      * buffer can be ahead of the index in the status block
3200      */
3201     rmb();
3202 
3203     BLOGD(sc, DBG_RX,
3204           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3205           fp->index, hw_cq_cons, sw_cq_cons);
3206 
3207     while (sw_cq_cons != hw_cq_cons) {
3208         struct bxe_sw_rx_bd *rx_buf = NULL;
3209         union eth_rx_cqe *cqe;
3210         struct eth_fast_path_rx_cqe *cqe_fp;
3211         uint8_t cqe_fp_flags;
3212         enum eth_rx_cqe_type cqe_fp_type;
3213         uint16_t len, lenonbd,  pad;
3214         struct mbuf *m = NULL;
3215 
3216         comp_ring_cons = RCQ(sw_cq_cons);
3217         bd_prod = RX_BD(bd_prod);
3218         bd_cons = RX_BD(bd_cons);
3219 
3220         cqe          = &fp->rcq_chain[comp_ring_cons];
3221         cqe_fp       = &cqe->fast_path_cqe;
3222         cqe_fp_flags = cqe_fp->type_error_flags;
3223         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3224 
3225         BLOGD(sc, DBG_RX,
3226               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3227               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3228               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3229               fp->index,
3230               hw_cq_cons,
3231               sw_cq_cons,
3232               bd_prod,
3233               bd_cons,
3234               CQE_TYPE(cqe_fp_flags),
3235               cqe_fp_flags,
3236               cqe_fp->status_flags,
3237               le32toh(cqe_fp->rss_hash_result),
3238               le16toh(cqe_fp->vlan_tag),
3239               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3240               le16toh(cqe_fp->len_on_bd));
3241 
3242         /* is this a slowpath msg? */
3243         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3244             bxe_sp_event(sc, fp, cqe);
3245             goto next_cqe;
3246         }
3247 
3248         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3249 
3250         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3251             struct bxe_sw_tpa_info *tpa_info;
3252             uint16_t frag_size, pages;
3253             uint8_t queue;
3254 
3255             if (CQE_TYPE_START(cqe_fp_type)) {
3256                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3257                               bd_cons, bd_prod, cqe_fp);
3258                 m = NULL; /* packet not ready yet */
3259                 goto next_rx;
3260             }
3261 
3262             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3263                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3264 
3265             queue = cqe->end_agg_cqe.queue_index;
3266             tpa_info = &fp->rx_tpa_info[queue];
3267 
3268             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3269                   fp->index, queue);
3270 
3271             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3272                          tpa_info->len_on_bd);
3273             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3274 
3275             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3276                          &cqe->end_agg_cqe, comp_ring_cons);
3277 
3278             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3279 
3280             goto next_cqe;
3281         }
3282 
3283         /* non TPA */
3284 
3285         /* is this an error packet? */
3286         if (__predict_false(cqe_fp_flags &
3287                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3288             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3289             fp->eth_q_stats.rx_soft_errors++;
3290             goto next_rx;
3291         }
3292 
3293         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3294         lenonbd = le16toh(cqe_fp->len_on_bd);
3295         pad = cqe_fp->placement_offset;
3296 
3297         m = rx_buf->m;
3298 
3299         if (__predict_false(m == NULL)) {
3300             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3301                   bd_cons, fp->index);
3302             goto next_rx;
3303         }
3304 
3305         /* XXX double copy if packet length under a threshold */
3306 
3307         /*
3308          * If all the buffer descriptors are filled with mbufs then fill in
3309          * the current consumer index with a new BD. Else if a maximum Rx
3310          * buffer limit is imposed then fill in the next producer index.
3311          */
3312         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3313                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3314                                       bd_prod : bd_cons);
3315         if (rc != 0) {
3316 
3317             /* we simply reuse the received mbuf and don't post it to the stack */
3318             m = NULL;
3319 
3320             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3321                   fp->index, rc);
3322             fp->eth_q_stats.rx_soft_errors++;
3323 
3324             if (sc->max_rx_bufs != RX_BD_USABLE) {
3325                 /* copy this consumer index to the producer index */
3326                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3327                        sizeof(struct bxe_sw_rx_bd));
3328                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3329             }
3330 
3331             goto next_rx;
3332         }
3333 
3334         /* current mbuf was detached from the bd */
3335         fp->eth_q_stats.mbuf_alloc_rx--;
3336 
3337         /* we allocated a replacement mbuf, fixup the current one */
3338         m_adj(m, pad);
3339         m->m_pkthdr.len = m->m_len = len;
3340 
3341         if ((len > 60) && (len > lenonbd)) {
3342             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3343             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3344             if (rc)
3345                 break;
3346             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3347         } else if (lenonbd < len) {
3348             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3349         }
3350 
3351         /* assign packet to this interface interface */
3352 	if_setrcvif(m, ifp);
3353 
3354         /* assume no hardware checksum has complated */
3355         m->m_pkthdr.csum_flags = 0;
3356 
3357         /* validate checksum if offload enabled */
3358         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3359             /* check for a valid IP frame */
3360             if (!(cqe->fast_path_cqe.status_flags &
3361                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3362                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3363                 if (__predict_false(cqe_fp_flags &
3364                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3365                     fp->eth_q_stats.rx_hw_csum_errors++;
3366                 } else {
3367                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3368                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3369                 }
3370             }
3371 
3372             /* check for a valid TCP/UDP frame */
3373             if (!(cqe->fast_path_cqe.status_flags &
3374                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3375                 if (__predict_false(cqe_fp_flags &
3376                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3377                     fp->eth_q_stats.rx_hw_csum_errors++;
3378                 } else {
3379                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3380                     m->m_pkthdr.csum_data = 0xFFFF;
3381                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3382                                                CSUM_PSEUDO_HDR);
3383                 }
3384             }
3385         }
3386 
3387         /* if there is a VLAN tag then flag that info */
3388         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3389             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3390             m->m_flags |= M_VLANTAG;
3391         }
3392 
3393 #if __FreeBSD_version >= 800000
3394         /* specify what RSS queue was used for this flow */
3395         m->m_pkthdr.flowid = fp->index;
3396         BXE_SET_FLOWID(m);
3397 #endif
3398 
3399 next_rx:
3400 
3401         bd_cons    = RX_BD_NEXT(bd_cons);
3402         bd_prod    = RX_BD_NEXT(bd_prod);
3403         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3404 
3405         /* pass the frame to the stack */
3406         if (__predict_true(m != NULL)) {
3407             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3408             rx_pkts++;
3409             if_input(ifp, m);
3410         }
3411 
3412 next_cqe:
3413 
3414         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3415         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3416 
3417         /* limit spinning on the queue */
3418         if (rc != 0)
3419             break;
3420 
3421         if (rx_pkts == sc->rx_budget) {
3422             fp->eth_q_stats.rx_budget_reached++;
3423             break;
3424         }
3425     } /* while work to do */
3426 
3427     fp->rx_bd_cons = bd_cons;
3428     fp->rx_bd_prod = bd_prod_fw;
3429     fp->rx_cq_cons = sw_cq_cons;
3430     fp->rx_cq_prod = sw_cq_prod;
3431 
3432     /* Update producers */
3433     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3434 
3435     fp->eth_q_stats.rx_pkts += rx_pkts;
3436     fp->eth_q_stats.rx_calls++;
3437 
3438     BXE_FP_RX_UNLOCK(fp);
3439 
3440     return (sw_cq_cons != hw_cq_cons);
3441 }
3442 
3443 static uint16_t
3444 bxe_free_tx_pkt(struct bxe_softc    *sc,
3445                 struct bxe_fastpath *fp,
3446                 uint16_t            idx)
3447 {
3448     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3449     struct eth_tx_start_bd *tx_start_bd;
3450     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3451     uint16_t new_cons;
3452     int nbd;
3453 
3454     /* unmap the mbuf from non-paged memory */
3455     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3456 
3457     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3458     nbd = le16toh(tx_start_bd->nbd) - 1;
3459 
3460     new_cons = (tx_buf->first_bd + nbd);
3461 
3462     /* free the mbuf */
3463     if (__predict_true(tx_buf->m != NULL)) {
3464         m_freem(tx_buf->m);
3465         fp->eth_q_stats.mbuf_alloc_tx--;
3466     } else {
3467         fp->eth_q_stats.tx_chain_lost_mbuf++;
3468     }
3469 
3470     tx_buf->m = NULL;
3471     tx_buf->first_bd = 0;
3472 
3473     return (new_cons);
3474 }
3475 
3476 /* transmit timeout watchdog */
3477 static int
3478 bxe_watchdog(struct bxe_softc    *sc,
3479              struct bxe_fastpath *fp)
3480 {
3481     BXE_FP_TX_LOCK(fp);
3482 
3483     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3484         BXE_FP_TX_UNLOCK(fp);
3485         return (0);
3486     }
3487 
3488     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3489     if(sc->trigger_grcdump) {
3490          /* taking grcdump */
3491          bxe_grc_dump(sc);
3492     }
3493 
3494     BXE_FP_TX_UNLOCK(fp);
3495 
3496     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3497     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3498 
3499     return (-1);
3500 }
3501 
3502 /* processes transmit completions */
3503 static uint8_t
3504 bxe_txeof(struct bxe_softc    *sc,
3505           struct bxe_fastpath *fp)
3506 {
3507     if_t ifp = sc->ifp;
3508     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3509     uint16_t tx_bd_avail;
3510 
3511     BXE_FP_TX_LOCK_ASSERT(fp);
3512 
3513     bd_cons = fp->tx_bd_cons;
3514     hw_cons = le16toh(*fp->tx_cons_sb);
3515     sw_cons = fp->tx_pkt_cons;
3516 
3517     while (sw_cons != hw_cons) {
3518         pkt_cons = TX_BD(sw_cons);
3519 
3520         BLOGD(sc, DBG_TX,
3521               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3522               fp->index, hw_cons, sw_cons, pkt_cons);
3523 
3524         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3525 
3526         sw_cons++;
3527     }
3528 
3529     fp->tx_pkt_cons = sw_cons;
3530     fp->tx_bd_cons  = bd_cons;
3531 
3532     BLOGD(sc, DBG_TX,
3533           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3534           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3535 
3536     mb();
3537 
3538     tx_bd_avail = bxe_tx_avail(sc, fp);
3539 
3540     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3541         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3542     } else {
3543         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3544     }
3545 
3546     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3547         /* reset the watchdog timer if there are pending transmits */
3548         fp->watchdog_timer = BXE_TX_TIMEOUT;
3549         return (TRUE);
3550     } else {
3551         /* clear watchdog when there are no pending transmits */
3552         fp->watchdog_timer = 0;
3553         return (FALSE);
3554     }
3555 }
3556 
3557 static void
3558 bxe_drain_tx_queues(struct bxe_softc *sc)
3559 {
3560     struct bxe_fastpath *fp;
3561     int i, count;
3562 
3563     /* wait until all TX fastpath tasks have completed */
3564     for (i = 0; i < sc->num_queues; i++) {
3565         fp = &sc->fp[i];
3566 
3567         count = 1000;
3568 
3569         while (bxe_has_tx_work(fp)) {
3570 
3571             BXE_FP_TX_LOCK(fp);
3572             bxe_txeof(sc, fp);
3573             BXE_FP_TX_UNLOCK(fp);
3574 
3575             if (count == 0) {
3576                 BLOGE(sc, "Timeout waiting for fp[%d] "
3577                           "transmits to complete!\n", i);
3578                 bxe_panic(sc, ("tx drain failure\n"));
3579                 return;
3580             }
3581 
3582             count--;
3583             DELAY(1000);
3584             rmb();
3585         }
3586     }
3587 
3588     return;
3589 }
3590 
3591 static int
3592 bxe_del_all_macs(struct bxe_softc          *sc,
3593                  struct ecore_vlan_mac_obj *mac_obj,
3594                  int                       mac_type,
3595                  uint8_t                   wait_for_comp)
3596 {
3597     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3598     int rc;
3599 
3600     /* wait for completion of requested */
3601     if (wait_for_comp) {
3602         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3603     }
3604 
3605     /* Set the mac type of addresses we want to clear */
3606     bxe_set_bit(mac_type, &vlan_mac_flags);
3607 
3608     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3609     if (rc < 0) {
3610         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3611             rc, mac_type, wait_for_comp);
3612     }
3613 
3614     return (rc);
3615 }
3616 
3617 static int
3618 bxe_fill_accept_flags(struct bxe_softc *sc,
3619                       uint32_t         rx_mode,
3620                       unsigned long    *rx_accept_flags,
3621                       unsigned long    *tx_accept_flags)
3622 {
3623     /* Clear the flags first */
3624     *rx_accept_flags = 0;
3625     *tx_accept_flags = 0;
3626 
3627     switch (rx_mode) {
3628     case BXE_RX_MODE_NONE:
3629         /*
3630          * 'drop all' supersedes any accept flags that may have been
3631          * passed to the function.
3632          */
3633         break;
3634 
3635     case BXE_RX_MODE_NORMAL:
3636         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3637         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3638         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3639 
3640         /* internal switching mode */
3641         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3642         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3643         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3644 
3645         break;
3646 
3647     case BXE_RX_MODE_ALLMULTI:
3648         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3649         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3650         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3651 
3652         /* internal switching mode */
3653         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3654         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3655         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3656 
3657         break;
3658 
3659     case BXE_RX_MODE_PROMISC:
3660         /*
3661          * According to deffinition of SI mode, iface in promisc mode
3662          * should receive matched and unmatched (in resolution of port)
3663          * unicast packets.
3664          */
3665         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3666         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3667         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3668         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3669 
3670         /* internal switching mode */
3671         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3672         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3673 
3674         if (IS_MF_SI(sc)) {
3675             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3676         } else {
3677             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3678         }
3679 
3680         break;
3681 
3682     default:
3683         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3684         return (-1);
3685     }
3686 
3687     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3688     if (rx_mode != BXE_RX_MODE_NONE) {
3689         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3690         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3691     }
3692 
3693     return (0);
3694 }
3695 
3696 static int
3697 bxe_set_q_rx_mode(struct bxe_softc *sc,
3698                   uint8_t          cl_id,
3699                   unsigned long    rx_mode_flags,
3700                   unsigned long    rx_accept_flags,
3701                   unsigned long    tx_accept_flags,
3702                   unsigned long    ramrod_flags)
3703 {
3704     struct ecore_rx_mode_ramrod_params ramrod_param;
3705     int rc;
3706 
3707     memset(&ramrod_param, 0, sizeof(ramrod_param));
3708 
3709     /* Prepare ramrod parameters */
3710     ramrod_param.cid = 0;
3711     ramrod_param.cl_id = cl_id;
3712     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3713     ramrod_param.func_id = SC_FUNC(sc);
3714 
3715     ramrod_param.pstate = &sc->sp_state;
3716     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3717 
3718     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3719     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3720 
3721     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3722 
3723     ramrod_param.ramrod_flags = ramrod_flags;
3724     ramrod_param.rx_mode_flags = rx_mode_flags;
3725 
3726     ramrod_param.rx_accept_flags = rx_accept_flags;
3727     ramrod_param.tx_accept_flags = tx_accept_flags;
3728 
3729     rc = ecore_config_rx_mode(sc, &ramrod_param);
3730     if (rc < 0) {
3731         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3732             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3733             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3734             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3735             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3736         return (rc);
3737     }
3738 
3739     return (0);
3740 }
3741 
3742 static int
3743 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3744 {
3745     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3746     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3747     int rc;
3748 
3749     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3750                                &tx_accept_flags);
3751     if (rc) {
3752         return (rc);
3753     }
3754 
3755     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3756     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3757 
3758     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3759     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3760                               rx_accept_flags, tx_accept_flags,
3761                               ramrod_flags));
3762 }
3763 
3764 /* returns the "mcp load_code" according to global load_count array */
3765 static int
3766 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3767 {
3768     int path = SC_PATH(sc);
3769     int port = SC_PORT(sc);
3770 
3771     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3772           path, load_count[path][0], load_count[path][1],
3773           load_count[path][2]);
3774     load_count[path][0]++;
3775     load_count[path][1 + port]++;
3776     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3777           path, load_count[path][0], load_count[path][1],
3778           load_count[path][2]);
3779     if (load_count[path][0] == 1) {
3780         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3781     } else if (load_count[path][1 + port] == 1) {
3782         return (FW_MSG_CODE_DRV_LOAD_PORT);
3783     } else {
3784         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3785     }
3786 }
3787 
3788 /* returns the "mcp load_code" according to global load_count array */
3789 static int
3790 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3791 {
3792     int port = SC_PORT(sc);
3793     int path = SC_PATH(sc);
3794 
3795     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3796           path, load_count[path][0], load_count[path][1],
3797           load_count[path][2]);
3798     load_count[path][0]--;
3799     load_count[path][1 + port]--;
3800     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3801           path, load_count[path][0], load_count[path][1],
3802           load_count[path][2]);
3803     if (load_count[path][0] == 0) {
3804         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3805     } else if (load_count[path][1 + port] == 0) {
3806         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3807     } else {
3808         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3809     }
3810 }
3811 
3812 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3813 static uint32_t
3814 bxe_send_unload_req(struct bxe_softc *sc,
3815                     int              unload_mode)
3816 {
3817     uint32_t reset_code = 0;
3818 
3819     /* Select the UNLOAD request mode */
3820     if (unload_mode == UNLOAD_NORMAL) {
3821         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3822     } else {
3823         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3824     }
3825 
3826     /* Send the request to the MCP */
3827     if (!BXE_NOMCP(sc)) {
3828         reset_code = bxe_fw_command(sc, reset_code, 0);
3829     } else {
3830         reset_code = bxe_nic_unload_no_mcp(sc);
3831     }
3832 
3833     return (reset_code);
3834 }
3835 
3836 /* send UNLOAD_DONE command to the MCP */
3837 static void
3838 bxe_send_unload_done(struct bxe_softc *sc,
3839                      uint8_t          keep_link)
3840 {
3841     uint32_t reset_param =
3842         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3843 
3844     /* Report UNLOAD_DONE to MCP */
3845     if (!BXE_NOMCP(sc)) {
3846         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3847     }
3848 }
3849 
3850 static int
3851 bxe_func_wait_started(struct bxe_softc *sc)
3852 {
3853     int tout = 50;
3854 
3855     if (!sc->port.pmf) {
3856         return (0);
3857     }
3858 
3859     /*
3860      * (assumption: No Attention from MCP at this stage)
3861      * PMF probably in the middle of TX disable/enable transaction
3862      * 1. Sync IRS for default SB
3863      * 2. Sync SP queue - this guarantees us that attention handling started
3864      * 3. Wait, that TX disable/enable transaction completes
3865      *
3866      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3867      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3868      * received completion for the transaction the state is TX_STOPPED.
3869      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3870      * transaction.
3871      */
3872 
3873     /* XXX make sure default SB ISR is done */
3874     /* need a way to synchronize an irq (intr_mtx?) */
3875 
3876     /* XXX flush any work queues */
3877 
3878     while (ecore_func_get_state(sc, &sc->func_obj) !=
3879            ECORE_F_STATE_STARTED && tout--) {
3880         DELAY(20000);
3881     }
3882 
3883     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3884         /*
3885          * Failed to complete the transaction in a "good way"
3886          * Force both transactions with CLR bit.
3887          */
3888         struct ecore_func_state_params func_params = { NULL };
3889 
3890         BLOGE(sc, "Unexpected function state! "
3891                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3892 
3893         func_params.f_obj = &sc->func_obj;
3894         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3895 
3896         /* STARTED-->TX_STOPPED */
3897         func_params.cmd = ECORE_F_CMD_TX_STOP;
3898         ecore_func_state_change(sc, &func_params);
3899 
3900         /* TX_STOPPED-->STARTED */
3901         func_params.cmd = ECORE_F_CMD_TX_START;
3902         return (ecore_func_state_change(sc, &func_params));
3903     }
3904 
3905     return (0);
3906 }
3907 
3908 static int
3909 bxe_stop_queue(struct bxe_softc *sc,
3910                int              index)
3911 {
3912     struct bxe_fastpath *fp = &sc->fp[index];
3913     struct ecore_queue_state_params q_params = { NULL };
3914     int rc;
3915 
3916     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3917 
3918     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3919     /* We want to wait for completion in this context */
3920     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3921 
3922     /* Stop the primary connection: */
3923 
3924     /* ...halt the connection */
3925     q_params.cmd = ECORE_Q_CMD_HALT;
3926     rc = ecore_queue_state_change(sc, &q_params);
3927     if (rc) {
3928         return (rc);
3929     }
3930 
3931     /* ...terminate the connection */
3932     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3933     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3934     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3935     rc = ecore_queue_state_change(sc, &q_params);
3936     if (rc) {
3937         return (rc);
3938     }
3939 
3940     /* ...delete cfc entry */
3941     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3942     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3943     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3944     return (ecore_queue_state_change(sc, &q_params));
3945 }
3946 
3947 /* wait for the outstanding SP commands */
3948 static inline uint8_t
3949 bxe_wait_sp_comp(struct bxe_softc *sc,
3950                  unsigned long    mask)
3951 {
3952     unsigned long tmp;
3953     int tout = 5000; /* wait for 5 secs tops */
3954 
3955     while (tout--) {
3956         mb();
3957         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3958             return (TRUE);
3959         }
3960 
3961         DELAY(1000);
3962     }
3963 
3964     mb();
3965 
3966     tmp = atomic_load_acq_long(&sc->sp_state);
3967     if (tmp & mask) {
3968         BLOGE(sc, "Filtering completion timed out: "
3969                   "sp_state 0x%lx, mask 0x%lx\n",
3970               tmp, mask);
3971         return (FALSE);
3972     }
3973 
3974     return (FALSE);
3975 }
3976 
3977 static int
3978 bxe_func_stop(struct bxe_softc *sc)
3979 {
3980     struct ecore_func_state_params func_params = { NULL };
3981     int rc;
3982 
3983     /* prepare parameters for function state transitions */
3984     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3985     func_params.f_obj = &sc->func_obj;
3986     func_params.cmd = ECORE_F_CMD_STOP;
3987 
3988     /*
3989      * Try to stop the function the 'good way'. If it fails (in case
3990      * of a parity error during bxe_chip_cleanup()) and we are
3991      * not in a debug mode, perform a state transaction in order to
3992      * enable further HW_RESET transaction.
3993      */
3994     rc = ecore_func_state_change(sc, &func_params);
3995     if (rc) {
3996         BLOGE(sc, "FUNC_STOP ramrod failed. "
3997                   "Running a dry transaction (%d)\n", rc);
3998         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3999         return (ecore_func_state_change(sc, &func_params));
4000     }
4001 
4002     return (0);
4003 }
4004 
4005 static int
4006 bxe_reset_hw(struct bxe_softc *sc,
4007              uint32_t         load_code)
4008 {
4009     struct ecore_func_state_params func_params = { NULL };
4010 
4011     /* Prepare parameters for function state transitions */
4012     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4013 
4014     func_params.f_obj = &sc->func_obj;
4015     func_params.cmd = ECORE_F_CMD_HW_RESET;
4016 
4017     func_params.params.hw_init.load_phase = load_code;
4018 
4019     return (ecore_func_state_change(sc, &func_params));
4020 }
4021 
4022 static void
4023 bxe_int_disable_sync(struct bxe_softc *sc,
4024                      int              disable_hw)
4025 {
4026     if (disable_hw) {
4027         /* prevent the HW from sending interrupts */
4028         bxe_int_disable(sc);
4029     }
4030 
4031     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4032     /* make sure all ISRs are done */
4033 
4034     /* XXX make sure sp_task is not running */
4035     /* cancel and flush work queues */
4036 }
4037 
4038 static void
4039 bxe_chip_cleanup(struct bxe_softc *sc,
4040                  uint32_t         unload_mode,
4041                  uint8_t          keep_link)
4042 {
4043     int port = SC_PORT(sc);
4044     struct ecore_mcast_ramrod_params rparam = { NULL };
4045     uint32_t reset_code;
4046     int i, rc = 0;
4047 
4048     bxe_drain_tx_queues(sc);
4049 
4050     /* give HW time to discard old tx messages */
4051     DELAY(1000);
4052 
4053     /* Clean all ETH MACs */
4054     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4055     if (rc < 0) {
4056         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4057     }
4058 
4059     /* Clean up UC list  */
4060     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4061     if (rc < 0) {
4062         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4063     }
4064 
4065     /* Disable LLH */
4066     if (!CHIP_IS_E1(sc)) {
4067         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4068     }
4069 
4070     /* Set "drop all" to stop Rx */
4071 
4072     /*
4073      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4074      * a race between the completion code and this code.
4075      */
4076     BXE_MCAST_LOCK(sc);
4077 
4078     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4079         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4080     } else {
4081         bxe_set_storm_rx_mode(sc);
4082     }
4083 
4084     /* Clean up multicast configuration */
4085     rparam.mcast_obj = &sc->mcast_obj;
4086     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4087     if (rc < 0) {
4088         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4089     }
4090 
4091     BXE_MCAST_UNLOCK(sc);
4092 
4093     // XXX bxe_iov_chip_cleanup(sc);
4094 
4095     /*
4096      * Send the UNLOAD_REQUEST to the MCP. This will return if
4097      * this function should perform FUNCTION, PORT, or COMMON HW
4098      * reset.
4099      */
4100     reset_code = bxe_send_unload_req(sc, unload_mode);
4101 
4102     /*
4103      * (assumption: No Attention from MCP at this stage)
4104      * PMF probably in the middle of TX disable/enable transaction
4105      */
4106     rc = bxe_func_wait_started(sc);
4107     if (rc) {
4108         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4109     }
4110 
4111     /*
4112      * Close multi and leading connections
4113      * Completions for ramrods are collected in a synchronous way
4114      */
4115     for (i = 0; i < sc->num_queues; i++) {
4116         if (bxe_stop_queue(sc, i)) {
4117             goto unload_error;
4118         }
4119     }
4120 
4121     /*
4122      * If SP settings didn't get completed so far - something
4123      * very wrong has happen.
4124      */
4125     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4126         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4127     }
4128 
4129 unload_error:
4130 
4131     rc = bxe_func_stop(sc);
4132     if (rc) {
4133         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4134     }
4135 
4136     /* disable HW interrupts */
4137     bxe_int_disable_sync(sc, TRUE);
4138 
4139     /* detach interrupts */
4140     bxe_interrupt_detach(sc);
4141 
4142     /* Reset the chip */
4143     rc = bxe_reset_hw(sc, reset_code);
4144     if (rc) {
4145         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4146     }
4147 
4148     /* Report UNLOAD_DONE to MCP */
4149     bxe_send_unload_done(sc, keep_link);
4150 }
4151 
4152 static void
4153 bxe_disable_close_the_gate(struct bxe_softc *sc)
4154 {
4155     uint32_t val;
4156     int port = SC_PORT(sc);
4157 
4158     BLOGD(sc, DBG_LOAD,
4159           "Disabling 'close the gates'\n");
4160 
4161     if (CHIP_IS_E1(sc)) {
4162         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4163                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4164         val = REG_RD(sc, addr);
4165         val &= ~(0x300);
4166         REG_WR(sc, addr, val);
4167     } else {
4168         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4169         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4170                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4171         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4172     }
4173 }
4174 
4175 /*
4176  * Cleans the object that have internal lists without sending
4177  * ramrods. Should be run when interrutps are disabled.
4178  */
4179 static void
4180 bxe_squeeze_objects(struct bxe_softc *sc)
4181 {
4182     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4183     struct ecore_mcast_ramrod_params rparam = { NULL };
4184     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4185     int rc;
4186 
4187     /* Cleanup MACs' object first... */
4188 
4189     /* Wait for completion of requested */
4190     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4191     /* Perform a dry cleanup */
4192     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4193 
4194     /* Clean ETH primary MAC */
4195     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4196     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4197                              &ramrod_flags);
4198     if (rc != 0) {
4199         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4200     }
4201 
4202     /* Cleanup UC list */
4203     vlan_mac_flags = 0;
4204     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4205     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4206                              &ramrod_flags);
4207     if (rc != 0) {
4208         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4209     }
4210 
4211     /* Now clean mcast object... */
4212 
4213     rparam.mcast_obj = &sc->mcast_obj;
4214     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4215 
4216     /* Add a DEL command... */
4217     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4218     if (rc < 0) {
4219         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4220     }
4221 
4222     /* now wait until all pending commands are cleared */
4223 
4224     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4225     while (rc != 0) {
4226         if (rc < 0) {
4227             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4228             return;
4229         }
4230 
4231         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4232     }
4233 }
4234 
4235 /* stop the controller */
4236 static __noinline int
4237 bxe_nic_unload(struct bxe_softc *sc,
4238                uint32_t         unload_mode,
4239                uint8_t          keep_link)
4240 {
4241     uint8_t global = FALSE;
4242     uint32_t val;
4243     int i;
4244 
4245     BXE_CORE_LOCK_ASSERT(sc);
4246 
4247     if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4248 
4249     for (i = 0; i < sc->num_queues; i++) {
4250         struct bxe_fastpath *fp;
4251 
4252         fp = &sc->fp[i];
4253         BXE_FP_TX_LOCK(fp);
4254         BXE_FP_TX_UNLOCK(fp);
4255     }
4256 
4257     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4258 
4259     /* mark driver as unloaded in shmem2 */
4260     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4261         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4262         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4263                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4264     }
4265 
4266     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4267         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4268         /*
4269          * We can get here if the driver has been unloaded
4270          * during parity error recovery and is either waiting for a
4271          * leader to complete or for other functions to unload and
4272          * then ifconfig down has been issued. In this case we want to
4273          * unload and let other functions to complete a recovery
4274          * process.
4275          */
4276         sc->recovery_state = BXE_RECOVERY_DONE;
4277         sc->is_leader = 0;
4278         bxe_release_leader_lock(sc);
4279         mb();
4280 
4281         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4282         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4283             " state = 0x%x\n", sc->recovery_state, sc->state);
4284         return (-1);
4285     }
4286 
4287     /*
4288      * Nothing to do during unload if previous bxe_nic_load()
4289      * did not completed successfully - all resourses are released.
4290      */
4291     if ((sc->state == BXE_STATE_CLOSED) ||
4292         (sc->state == BXE_STATE_ERROR)) {
4293         return (0);
4294     }
4295 
4296     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4297     mb();
4298 
4299     /* stop tx */
4300     bxe_tx_disable(sc);
4301 
4302     sc->rx_mode = BXE_RX_MODE_NONE;
4303     /* XXX set rx mode ??? */
4304 
4305     if (IS_PF(sc) && !sc->grcdump_done) {
4306         /* set ALWAYS_ALIVE bit in shmem */
4307         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4308 
4309         bxe_drv_pulse(sc);
4310 
4311         bxe_stats_handle(sc, STATS_EVENT_STOP);
4312         bxe_save_statistics(sc);
4313     }
4314 
4315     /* wait till consumers catch up with producers in all queues */
4316     bxe_drain_tx_queues(sc);
4317 
4318     /* if VF indicate to PF this function is going down (PF will delete sp
4319      * elements and clear initializations
4320      */
4321     if (IS_VF(sc)) {
4322         ; /* bxe_vfpf_close_vf(sc); */
4323     } else if (unload_mode != UNLOAD_RECOVERY) {
4324         /* if this is a normal/close unload need to clean up chip */
4325         if (!sc->grcdump_done)
4326             bxe_chip_cleanup(sc, unload_mode, keep_link);
4327     } else {
4328         /* Send the UNLOAD_REQUEST to the MCP */
4329         bxe_send_unload_req(sc, unload_mode);
4330 
4331         /*
4332          * Prevent transactions to host from the functions on the
4333          * engine that doesn't reset global blocks in case of global
4334          * attention once gloabl blocks are reset and gates are opened
4335          * (the engine which leader will perform the recovery
4336          * last).
4337          */
4338         if (!CHIP_IS_E1x(sc)) {
4339             bxe_pf_disable(sc);
4340         }
4341 
4342         /* disable HW interrupts */
4343         bxe_int_disable_sync(sc, TRUE);
4344 
4345         /* detach interrupts */
4346         bxe_interrupt_detach(sc);
4347 
4348         /* Report UNLOAD_DONE to MCP */
4349         bxe_send_unload_done(sc, FALSE);
4350     }
4351 
4352     /*
4353      * At this stage no more interrupts will arrive so we may safely clean
4354      * the queue'able objects here in case they failed to get cleaned so far.
4355      */
4356     if (IS_PF(sc)) {
4357         bxe_squeeze_objects(sc);
4358     }
4359 
4360     /* There should be no more pending SP commands at this stage */
4361     sc->sp_state = 0;
4362 
4363     sc->port.pmf = 0;
4364 
4365     bxe_free_fp_buffers(sc);
4366 
4367     if (IS_PF(sc)) {
4368         bxe_free_mem(sc);
4369     }
4370 
4371     bxe_free_fw_stats_mem(sc);
4372 
4373     sc->state = BXE_STATE_CLOSED;
4374 
4375     /*
4376      * Check if there are pending parity attentions. If there are - set
4377      * RECOVERY_IN_PROGRESS.
4378      */
4379     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4380         bxe_set_reset_in_progress(sc);
4381 
4382         /* Set RESET_IS_GLOBAL if needed */
4383         if (global) {
4384             bxe_set_reset_global(sc);
4385         }
4386     }
4387 
4388     /*
4389      * The last driver must disable a "close the gate" if there is no
4390      * parity attention or "process kill" pending.
4391      */
4392     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4393         bxe_reset_is_done(sc, SC_PATH(sc))) {
4394         bxe_disable_close_the_gate(sc);
4395     }
4396 
4397     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4398 
4399     return (0);
4400 }
4401 
4402 /*
4403  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4404  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4405  */
4406 static int
4407 bxe_ifmedia_update(struct ifnet  *ifp)
4408 {
4409     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4410     struct ifmedia *ifm;
4411 
4412     ifm = &sc->ifmedia;
4413 
4414     /* We only support Ethernet media type. */
4415     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4416         return (EINVAL);
4417     }
4418 
4419     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4420     case IFM_AUTO:
4421          break;
4422     case IFM_10G_CX4:
4423     case IFM_10G_SR:
4424     case IFM_10G_T:
4425     case IFM_10G_TWINAX:
4426     default:
4427         /* We don't support changing the media type. */
4428         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4429               IFM_SUBTYPE(ifm->ifm_media));
4430         return (EINVAL);
4431     }
4432 
4433     return (0);
4434 }
4435 
4436 /*
4437  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4438  */
4439 static void
4440 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4441 {
4442     struct bxe_softc *sc = if_getsoftc(ifp);
4443 
4444     /* Report link down if the driver isn't running. */
4445     if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4446         ifmr->ifm_active |= IFM_NONE;
4447         return;
4448     }
4449 
4450     /* Setup the default interface info. */
4451     ifmr->ifm_status = IFM_AVALID;
4452     ifmr->ifm_active = IFM_ETHER;
4453 
4454     if (sc->link_vars.link_up) {
4455         ifmr->ifm_status |= IFM_ACTIVE;
4456     } else {
4457         ifmr->ifm_active |= IFM_NONE;
4458         return;
4459     }
4460 
4461     ifmr->ifm_active |= sc->media;
4462 
4463     if (sc->link_vars.duplex == DUPLEX_FULL) {
4464         ifmr->ifm_active |= IFM_FDX;
4465     } else {
4466         ifmr->ifm_active |= IFM_HDX;
4467     }
4468 }
4469 
4470 static void
4471 bxe_handle_chip_tq(void *context,
4472                    int  pending)
4473 {
4474     struct bxe_softc *sc = (struct bxe_softc *)context;
4475     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4476 
4477     switch (work)
4478     {
4479 
4480     case CHIP_TQ_REINIT:
4481         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4482             /* restart the interface */
4483             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4484             bxe_periodic_stop(sc);
4485             BXE_CORE_LOCK(sc);
4486             bxe_stop_locked(sc);
4487             bxe_init_locked(sc);
4488             BXE_CORE_UNLOCK(sc);
4489         }
4490         break;
4491 
4492     default:
4493         break;
4494     }
4495 }
4496 
4497 /*
4498  * Handles any IOCTL calls from the operating system.
4499  *
4500  * Returns:
4501  *   0 = Success, >0 Failure
4502  */
4503 static int
4504 bxe_ioctl(if_t ifp,
4505           u_long       command,
4506           caddr_t      data)
4507 {
4508     struct bxe_softc *sc = if_getsoftc(ifp);
4509     struct ifreq *ifr = (struct ifreq *)data;
4510     int mask = 0;
4511     int reinit = 0;
4512     int error = 0;
4513 
4514     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4515     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4516 
4517     switch (command)
4518     {
4519     case SIOCSIFMTU:
4520         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4521               ifr->ifr_mtu);
4522 
4523         if (sc->mtu == ifr->ifr_mtu) {
4524             /* nothing to change */
4525             break;
4526         }
4527 
4528         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4529             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4530                   ifr->ifr_mtu, mtu_min, mtu_max);
4531             error = EINVAL;
4532             break;
4533         }
4534 
4535         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4536                              (unsigned long)ifr->ifr_mtu);
4537 	/*
4538         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4539                               (unsigned long)ifr->ifr_mtu);
4540 	XXX - Not sure why it needs to be atomic
4541 	*/
4542 	if_setmtu(ifp, ifr->ifr_mtu);
4543         reinit = 1;
4544         break;
4545 
4546     case SIOCSIFFLAGS:
4547         /* toggle the interface state up or down */
4548         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4549 
4550 	BXE_CORE_LOCK(sc);
4551         /* check if the interface is up */
4552         if (if_getflags(ifp) & IFF_UP) {
4553             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4554                 /* set the receive mode flags */
4555                 bxe_set_rx_mode(sc);
4556             } else if(sc->state != BXE_STATE_DISABLED) {
4557 		bxe_init_locked(sc);
4558             }
4559         } else {
4560             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4561 		bxe_periodic_stop(sc);
4562 		bxe_stop_locked(sc);
4563             }
4564         }
4565 	BXE_CORE_UNLOCK(sc);
4566 
4567         break;
4568 
4569     case SIOCADDMULTI:
4570     case SIOCDELMULTI:
4571         /* add/delete multicast addresses */
4572         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4573 
4574         /* check if the interface is up */
4575         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4576             /* set the receive mode flags */
4577 	    BXE_CORE_LOCK(sc);
4578             bxe_set_rx_mode(sc);
4579 	    BXE_CORE_UNLOCK(sc);
4580         }
4581 
4582         break;
4583 
4584     case SIOCSIFCAP:
4585         /* find out which capabilities have changed */
4586         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4587 
4588         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4589               mask);
4590 
4591         /* toggle the LRO capabilites enable flag */
4592         if (mask & IFCAP_LRO) {
4593 	    if_togglecapenable(ifp, IFCAP_LRO);
4594             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4595                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4596             reinit = 1;
4597         }
4598 
4599         /* toggle the TXCSUM checksum capabilites enable flag */
4600         if (mask & IFCAP_TXCSUM) {
4601 	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4602             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4603                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4604             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4605                 if_sethwassistbits(ifp, (CSUM_IP      |
4606                                     CSUM_TCP      |
4607                                     CSUM_UDP      |
4608                                     CSUM_TSO      |
4609                                     CSUM_TCP_IPV6 |
4610                                     CSUM_UDP_IPV6), 0);
4611             } else {
4612 		if_clearhwassist(ifp); /* XXX */
4613             }
4614         }
4615 
4616         /* toggle the RXCSUM checksum capabilities enable flag */
4617         if (mask & IFCAP_RXCSUM) {
4618 	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4619             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4620                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4621             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4622                 if_sethwassistbits(ifp, (CSUM_IP      |
4623                                     CSUM_TCP      |
4624                                     CSUM_UDP      |
4625                                     CSUM_TSO      |
4626                                     CSUM_TCP_IPV6 |
4627                                     CSUM_UDP_IPV6), 0);
4628             } else {
4629 		if_clearhwassist(ifp); /* XXX */
4630             }
4631         }
4632 
4633         /* toggle TSO4 capabilities enabled flag */
4634         if (mask & IFCAP_TSO4) {
4635             if_togglecapenable(ifp, IFCAP_TSO4);
4636             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4637                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4638         }
4639 
4640         /* toggle TSO6 capabilities enabled flag */
4641         if (mask & IFCAP_TSO6) {
4642 	    if_togglecapenable(ifp, IFCAP_TSO6);
4643             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4644                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4645         }
4646 
4647         /* toggle VLAN_HWTSO capabilities enabled flag */
4648         if (mask & IFCAP_VLAN_HWTSO) {
4649 
4650 	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4651             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4652                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4653         }
4654 
4655         /* toggle VLAN_HWCSUM capabilities enabled flag */
4656         if (mask & IFCAP_VLAN_HWCSUM) {
4657             /* XXX investigate this... */
4658             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4659             error = EINVAL;
4660         }
4661 
4662         /* toggle VLAN_MTU capabilities enable flag */
4663         if (mask & IFCAP_VLAN_MTU) {
4664             /* XXX investigate this... */
4665             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4666             error = EINVAL;
4667         }
4668 
4669         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4670         if (mask & IFCAP_VLAN_HWTAGGING) {
4671             /* XXX investigate this... */
4672             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4673             error = EINVAL;
4674         }
4675 
4676         /* toggle VLAN_HWFILTER capabilities enabled flag */
4677         if (mask & IFCAP_VLAN_HWFILTER) {
4678             /* XXX investigate this... */
4679             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4680             error = EINVAL;
4681         }
4682 
4683         /* XXX not yet...
4684          * IFCAP_WOL_MAGIC
4685          */
4686 
4687         break;
4688 
4689     case SIOCSIFMEDIA:
4690     case SIOCGIFMEDIA:
4691         /* set/get interface media */
4692         BLOGD(sc, DBG_IOCTL,
4693               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4694               (command & 0xff));
4695         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4696         break;
4697 
4698     default:
4699         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4700               (command & 0xff));
4701         error = ether_ioctl(ifp, command, data);
4702         break;
4703     }
4704 
4705     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4706         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4707               "Re-initializing hardware from IOCTL change\n");
4708 	bxe_periodic_stop(sc);
4709 	BXE_CORE_LOCK(sc);
4710 	bxe_stop_locked(sc);
4711 	bxe_init_locked(sc);
4712 	BXE_CORE_UNLOCK(sc);
4713     }
4714 
4715     return (error);
4716 }
4717 
4718 static __noinline void
4719 bxe_dump_mbuf(struct bxe_softc *sc,
4720               struct mbuf      *m,
4721               uint8_t          contents)
4722 {
4723     char * type;
4724     int i = 0;
4725 
4726     if (!(sc->debug & DBG_MBUF)) {
4727         return;
4728     }
4729 
4730     if (m == NULL) {
4731         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4732         return;
4733     }
4734 
4735     while (m) {
4736 
4737 #if __FreeBSD_version >= 1000000
4738         BLOGD(sc, DBG_MBUF,
4739               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4740               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4741 
4742         if (m->m_flags & M_PKTHDR) {
4743              BLOGD(sc, DBG_MBUF,
4744                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4745                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4746                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4747         }
4748 #else
4749         BLOGD(sc, DBG_MBUF,
4750               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4751               i, m, m->m_len, m->m_flags,
4752               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4753 
4754         if (m->m_flags & M_PKTHDR) {
4755              BLOGD(sc, DBG_MBUF,
4756                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4757                    i, m->m_pkthdr.len, m->m_flags,
4758                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4759                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4760                    "\22M_PROMISC\23M_NOFREE",
4761                    (int)m->m_pkthdr.csum_flags,
4762                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4763                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4764                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4765                    "\14CSUM_PSEUDO_HDR");
4766         }
4767 #endif /* #if __FreeBSD_version >= 1000000 */
4768 
4769         if (m->m_flags & M_EXT) {
4770             switch (m->m_ext.ext_type) {
4771             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4772             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4773             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4774             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4775             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4776             case EXT_PACKET:     type = "EXT_PACKET";     break;
4777             case EXT_MBUF:       type = "EXT_MBUF";       break;
4778             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4779             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4780             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4781             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4782             default:             type = "UNKNOWN";        break;
4783             }
4784 
4785             BLOGD(sc, DBG_MBUF,
4786                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4787                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4788         }
4789 
4790         if (contents) {
4791             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4792         }
4793 
4794         m = m->m_next;
4795         i++;
4796     }
4797 }
4798 
4799 /*
4800  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4801  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4802  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4803  * The headers comes in a separate bd in FreeBSD so 13-3=10.
4804  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4805  */
4806 static int
4807 bxe_chktso_window(struct bxe_softc  *sc,
4808                   int               nsegs,
4809                   bus_dma_segment_t *segs,
4810                   struct mbuf       *m)
4811 {
4812     uint32_t num_wnds, wnd_size, wnd_sum;
4813     int32_t frag_idx, wnd_idx;
4814     unsigned short lso_mss;
4815     int defrag;
4816 
4817     defrag = 0;
4818     wnd_sum = 0;
4819     wnd_size = 10;
4820     num_wnds = nsegs - wnd_size;
4821     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4822 
4823     /*
4824      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4825      * first window sum of data while skipping the first assuming it is the
4826      * header in FreeBSD.
4827      */
4828     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4829         wnd_sum += htole16(segs[frag_idx].ds_len);
4830     }
4831 
4832     /* check the first 10 bd window size */
4833     if (wnd_sum < lso_mss) {
4834         return (1);
4835     }
4836 
4837     /* run through the windows */
4838     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4839         /* subtract the first mbuf->m_len of the last wndw(-header) */
4840         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4841         /* add the next mbuf len to the len of our new window */
4842         wnd_sum += htole16(segs[frag_idx].ds_len);
4843         if (wnd_sum < lso_mss) {
4844             return (1);
4845         }
4846     }
4847 
4848     return (0);
4849 }
4850 
4851 static uint8_t
4852 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4853                     struct mbuf         *m,
4854                     uint32_t            *parsing_data)
4855 {
4856     struct ether_vlan_header *eh = NULL;
4857     struct ip *ip4 = NULL;
4858     struct ip6_hdr *ip6 = NULL;
4859     caddr_t ip = NULL;
4860     struct tcphdr *th = NULL;
4861     int e_hlen, ip_hlen, l4_off;
4862     uint16_t proto;
4863 
4864     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4865         /* no L4 checksum offload needed */
4866         return (0);
4867     }
4868 
4869     /* get the Ethernet header */
4870     eh = mtod(m, struct ether_vlan_header *);
4871 
4872     /* handle VLAN encapsulation if present */
4873     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4874         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4875         proto  = ntohs(eh->evl_proto);
4876     } else {
4877         e_hlen = ETHER_HDR_LEN;
4878         proto  = ntohs(eh->evl_encap_proto);
4879     }
4880 
4881     switch (proto) {
4882     case ETHERTYPE_IP:
4883         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4884         ip4 = (m->m_len < sizeof(struct ip)) ?
4885                   (struct ip *)m->m_next->m_data :
4886                   (struct ip *)(m->m_data + e_hlen);
4887         /* ip_hl is number of 32-bit words */
4888         ip_hlen = (ip4->ip_hl << 2);
4889         ip = (caddr_t)ip4;
4890         break;
4891     case ETHERTYPE_IPV6:
4892         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4893         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4894                   (struct ip6_hdr *)m->m_next->m_data :
4895                   (struct ip6_hdr *)(m->m_data + e_hlen);
4896         /* XXX cannot support offload with IPv6 extensions */
4897         ip_hlen = sizeof(struct ip6_hdr);
4898         ip = (caddr_t)ip6;
4899         break;
4900     default:
4901         /* We can't offload in this case... */
4902         /* XXX error stat ??? */
4903         return (0);
4904     }
4905 
4906     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4907     l4_off = (e_hlen + ip_hlen);
4908 
4909     *parsing_data |=
4910         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4911          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4912 
4913     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4914                                   CSUM_TSO |
4915                                   CSUM_TCP_IPV6)) {
4916         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4917         th = (struct tcphdr *)(ip + ip_hlen);
4918         /* th_off is number of 32-bit words */
4919         *parsing_data |= ((th->th_off <<
4920                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4921                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4922         return (l4_off + (th->th_off << 2)); /* entire header length */
4923     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4924                                          CSUM_UDP_IPV6)) {
4925         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4926         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4927     } else {
4928         /* XXX error stat ??? */
4929         return (0);
4930     }
4931 }
4932 
4933 static uint8_t
4934 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4935                  struct mbuf                *m,
4936                  struct eth_tx_parse_bd_e1x *pbd)
4937 {
4938     struct ether_vlan_header *eh = NULL;
4939     struct ip *ip4 = NULL;
4940     struct ip6_hdr *ip6 = NULL;
4941     caddr_t ip = NULL;
4942     struct tcphdr *th = NULL;
4943     struct udphdr *uh = NULL;
4944     int e_hlen, ip_hlen;
4945     uint16_t proto;
4946     uint8_t hlen;
4947     uint16_t tmp_csum;
4948     uint32_t *tmp_uh;
4949 
4950     /* get the Ethernet header */
4951     eh = mtod(m, struct ether_vlan_header *);
4952 
4953     /* handle VLAN encapsulation if present */
4954     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4955         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4956         proto  = ntohs(eh->evl_proto);
4957     } else {
4958         e_hlen = ETHER_HDR_LEN;
4959         proto  = ntohs(eh->evl_encap_proto);
4960     }
4961 
4962     switch (proto) {
4963     case ETHERTYPE_IP:
4964         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4965         ip4 = (m->m_len < sizeof(struct ip)) ?
4966                   (struct ip *)m->m_next->m_data :
4967                   (struct ip *)(m->m_data + e_hlen);
4968         /* ip_hl is number of 32-bit words */
4969         ip_hlen = (ip4->ip_hl << 1);
4970         ip = (caddr_t)ip4;
4971         break;
4972     case ETHERTYPE_IPV6:
4973         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4974         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4975                   (struct ip6_hdr *)m->m_next->m_data :
4976                   (struct ip6_hdr *)(m->m_data + e_hlen);
4977         /* XXX cannot support offload with IPv6 extensions */
4978         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4979         ip = (caddr_t)ip6;
4980         break;
4981     default:
4982         /* We can't offload in this case... */
4983         /* XXX error stat ??? */
4984         return (0);
4985     }
4986 
4987     hlen = (e_hlen >> 1);
4988 
4989     /* note that rest of global_data is indirectly zeroed here */
4990     if (m->m_flags & M_VLANTAG) {
4991         pbd->global_data =
4992             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4993     } else {
4994         pbd->global_data = htole16(hlen);
4995     }
4996 
4997     pbd->ip_hlen_w = ip_hlen;
4998 
4999     hlen += pbd->ip_hlen_w;
5000 
5001     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5002 
5003     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5004                                   CSUM_TSO |
5005                                   CSUM_TCP_IPV6)) {
5006         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5007         /* th_off is number of 32-bit words */
5008         hlen += (uint16_t)(th->th_off << 1);
5009     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5010                                          CSUM_UDP_IPV6)) {
5011         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5012         hlen += (sizeof(struct udphdr) / 2);
5013     } else {
5014         /* valid case as only CSUM_IP was set */
5015         return (0);
5016     }
5017 
5018     pbd->total_hlen_w = htole16(hlen);
5019 
5020     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5021                                   CSUM_TSO |
5022                                   CSUM_TCP_IPV6)) {
5023         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5024         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5025     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5026                                          CSUM_UDP_IPV6)) {
5027         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5028 
5029         /*
5030          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5031          * checksums and does not know anything about the UDP header and where
5032          * the checksum field is located. It only knows about TCP. Therefore
5033          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5034          * offload. Since the checksum field offset for TCP is 16 bytes and
5035          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5036          * bytes less than the start of the UDP header. This allows the
5037          * hardware to write the checksum in the correct spot. But the
5038          * hardware will compute a checksum which includes the last 10 bytes
5039          * of the IP header. To correct this we tweak the stack computed
5040          * pseudo checksum by folding in the calculation of the inverse
5041          * checksum for those final 10 bytes of the IP header. This allows
5042          * the correct checksum to be computed by the hardware.
5043          */
5044 
5045         /* set pointer 10 bytes before UDP header */
5046         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5047 
5048         /* calculate a pseudo header checksum over the first 10 bytes */
5049         tmp_csum = in_pseudo(*tmp_uh,
5050                              *(tmp_uh + 1),
5051                              *(uint16_t *)(tmp_uh + 2));
5052 
5053         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5054     }
5055 
5056     return (hlen * 2); /* entire header length, number of bytes */
5057 }
5058 
5059 static void
5060 bxe_set_pbd_lso_e2(struct mbuf *m,
5061                    uint32_t    *parsing_data)
5062 {
5063     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5064                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5065                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5066 
5067     /* XXX test for IPv6 with extension header... */
5068 }
5069 
5070 static void
5071 bxe_set_pbd_lso(struct mbuf                *m,
5072                 struct eth_tx_parse_bd_e1x *pbd)
5073 {
5074     struct ether_vlan_header *eh = NULL;
5075     struct ip *ip = NULL;
5076     struct tcphdr *th = NULL;
5077     int e_hlen;
5078 
5079     /* get the Ethernet header */
5080     eh = mtod(m, struct ether_vlan_header *);
5081 
5082     /* handle VLAN encapsulation if present */
5083     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5084                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5085 
5086     /* get the IP and TCP header, with LSO entire header in first mbuf */
5087     /* XXX assuming IPv4 */
5088     ip = (struct ip *)(m->m_data + e_hlen);
5089     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5090 
5091     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5092     pbd->tcp_send_seq = ntohl(th->th_seq);
5093     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5094 
5095 #if 1
5096         /* XXX IPv4 */
5097         pbd->ip_id = ntohs(ip->ip_id);
5098         pbd->tcp_pseudo_csum =
5099             ntohs(in_pseudo(ip->ip_src.s_addr,
5100                             ip->ip_dst.s_addr,
5101                             htons(IPPROTO_TCP)));
5102 #else
5103         /* XXX IPv6 */
5104         pbd->tcp_pseudo_csum =
5105             ntohs(in_pseudo(&ip6->ip6_src,
5106                             &ip6->ip6_dst,
5107                             htons(IPPROTO_TCP)));
5108 #endif
5109 
5110     pbd->global_data |=
5111         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5112 }
5113 
5114 /*
5115  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5116  * visible to the controller.
5117  *
5118  * If an mbuf is submitted to this routine and cannot be given to the
5119  * controller (e.g. it has too many fragments) then the function may free
5120  * the mbuf and return to the caller.
5121  *
5122  * Returns:
5123  *   0 = Success, !0 = Failure
5124  *   Note the side effect that an mbuf may be freed if it causes a problem.
5125  */
5126 static int
5127 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5128 {
5129     bus_dma_segment_t segs[32];
5130     struct mbuf *m0;
5131     struct bxe_sw_tx_bd *tx_buf;
5132     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5133     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5134     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5135     struct eth_tx_bd *tx_data_bd;
5136     struct eth_tx_bd *tx_total_pkt_size_bd;
5137     struct eth_tx_start_bd *tx_start_bd;
5138     uint16_t bd_prod, pkt_prod, total_pkt_size;
5139     uint8_t mac_type;
5140     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5141     struct bxe_softc *sc;
5142     uint16_t tx_bd_avail;
5143     struct ether_vlan_header *eh;
5144     uint32_t pbd_e2_parsing_data = 0;
5145     uint8_t hlen = 0;
5146     int tmp_bd;
5147     int i;
5148 
5149     sc = fp->sc;
5150 
5151 #if __FreeBSD_version >= 800000
5152     M_ASSERTPKTHDR(*m_head);
5153 #endif /* #if __FreeBSD_version >= 800000 */
5154 
5155     m0 = *m_head;
5156     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5157     tx_start_bd = NULL;
5158     tx_data_bd = NULL;
5159     tx_total_pkt_size_bd = NULL;
5160 
5161     /* get the H/W pointer for packets and BDs */
5162     pkt_prod = fp->tx_pkt_prod;
5163     bd_prod = fp->tx_bd_prod;
5164 
5165     mac_type = UNICAST_ADDRESS;
5166 
5167     /* map the mbuf into the next open DMAable memory */
5168     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5169     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5170                                     tx_buf->m_map, m0,
5171                                     segs, &nsegs, BUS_DMA_NOWAIT);
5172 
5173     /* mapping errors */
5174     if(__predict_false(error != 0)) {
5175         fp->eth_q_stats.tx_dma_mapping_failure++;
5176         if (error == ENOMEM) {
5177             /* resource issue, try again later */
5178             rc = ENOMEM;
5179         } else if (error == EFBIG) {
5180             /* possibly recoverable with defragmentation */
5181             fp->eth_q_stats.mbuf_defrag_attempts++;
5182             m0 = m_defrag(*m_head, M_NOWAIT);
5183             if (m0 == NULL) {
5184                 fp->eth_q_stats.mbuf_defrag_failures++;
5185                 rc = ENOBUFS;
5186             } else {
5187                 /* defrag successful, try mapping again */
5188                 *m_head = m0;
5189                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5190                                                 tx_buf->m_map, m0,
5191                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5192                 if (error) {
5193                     fp->eth_q_stats.tx_dma_mapping_failure++;
5194                     rc = error;
5195                 }
5196             }
5197         } else {
5198             /* unknown, unrecoverable mapping error */
5199             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5200             bxe_dump_mbuf(sc, m0, FALSE);
5201             rc = error;
5202         }
5203 
5204         goto bxe_tx_encap_continue;
5205     }
5206 
5207     tx_bd_avail = bxe_tx_avail(sc, fp);
5208 
5209     /* make sure there is enough room in the send queue */
5210     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5211         /* Recoverable, try again later. */
5212         fp->eth_q_stats.tx_hw_queue_full++;
5213         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5214         rc = ENOMEM;
5215         goto bxe_tx_encap_continue;
5216     }
5217 
5218     /* capture the current H/W TX chain high watermark */
5219     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5220                         (TX_BD_USABLE - tx_bd_avail))) {
5221         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5222     }
5223 
5224     /* make sure it fits in the packet window */
5225     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5226         /*
5227          * The mbuf may be to big for the controller to handle. If the frame
5228          * is a TSO frame we'll need to do an additional check.
5229          */
5230         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5231             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5232                 goto bxe_tx_encap_continue; /* OK to send */
5233             } else {
5234                 fp->eth_q_stats.tx_window_violation_tso++;
5235             }
5236         } else {
5237             fp->eth_q_stats.tx_window_violation_std++;
5238         }
5239 
5240         /* lets try to defragment this mbuf and remap it */
5241         fp->eth_q_stats.mbuf_defrag_attempts++;
5242         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5243 
5244         m0 = m_defrag(*m_head, M_NOWAIT);
5245         if (m0 == NULL) {
5246             fp->eth_q_stats.mbuf_defrag_failures++;
5247             /* Ugh, just drop the frame... :( */
5248             rc = ENOBUFS;
5249         } else {
5250             /* defrag successful, try mapping again */
5251             *m_head = m0;
5252             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5253                                             tx_buf->m_map, m0,
5254                                             segs, &nsegs, BUS_DMA_NOWAIT);
5255             if (error) {
5256                 fp->eth_q_stats.tx_dma_mapping_failure++;
5257                 /* No sense in trying to defrag/copy chain, drop it. :( */
5258                 rc = error;
5259             } else {
5260                /* if the chain is still too long then drop it */
5261                 if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5262                     /*
5263                      * in case TSO is enabled nsegs should be checked against
5264                      * BXE_TSO_MAX_SEGMENTS
5265                      */
5266                     if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5267                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5268                         fp->eth_q_stats.nsegs_path1_errors++;
5269                         rc = ENODEV;
5270                     }
5271                 } else {
5272                     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5273                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5274                         fp->eth_q_stats.nsegs_path2_errors++;
5275                         rc = ENODEV;
5276                     }
5277                 }
5278             }
5279         }
5280     }
5281 
5282 bxe_tx_encap_continue:
5283 
5284     /* Check for errors */
5285     if (rc) {
5286         if (rc == ENOMEM) {
5287             /* recoverable try again later  */
5288         } else {
5289             fp->eth_q_stats.tx_soft_errors++;
5290             fp->eth_q_stats.mbuf_alloc_tx--;
5291             m_freem(*m_head);
5292             *m_head = NULL;
5293         }
5294 
5295         return (rc);
5296     }
5297 
5298     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5299     if (m0->m_flags & M_BCAST) {
5300         mac_type = BROADCAST_ADDRESS;
5301     } else if (m0->m_flags & M_MCAST) {
5302         mac_type = MULTICAST_ADDRESS;
5303     }
5304 
5305     /* store the mbuf into the mbuf ring */
5306     tx_buf->m        = m0;
5307     tx_buf->first_bd = fp->tx_bd_prod;
5308     tx_buf->flags    = 0;
5309 
5310     /* prepare the first transmit (start) BD for the mbuf */
5311     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5312 
5313     BLOGD(sc, DBG_TX,
5314           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5315           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5316 
5317     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5318     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5319     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5320     total_pkt_size += tx_start_bd->nbytes;
5321     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5322 
5323     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5324 
5325     /* all frames have at least Start BD + Parsing BD */
5326     nbds = nsegs + 1;
5327     tx_start_bd->nbd = htole16(nbds);
5328 
5329     if (m0->m_flags & M_VLANTAG) {
5330         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5331         tx_start_bd->bd_flags.as_bitfield |=
5332             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5333     } else {
5334         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5335         if (IS_VF(sc)) {
5336             /* map ethernet header to find type and header length */
5337             eh = mtod(m0, struct ether_vlan_header *);
5338             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5339         } else {
5340             /* used by FW for packet accounting */
5341             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5342         }
5343     }
5344 
5345     /*
5346      * add a parsing BD from the chain. The parsing BD is always added
5347      * though it is only used for TSO and chksum
5348      */
5349     bd_prod = TX_BD_NEXT(bd_prod);
5350 
5351     if (m0->m_pkthdr.csum_flags) {
5352         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5353             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5354             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5355         }
5356 
5357         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5358             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5359                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5360         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5361             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5362                                                   ETH_TX_BD_FLAGS_IS_UDP |
5363                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5364         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5365                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5366             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5367         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5368             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5369                                                   ETH_TX_BD_FLAGS_IS_UDP);
5370         }
5371     }
5372 
5373     if (!CHIP_IS_E1x(sc)) {
5374         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5375         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5376 
5377         if (m0->m_pkthdr.csum_flags) {
5378             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5379         }
5380 
5381         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5382                  mac_type);
5383     } else {
5384         uint16_t global_data = 0;
5385 
5386         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5387         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5388 
5389         if (m0->m_pkthdr.csum_flags) {
5390             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5391         }
5392 
5393         SET_FLAG(global_data,
5394                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5395         pbd_e1x->global_data |= htole16(global_data);
5396     }
5397 
5398     /* setup the parsing BD with TSO specific info */
5399     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5400         fp->eth_q_stats.tx_ofld_frames_lso++;
5401         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5402 
5403         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5404             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5405 
5406             /* split the first BD into header/data making the fw job easy */
5407             nbds++;
5408             tx_start_bd->nbd = htole16(nbds);
5409             tx_start_bd->nbytes = htole16(hlen);
5410 
5411             bd_prod = TX_BD_NEXT(bd_prod);
5412 
5413             /* new transmit BD after the tx_parse_bd */
5414             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5415             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5416             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5417             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5418             if (tx_total_pkt_size_bd == NULL) {
5419                 tx_total_pkt_size_bd = tx_data_bd;
5420             }
5421 
5422             BLOGD(sc, DBG_TX,
5423                   "TSO split header size is %d (%x:%x) nbds %d\n",
5424                   le16toh(tx_start_bd->nbytes),
5425                   le32toh(tx_start_bd->addr_hi),
5426                   le32toh(tx_start_bd->addr_lo),
5427                   nbds);
5428         }
5429 
5430         if (!CHIP_IS_E1x(sc)) {
5431             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5432         } else {
5433             bxe_set_pbd_lso(m0, pbd_e1x);
5434         }
5435     }
5436 
5437     if (pbd_e2_parsing_data) {
5438         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5439     }
5440 
5441     /* prepare remaining BDs, start tx bd contains first seg/frag */
5442     for (i = 1; i < nsegs ; i++) {
5443         bd_prod = TX_BD_NEXT(bd_prod);
5444         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5445         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5446         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5447         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5448         if (tx_total_pkt_size_bd == NULL) {
5449             tx_total_pkt_size_bd = tx_data_bd;
5450         }
5451         total_pkt_size += tx_data_bd->nbytes;
5452     }
5453 
5454     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5455 
5456     if (tx_total_pkt_size_bd != NULL) {
5457         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5458     }
5459 
5460     if (__predict_false(sc->debug & DBG_TX)) {
5461         tmp_bd = tx_buf->first_bd;
5462         for (i = 0; i < nbds; i++)
5463         {
5464             if (i == 0) {
5465                 BLOGD(sc, DBG_TX,
5466                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5467                       "bd_flags=0x%x hdr_nbds=%d\n",
5468                       tx_start_bd,
5469                       tmp_bd,
5470                       le16toh(tx_start_bd->nbd),
5471                       le16toh(tx_start_bd->vlan_or_ethertype),
5472                       tx_start_bd->bd_flags.as_bitfield,
5473                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5474             } else if (i == 1) {
5475                 if (pbd_e1x) {
5476                     BLOGD(sc, DBG_TX,
5477                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5478                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5479                           "tcp_seq=%u total_hlen_w=%u\n",
5480                           pbd_e1x,
5481                           tmp_bd,
5482                           pbd_e1x->global_data,
5483                           pbd_e1x->ip_hlen_w,
5484                           pbd_e1x->ip_id,
5485                           pbd_e1x->lso_mss,
5486                           pbd_e1x->tcp_flags,
5487                           pbd_e1x->tcp_pseudo_csum,
5488                           pbd_e1x->tcp_send_seq,
5489                           le16toh(pbd_e1x->total_hlen_w));
5490                 } else { /* if (pbd_e2) */
5491                     BLOGD(sc, DBG_TX,
5492                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5493                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5494                           pbd_e2,
5495                           tmp_bd,
5496                           pbd_e2->data.mac_addr.dst_hi,
5497                           pbd_e2->data.mac_addr.dst_mid,
5498                           pbd_e2->data.mac_addr.dst_lo,
5499                           pbd_e2->data.mac_addr.src_hi,
5500                           pbd_e2->data.mac_addr.src_mid,
5501                           pbd_e2->data.mac_addr.src_lo,
5502                           pbd_e2->parsing_data);
5503                 }
5504             }
5505 
5506             if (i != 1) { /* skip parse db as it doesn't hold data */
5507                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5508                 BLOGD(sc, DBG_TX,
5509                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5510                       tx_data_bd,
5511                       tmp_bd,
5512                       le16toh(tx_data_bd->nbytes),
5513                       le32toh(tx_data_bd->addr_hi),
5514                       le32toh(tx_data_bd->addr_lo));
5515             }
5516 
5517             tmp_bd = TX_BD_NEXT(tmp_bd);
5518         }
5519     }
5520 
5521     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5522 
5523     /* update TX BD producer index value for next TX */
5524     bd_prod = TX_BD_NEXT(bd_prod);
5525 
5526     /*
5527      * If the chain of tx_bd's describing this frame is adjacent to or spans
5528      * an eth_tx_next_bd element then we need to increment the nbds value.
5529      */
5530     if (TX_BD_IDX(bd_prod) < nbds) {
5531         nbds++;
5532     }
5533 
5534     /* don't allow reordering of writes for nbd and packets */
5535     mb();
5536 
5537     fp->tx_db.data.prod += nbds;
5538 
5539     /* producer points to the next free tx_bd at this point */
5540     fp->tx_pkt_prod++;
5541     fp->tx_bd_prod = bd_prod;
5542 
5543     DOORBELL(sc, fp->index, fp->tx_db.raw);
5544 
5545     fp->eth_q_stats.tx_pkts++;
5546 
5547     /* Prevent speculative reads from getting ahead of the status block. */
5548     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5549                       0, 0, BUS_SPACE_BARRIER_READ);
5550 
5551     /* Prevent speculative reads from getting ahead of the doorbell. */
5552     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5553                       0, 0, BUS_SPACE_BARRIER_READ);
5554 
5555     return (0);
5556 }
5557 
5558 static void
5559 bxe_tx_start_locked(struct bxe_softc *sc,
5560                     if_t ifp,
5561                     struct bxe_fastpath *fp)
5562 {
5563     struct mbuf *m = NULL;
5564     int tx_count = 0;
5565     uint16_t tx_bd_avail;
5566 
5567     BXE_FP_TX_LOCK_ASSERT(fp);
5568 
5569     /* keep adding entries while there are frames to send */
5570     while (!if_sendq_empty(ifp)) {
5571 
5572         /*
5573          * check for any frames to send
5574          * dequeue can still be NULL even if queue is not empty
5575          */
5576         m = if_dequeue(ifp);
5577         if (__predict_false(m == NULL)) {
5578             break;
5579         }
5580 
5581         /* the mbuf now belongs to us */
5582         fp->eth_q_stats.mbuf_alloc_tx++;
5583 
5584         /*
5585          * Put the frame into the transmit ring. If we don't have room,
5586          * place the mbuf back at the head of the TX queue, set the
5587          * OACTIVE flag, and wait for the NIC to drain the chain.
5588          */
5589         if (__predict_false(bxe_tx_encap(fp, &m))) {
5590             fp->eth_q_stats.tx_encap_failures++;
5591             if (m != NULL) {
5592                 /* mark the TX queue as full and return the frame */
5593                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5594 		if_sendq_prepend(ifp, m);
5595                 fp->eth_q_stats.mbuf_alloc_tx--;
5596                 fp->eth_q_stats.tx_queue_xoff++;
5597             }
5598 
5599             /* stop looking for more work */
5600             break;
5601         }
5602 
5603         /* the frame was enqueued successfully */
5604         tx_count++;
5605 
5606         /* send a copy of the frame to any BPF listeners. */
5607         if_etherbpfmtap(ifp, m);
5608 
5609         tx_bd_avail = bxe_tx_avail(sc, fp);
5610 
5611         /* handle any completions if we're running low */
5612         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5613             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5614             bxe_txeof(sc, fp);
5615             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5616                 break;
5617             }
5618         }
5619     }
5620 
5621     /* all TX packets were dequeued and/or the tx ring is full */
5622     if (tx_count > 0) {
5623         /* reset the TX watchdog timeout timer */
5624         fp->watchdog_timer = BXE_TX_TIMEOUT;
5625     }
5626 }
5627 
5628 /* Legacy (non-RSS) dispatch routine */
5629 static void
5630 bxe_tx_start(if_t ifp)
5631 {
5632     struct bxe_softc *sc;
5633     struct bxe_fastpath *fp;
5634 
5635     sc = if_getsoftc(ifp);
5636 
5637     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5638         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5639         return;
5640     }
5641 
5642     if (!sc->link_vars.link_up) {
5643         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5644         return;
5645     }
5646 
5647     fp = &sc->fp[0];
5648 
5649     if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5650         fp->eth_q_stats.tx_queue_full_return++;
5651         return;
5652     }
5653 
5654     BXE_FP_TX_LOCK(fp);
5655     bxe_tx_start_locked(sc, ifp, fp);
5656     BXE_FP_TX_UNLOCK(fp);
5657 }
5658 
5659 #if __FreeBSD_version >= 901504
5660 
5661 static int
5662 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5663                        if_t                ifp,
5664                        struct bxe_fastpath *fp,
5665                        struct mbuf         *m)
5666 {
5667     struct buf_ring *tx_br = fp->tx_br;
5668     struct mbuf *next;
5669     int depth, rc, tx_count;
5670     uint16_t tx_bd_avail;
5671 
5672     rc = tx_count = 0;
5673 
5674     BXE_FP_TX_LOCK_ASSERT(fp);
5675 
5676     if (sc->state != BXE_STATE_OPEN)  {
5677         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5678         return ENETDOWN;
5679     }
5680 
5681     if (!tx_br) {
5682         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5683         return (EINVAL);
5684     }
5685 
5686     if (m != NULL) {
5687         rc = drbr_enqueue(ifp, tx_br, m);
5688         if (rc != 0) {
5689             fp->eth_q_stats.tx_soft_errors++;
5690             goto bxe_tx_mq_start_locked_exit;
5691         }
5692     }
5693 
5694     if (!sc->link_vars.link_up || !(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5695         fp->eth_q_stats.tx_request_link_down_failures++;
5696         goto bxe_tx_mq_start_locked_exit;
5697     }
5698 
5699     /* fetch the depth of the driver queue */
5700     depth = drbr_inuse_drv(ifp, tx_br);
5701     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5702         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5703     }
5704 
5705     /* keep adding entries while there are frames to send */
5706     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5707         /* handle any completions if we're running low */
5708         tx_bd_avail = bxe_tx_avail(sc, fp);
5709         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5710             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5711             bxe_txeof(sc, fp);
5712             tx_bd_avail = bxe_tx_avail(sc, fp);
5713             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5714                 fp->eth_q_stats.bd_avail_too_less_failures++;
5715                 m_freem(next);
5716                 drbr_advance(ifp, tx_br);
5717                 rc = ENOBUFS;
5718                 break;
5719             }
5720         }
5721 
5722         /* the mbuf now belongs to us */
5723         fp->eth_q_stats.mbuf_alloc_tx++;
5724 
5725         /*
5726          * Put the frame into the transmit ring. If we don't have room,
5727          * place the mbuf back at the head of the TX queue, set the
5728          * OACTIVE flag, and wait for the NIC to drain the chain.
5729          */
5730         rc = bxe_tx_encap(fp, &next);
5731         if (__predict_false(rc != 0)) {
5732             fp->eth_q_stats.tx_encap_failures++;
5733             if (next != NULL) {
5734                 /* mark the TX queue as full and save the frame */
5735                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5736                 drbr_putback(ifp, tx_br, next);
5737                 fp->eth_q_stats.mbuf_alloc_tx--;
5738                 fp->eth_q_stats.tx_frames_deferred++;
5739             } else
5740                 drbr_advance(ifp, tx_br);
5741 
5742             /* stop looking for more work */
5743             break;
5744         }
5745 
5746         /* the transmit frame was enqueued successfully */
5747         tx_count++;
5748 
5749         /* send a copy of the frame to any BPF listeners */
5750 	if_etherbpfmtap(ifp, next);
5751 
5752         drbr_advance(ifp, tx_br);
5753     }
5754 
5755     /* all TX packets were dequeued and/or the tx ring is full */
5756     if (tx_count > 0) {
5757         /* reset the TX watchdog timeout timer */
5758         fp->watchdog_timer = BXE_TX_TIMEOUT;
5759     }
5760 
5761 bxe_tx_mq_start_locked_exit:
5762     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5763     if (!drbr_empty(ifp, tx_br)) {
5764         fp->eth_q_stats.tx_mq_not_empty++;
5765         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5766     }
5767 
5768     return (rc);
5769 }
5770 
5771 static void
5772 bxe_tx_mq_start_deferred(void *arg,
5773                          int pending)
5774 {
5775     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5776     struct bxe_softc *sc = fp->sc;
5777     if_t ifp = sc->ifp;
5778 
5779     BXE_FP_TX_LOCK(fp);
5780     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5781     BXE_FP_TX_UNLOCK(fp);
5782 }
5783 
5784 /* Multiqueue (TSS) dispatch routine. */
5785 static int
5786 bxe_tx_mq_start(struct ifnet *ifp,
5787                 struct mbuf  *m)
5788 {
5789     struct bxe_softc *sc = if_getsoftc(ifp);
5790     struct bxe_fastpath *fp;
5791     int fp_index, rc;
5792 
5793     fp_index = 0; /* default is the first queue */
5794 
5795     /* check if flowid is set */
5796 
5797     if (BXE_VALID_FLOWID(m))
5798         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5799 
5800     fp = &sc->fp[fp_index];
5801 
5802     if (sc->state != BXE_STATE_OPEN)  {
5803         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5804         return ENETDOWN;
5805     }
5806 
5807     if (BXE_FP_TX_TRYLOCK(fp)) {
5808         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5809         BXE_FP_TX_UNLOCK(fp);
5810     } else {
5811         rc = drbr_enqueue(ifp, fp->tx_br, m);
5812         taskqueue_enqueue(fp->tq, &fp->tx_task);
5813     }
5814 
5815     return (rc);
5816 }
5817 
5818 static void
5819 bxe_mq_flush(struct ifnet *ifp)
5820 {
5821     struct bxe_softc *sc = if_getsoftc(ifp);
5822     struct bxe_fastpath *fp;
5823     struct mbuf *m;
5824     int i;
5825 
5826     for (i = 0; i < sc->num_queues; i++) {
5827         fp = &sc->fp[i];
5828 
5829         if (fp->state != BXE_FP_STATE_IRQ) {
5830             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5831                   fp->index, fp->state);
5832             continue;
5833         }
5834 
5835         if (fp->tx_br != NULL) {
5836             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5837             BXE_FP_TX_LOCK(fp);
5838             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5839                 m_freem(m);
5840             }
5841             BXE_FP_TX_UNLOCK(fp);
5842         }
5843     }
5844 
5845     if_qflush(ifp);
5846 }
5847 
5848 #endif /* FreeBSD_version >= 901504 */
5849 
5850 static uint16_t
5851 bxe_cid_ilt_lines(struct bxe_softc *sc)
5852 {
5853     if (IS_SRIOV(sc)) {
5854         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5855     }
5856     return (L2_ILT_LINES(sc));
5857 }
5858 
5859 static void
5860 bxe_ilt_set_info(struct bxe_softc *sc)
5861 {
5862     struct ilt_client_info *ilt_client;
5863     struct ecore_ilt *ilt = sc->ilt;
5864     uint16_t line = 0;
5865 
5866     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5867     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5868 
5869     /* CDU */
5870     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5871     ilt_client->client_num = ILT_CLIENT_CDU;
5872     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5873     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5874     ilt_client->start = line;
5875     line += bxe_cid_ilt_lines(sc);
5876 
5877     if (CNIC_SUPPORT(sc)) {
5878         line += CNIC_ILT_LINES;
5879     }
5880 
5881     ilt_client->end = (line - 1);
5882 
5883     BLOGD(sc, DBG_LOAD,
5884           "ilt client[CDU]: start %d, end %d, "
5885           "psz 0x%x, flags 0x%x, hw psz %d\n",
5886           ilt_client->start, ilt_client->end,
5887           ilt_client->page_size,
5888           ilt_client->flags,
5889           ilog2(ilt_client->page_size >> 12));
5890 
5891     /* QM */
5892     if (QM_INIT(sc->qm_cid_count)) {
5893         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5894         ilt_client->client_num = ILT_CLIENT_QM;
5895         ilt_client->page_size = QM_ILT_PAGE_SZ;
5896         ilt_client->flags = 0;
5897         ilt_client->start = line;
5898 
5899         /* 4 bytes for each cid */
5900         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5901                              QM_ILT_PAGE_SZ);
5902 
5903         ilt_client->end = (line - 1);
5904 
5905         BLOGD(sc, DBG_LOAD,
5906               "ilt client[QM]: start %d, end %d, "
5907               "psz 0x%x, flags 0x%x, hw psz %d\n",
5908               ilt_client->start, ilt_client->end,
5909               ilt_client->page_size, ilt_client->flags,
5910               ilog2(ilt_client->page_size >> 12));
5911     }
5912 
5913     if (CNIC_SUPPORT(sc)) {
5914         /* SRC */
5915         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5916         ilt_client->client_num = ILT_CLIENT_SRC;
5917         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5918         ilt_client->flags = 0;
5919         ilt_client->start = line;
5920         line += SRC_ILT_LINES;
5921         ilt_client->end = (line - 1);
5922 
5923         BLOGD(sc, DBG_LOAD,
5924               "ilt client[SRC]: start %d, end %d, "
5925               "psz 0x%x, flags 0x%x, hw psz %d\n",
5926               ilt_client->start, ilt_client->end,
5927               ilt_client->page_size, ilt_client->flags,
5928               ilog2(ilt_client->page_size >> 12));
5929 
5930         /* TM */
5931         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5932         ilt_client->client_num = ILT_CLIENT_TM;
5933         ilt_client->page_size = TM_ILT_PAGE_SZ;
5934         ilt_client->flags = 0;
5935         ilt_client->start = line;
5936         line += TM_ILT_LINES;
5937         ilt_client->end = (line - 1);
5938 
5939         BLOGD(sc, DBG_LOAD,
5940               "ilt client[TM]: start %d, end %d, "
5941               "psz 0x%x, flags 0x%x, hw psz %d\n",
5942               ilt_client->start, ilt_client->end,
5943               ilt_client->page_size, ilt_client->flags,
5944               ilog2(ilt_client->page_size >> 12));
5945     }
5946 
5947     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5948 }
5949 
5950 static void
5951 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5952 {
5953     int i;
5954     uint32_t rx_buf_size;
5955 
5956     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5957 
5958     for (i = 0; i < sc->num_queues; i++) {
5959         if(rx_buf_size <= MCLBYTES){
5960             sc->fp[i].rx_buf_size = rx_buf_size;
5961             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5962         }else if (rx_buf_size <= MJUMPAGESIZE){
5963             sc->fp[i].rx_buf_size = rx_buf_size;
5964             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5965         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5966             sc->fp[i].rx_buf_size = MCLBYTES;
5967             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5968         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5969             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5970             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5971         }else {
5972             sc->fp[i].rx_buf_size = MCLBYTES;
5973             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5974         }
5975     }
5976 }
5977 
5978 static int
5979 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5980 {
5981     int rc = 0;
5982 
5983     if ((sc->ilt =
5984          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5985                                     M_BXE_ILT,
5986                                     (M_NOWAIT | M_ZERO))) == NULL) {
5987         rc = 1;
5988     }
5989 
5990     return (rc);
5991 }
5992 
5993 static int
5994 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5995 {
5996     int rc = 0;
5997 
5998     if ((sc->ilt->lines =
5999          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6000                                     M_BXE_ILT,
6001                                     (M_NOWAIT | M_ZERO))) == NULL) {
6002         rc = 1;
6003     }
6004 
6005     return (rc);
6006 }
6007 
6008 static void
6009 bxe_free_ilt_mem(struct bxe_softc *sc)
6010 {
6011     if (sc->ilt != NULL) {
6012         free(sc->ilt, M_BXE_ILT);
6013         sc->ilt = NULL;
6014     }
6015 }
6016 
6017 static void
6018 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6019 {
6020     if (sc->ilt->lines != NULL) {
6021         free(sc->ilt->lines, M_BXE_ILT);
6022         sc->ilt->lines = NULL;
6023     }
6024 }
6025 
6026 static void
6027 bxe_free_mem(struct bxe_softc *sc)
6028 {
6029     int i;
6030 
6031     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6032         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6033         sc->context[i].vcxt = NULL;
6034         sc->context[i].size = 0;
6035     }
6036 
6037     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6038 
6039     bxe_free_ilt_lines_mem(sc);
6040 
6041 }
6042 
6043 static int
6044 bxe_alloc_mem(struct bxe_softc *sc)
6045 {
6046 
6047     int context_size;
6048     int allocated;
6049     int i;
6050 
6051     /*
6052      * Allocate memory for CDU context:
6053      * This memory is allocated separately and not in the generic ILT
6054      * functions because CDU differs in few aspects:
6055      * 1. There can be multiple entities allocating memory for context -
6056      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6057      * its own ILT lines.
6058      * 2. Since CDU page-size is not a single 4KB page (which is the case
6059      * for the other ILT clients), to be efficient we want to support
6060      * allocation of sub-page-size in the last entry.
6061      * 3. Context pointers are used by the driver to pass to FW / update
6062      * the context (for the other ILT clients the pointers are used just to
6063      * free the memory during unload).
6064      */
6065     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6066     for (i = 0, allocated = 0; allocated < context_size; i++) {
6067         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6068                                   (context_size - allocated));
6069 
6070         if (bxe_dma_alloc(sc, sc->context[i].size,
6071                           &sc->context[i].vcxt_dma,
6072                           "cdu context") != 0) {
6073             bxe_free_mem(sc);
6074             return (-1);
6075         }
6076 
6077         sc->context[i].vcxt =
6078             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6079 
6080         allocated += sc->context[i].size;
6081     }
6082 
6083     bxe_alloc_ilt_lines_mem(sc);
6084 
6085     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6086           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6087     {
6088         for (i = 0; i < 4; i++) {
6089             BLOGD(sc, DBG_LOAD,
6090                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6091                   i,
6092                   sc->ilt->clients[i].page_size,
6093                   sc->ilt->clients[i].start,
6094                   sc->ilt->clients[i].end,
6095                   sc->ilt->clients[i].client_num,
6096                   sc->ilt->clients[i].flags);
6097         }
6098     }
6099     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6100         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6101         bxe_free_mem(sc);
6102         return (-1);
6103     }
6104 
6105     return (0);
6106 }
6107 
6108 static void
6109 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6110 {
6111     struct bxe_softc *sc;
6112     int i;
6113 
6114     sc = fp->sc;
6115 
6116     if (fp->rx_mbuf_tag == NULL) {
6117         return;
6118     }
6119 
6120     /* free all mbufs and unload all maps */
6121     for (i = 0; i < RX_BD_TOTAL; i++) {
6122         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6123             bus_dmamap_sync(fp->rx_mbuf_tag,
6124                             fp->rx_mbuf_chain[i].m_map,
6125                             BUS_DMASYNC_POSTREAD);
6126             bus_dmamap_unload(fp->rx_mbuf_tag,
6127                               fp->rx_mbuf_chain[i].m_map);
6128         }
6129 
6130         if (fp->rx_mbuf_chain[i].m != NULL) {
6131             m_freem(fp->rx_mbuf_chain[i].m);
6132             fp->rx_mbuf_chain[i].m = NULL;
6133             fp->eth_q_stats.mbuf_alloc_rx--;
6134         }
6135     }
6136 }
6137 
6138 static void
6139 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6140 {
6141     struct bxe_softc *sc;
6142     int i, max_agg_queues;
6143 
6144     sc = fp->sc;
6145 
6146     if (fp->rx_mbuf_tag == NULL) {
6147         return;
6148     }
6149 
6150     max_agg_queues = MAX_AGG_QS(sc);
6151 
6152     /* release all mbufs and unload all DMA maps in the TPA pool */
6153     for (i = 0; i < max_agg_queues; i++) {
6154         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6155             bus_dmamap_sync(fp->rx_mbuf_tag,
6156                             fp->rx_tpa_info[i].bd.m_map,
6157                             BUS_DMASYNC_POSTREAD);
6158             bus_dmamap_unload(fp->rx_mbuf_tag,
6159                               fp->rx_tpa_info[i].bd.m_map);
6160         }
6161 
6162         if (fp->rx_tpa_info[i].bd.m != NULL) {
6163             m_freem(fp->rx_tpa_info[i].bd.m);
6164             fp->rx_tpa_info[i].bd.m = NULL;
6165             fp->eth_q_stats.mbuf_alloc_tpa--;
6166         }
6167     }
6168 }
6169 
6170 static void
6171 bxe_free_sge_chain(struct bxe_fastpath *fp)
6172 {
6173     struct bxe_softc *sc;
6174     int i;
6175 
6176     sc = fp->sc;
6177 
6178     if (fp->rx_sge_mbuf_tag == NULL) {
6179         return;
6180     }
6181 
6182     /* rree all mbufs and unload all maps */
6183     for (i = 0; i < RX_SGE_TOTAL; i++) {
6184         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6185             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6186                             fp->rx_sge_mbuf_chain[i].m_map,
6187                             BUS_DMASYNC_POSTREAD);
6188             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6189                               fp->rx_sge_mbuf_chain[i].m_map);
6190         }
6191 
6192         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6193             m_freem(fp->rx_sge_mbuf_chain[i].m);
6194             fp->rx_sge_mbuf_chain[i].m = NULL;
6195             fp->eth_q_stats.mbuf_alloc_sge--;
6196         }
6197     }
6198 }
6199 
6200 static void
6201 bxe_free_fp_buffers(struct bxe_softc *sc)
6202 {
6203     struct bxe_fastpath *fp;
6204     int i;
6205 
6206     for (i = 0; i < sc->num_queues; i++) {
6207         fp = &sc->fp[i];
6208 
6209 #if __FreeBSD_version >= 901504
6210         if (fp->tx_br != NULL) {
6211             /* just in case bxe_mq_flush() wasn't called */
6212             if (mtx_initialized(&fp->tx_mtx)) {
6213                 struct mbuf *m;
6214 
6215                 BXE_FP_TX_LOCK(fp);
6216                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6217                     m_freem(m);
6218                 BXE_FP_TX_UNLOCK(fp);
6219             }
6220         }
6221 #endif
6222 
6223         /* free all RX buffers */
6224         bxe_free_rx_bd_chain(fp);
6225         bxe_free_tpa_pool(fp);
6226         bxe_free_sge_chain(fp);
6227 
6228         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6229             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6230                   fp->eth_q_stats.mbuf_alloc_rx);
6231         }
6232 
6233         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6234             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6235                   fp->eth_q_stats.mbuf_alloc_sge);
6236         }
6237 
6238         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6239             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6240                   fp->eth_q_stats.mbuf_alloc_tpa);
6241         }
6242 
6243         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6244             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6245                   fp->eth_q_stats.mbuf_alloc_tx);
6246         }
6247 
6248         /* XXX verify all mbufs were reclaimed */
6249     }
6250 }
6251 
6252 static int
6253 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6254                      uint16_t            prev_index,
6255                      uint16_t            index)
6256 {
6257     struct bxe_sw_rx_bd *rx_buf;
6258     struct eth_rx_bd *rx_bd;
6259     bus_dma_segment_t segs[1];
6260     bus_dmamap_t map;
6261     struct mbuf *m;
6262     int nsegs, rc;
6263 
6264     rc = 0;
6265 
6266     /* allocate the new RX BD mbuf */
6267     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6268     if (__predict_false(m == NULL)) {
6269         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6270         return (ENOBUFS);
6271     }
6272 
6273     fp->eth_q_stats.mbuf_alloc_rx++;
6274 
6275     /* initialize the mbuf buffer length */
6276     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6277 
6278     /* map the mbuf into non-paged pool */
6279     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6280                                  fp->rx_mbuf_spare_map,
6281                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6282     if (__predict_false(rc != 0)) {
6283         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6284         m_freem(m);
6285         fp->eth_q_stats.mbuf_alloc_rx--;
6286         return (rc);
6287     }
6288 
6289     /* all mbufs must map to a single segment */
6290     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6291 
6292     /* release any existing RX BD mbuf mappings */
6293 
6294     if (prev_index != index) {
6295         rx_buf = &fp->rx_mbuf_chain[prev_index];
6296 
6297         if (rx_buf->m_map != NULL) {
6298             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6299                             BUS_DMASYNC_POSTREAD);
6300             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6301         }
6302 
6303         /*
6304          * We only get here from bxe_rxeof() when the maximum number
6305          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6306          * holds the mbuf in the prev_index so it's OK to NULL it out
6307          * here without concern of a memory leak.
6308          */
6309         fp->rx_mbuf_chain[prev_index].m = NULL;
6310     }
6311 
6312     rx_buf = &fp->rx_mbuf_chain[index];
6313 
6314     if (rx_buf->m_map != NULL) {
6315         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6316                         BUS_DMASYNC_POSTREAD);
6317         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6318     }
6319 
6320     /* save the mbuf and mapping info for a future packet */
6321     map = (prev_index != index) ?
6322               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6323     rx_buf->m_map = fp->rx_mbuf_spare_map;
6324     fp->rx_mbuf_spare_map = map;
6325     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6326                     BUS_DMASYNC_PREREAD);
6327     rx_buf->m = m;
6328 
6329     rx_bd = &fp->rx_chain[index];
6330     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6331     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6332 
6333     return (rc);
6334 }
6335 
6336 static int
6337 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6338                       int                 queue)
6339 {
6340     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6341     bus_dma_segment_t segs[1];
6342     bus_dmamap_t map;
6343     struct mbuf *m;
6344     int nsegs;
6345     int rc = 0;
6346 
6347     /* allocate the new TPA mbuf */
6348     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6349     if (__predict_false(m == NULL)) {
6350         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6351         return (ENOBUFS);
6352     }
6353 
6354     fp->eth_q_stats.mbuf_alloc_tpa++;
6355 
6356     /* initialize the mbuf buffer length */
6357     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6358 
6359     /* map the mbuf into non-paged pool */
6360     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6361                                  fp->rx_tpa_info_mbuf_spare_map,
6362                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6363     if (__predict_false(rc != 0)) {
6364         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6365         m_free(m);
6366         fp->eth_q_stats.mbuf_alloc_tpa--;
6367         return (rc);
6368     }
6369 
6370     /* all mbufs must map to a single segment */
6371     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6372 
6373     /* release any existing TPA mbuf mapping */
6374     if (tpa_info->bd.m_map != NULL) {
6375         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6376                         BUS_DMASYNC_POSTREAD);
6377         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6378     }
6379 
6380     /* save the mbuf and mapping info for the TPA mbuf */
6381     map = tpa_info->bd.m_map;
6382     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6383     fp->rx_tpa_info_mbuf_spare_map = map;
6384     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6385                     BUS_DMASYNC_PREREAD);
6386     tpa_info->bd.m = m;
6387     tpa_info->seg = segs[0];
6388 
6389     return (rc);
6390 }
6391 
6392 /*
6393  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6394  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6395  * chain.
6396  */
6397 static int
6398 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6399                       uint16_t            index)
6400 {
6401     struct bxe_sw_rx_bd *sge_buf;
6402     struct eth_rx_sge *sge;
6403     bus_dma_segment_t segs[1];
6404     bus_dmamap_t map;
6405     struct mbuf *m;
6406     int nsegs;
6407     int rc = 0;
6408 
6409     /* allocate a new SGE mbuf */
6410     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6411     if (__predict_false(m == NULL)) {
6412         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6413         return (ENOMEM);
6414     }
6415 
6416     fp->eth_q_stats.mbuf_alloc_sge++;
6417 
6418     /* initialize the mbuf buffer length */
6419     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6420 
6421     /* map the SGE mbuf into non-paged pool */
6422     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6423                                  fp->rx_sge_mbuf_spare_map,
6424                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6425     if (__predict_false(rc != 0)) {
6426         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6427         m_freem(m);
6428         fp->eth_q_stats.mbuf_alloc_sge--;
6429         return (rc);
6430     }
6431 
6432     /* all mbufs must map to a single segment */
6433     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6434 
6435     sge_buf = &fp->rx_sge_mbuf_chain[index];
6436 
6437     /* release any existing SGE mbuf mapping */
6438     if (sge_buf->m_map != NULL) {
6439         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6440                         BUS_DMASYNC_POSTREAD);
6441         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6442     }
6443 
6444     /* save the mbuf and mapping info for a future packet */
6445     map = sge_buf->m_map;
6446     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6447     fp->rx_sge_mbuf_spare_map = map;
6448     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6449                     BUS_DMASYNC_PREREAD);
6450     sge_buf->m = m;
6451 
6452     sge = &fp->rx_sge_chain[index];
6453     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6454     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6455 
6456     return (rc);
6457 }
6458 
6459 static __noinline int
6460 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6461 {
6462     struct bxe_fastpath *fp;
6463     int i, j, rc = 0;
6464     int ring_prod, cqe_ring_prod;
6465     int max_agg_queues;
6466 
6467     for (i = 0; i < sc->num_queues; i++) {
6468         fp = &sc->fp[i];
6469 
6470         ring_prod = cqe_ring_prod = 0;
6471         fp->rx_bd_cons = 0;
6472         fp->rx_cq_cons = 0;
6473 
6474         /* allocate buffers for the RX BDs in RX BD chain */
6475         for (j = 0; j < sc->max_rx_bufs; j++) {
6476             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6477             if (rc != 0) {
6478                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6479                       i, rc);
6480                 goto bxe_alloc_fp_buffers_error;
6481             }
6482 
6483             ring_prod     = RX_BD_NEXT(ring_prod);
6484             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6485         }
6486 
6487         fp->rx_bd_prod = ring_prod;
6488         fp->rx_cq_prod = cqe_ring_prod;
6489         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6490 
6491         max_agg_queues = MAX_AGG_QS(sc);
6492 
6493         fp->tpa_enable = TRUE;
6494 
6495         /* fill the TPA pool */
6496         for (j = 0; j < max_agg_queues; j++) {
6497             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6498             if (rc != 0) {
6499                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6500                           i, j);
6501                 fp->tpa_enable = FALSE;
6502                 goto bxe_alloc_fp_buffers_error;
6503             }
6504 
6505             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6506         }
6507 
6508         if (fp->tpa_enable) {
6509             /* fill the RX SGE chain */
6510             ring_prod = 0;
6511             for (j = 0; j < RX_SGE_USABLE; j++) {
6512                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6513                 if (rc != 0) {
6514                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6515                               i, ring_prod);
6516                     fp->tpa_enable = FALSE;
6517                     ring_prod = 0;
6518                     goto bxe_alloc_fp_buffers_error;
6519                 }
6520 
6521                 ring_prod = RX_SGE_NEXT(ring_prod);
6522             }
6523 
6524             fp->rx_sge_prod = ring_prod;
6525         }
6526     }
6527 
6528     return (0);
6529 
6530 bxe_alloc_fp_buffers_error:
6531 
6532     /* unwind what was already allocated */
6533     bxe_free_rx_bd_chain(fp);
6534     bxe_free_tpa_pool(fp);
6535     bxe_free_sge_chain(fp);
6536 
6537     return (ENOBUFS);
6538 }
6539 
6540 static void
6541 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6542 {
6543     bxe_dma_free(sc, &sc->fw_stats_dma);
6544 
6545     sc->fw_stats_num = 0;
6546 
6547     sc->fw_stats_req_size = 0;
6548     sc->fw_stats_req = NULL;
6549     sc->fw_stats_req_mapping = 0;
6550 
6551     sc->fw_stats_data_size = 0;
6552     sc->fw_stats_data = NULL;
6553     sc->fw_stats_data_mapping = 0;
6554 }
6555 
6556 static int
6557 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6558 {
6559     uint8_t num_queue_stats;
6560     int num_groups;
6561 
6562     /* number of queues for statistics is number of eth queues */
6563     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6564 
6565     /*
6566      * Total number of FW statistics requests =
6567      *   1 for port stats + 1 for PF stats + num of queues
6568      */
6569     sc->fw_stats_num = (2 + num_queue_stats);
6570 
6571     /*
6572      * Request is built from stats_query_header and an array of
6573      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6574      * rules. The real number or requests is configured in the
6575      * stats_query_header.
6576      */
6577     num_groups =
6578         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6579          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6580 
6581     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6582           sc->fw_stats_num, num_groups);
6583 
6584     sc->fw_stats_req_size =
6585         (sizeof(struct stats_query_header) +
6586          (num_groups * sizeof(struct stats_query_cmd_group)));
6587 
6588     /*
6589      * Data for statistics requests + stats_counter.
6590      * stats_counter holds per-STORM counters that are incremented when
6591      * STORM has finished with the current request. Memory for FCoE
6592      * offloaded statistics are counted anyway, even if they will not be sent.
6593      * VF stats are not accounted for here as the data of VF stats is stored
6594      * in memory allocated by the VF, not here.
6595      */
6596     sc->fw_stats_data_size =
6597         (sizeof(struct stats_counter) +
6598          sizeof(struct per_port_stats) +
6599          sizeof(struct per_pf_stats) +
6600          /* sizeof(struct fcoe_statistics_params) + */
6601          (sizeof(struct per_queue_stats) * num_queue_stats));
6602 
6603     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6604                       &sc->fw_stats_dma, "fw stats") != 0) {
6605         bxe_free_fw_stats_mem(sc);
6606         return (-1);
6607     }
6608 
6609     /* set up the shortcuts */
6610 
6611     sc->fw_stats_req =
6612         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6613     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6614 
6615     sc->fw_stats_data =
6616         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6617                                      sc->fw_stats_req_size);
6618     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6619                                  sc->fw_stats_req_size);
6620 
6621     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6622           (uintmax_t)sc->fw_stats_req_mapping);
6623 
6624     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6625           (uintmax_t)sc->fw_stats_data_mapping);
6626 
6627     return (0);
6628 }
6629 
6630 /*
6631  * Bits map:
6632  * 0-7  - Engine0 load counter.
6633  * 8-15 - Engine1 load counter.
6634  * 16   - Engine0 RESET_IN_PROGRESS bit.
6635  * 17   - Engine1 RESET_IN_PROGRESS bit.
6636  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6637  *        function on the engine
6638  * 19   - Engine1 ONE_IS_LOADED.
6639  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6640  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6641  *        for just the one belonging to its engine).
6642  */
6643 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6644 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6645 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6646 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6647 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6648 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6649 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6650 #define BXE_GLOBAL_RESET_BIT      0x00040000
6651 
6652 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6653 static void
6654 bxe_set_reset_global(struct bxe_softc *sc)
6655 {
6656     uint32_t val;
6657     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6658     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6659     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6660     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6661 }
6662 
6663 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6664 static void
6665 bxe_clear_reset_global(struct bxe_softc *sc)
6666 {
6667     uint32_t val;
6668     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6669     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6670     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6671     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6672 }
6673 
6674 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6675 static uint8_t
6676 bxe_reset_is_global(struct bxe_softc *sc)
6677 {
6678     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6679     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6680     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6681 }
6682 
6683 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6684 static void
6685 bxe_set_reset_done(struct bxe_softc *sc)
6686 {
6687     uint32_t val;
6688     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6689                                  BXE_PATH0_RST_IN_PROG_BIT;
6690 
6691     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6692 
6693     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6694     /* Clear the bit */
6695     val &= ~bit;
6696     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6697 
6698     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6699 }
6700 
6701 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6702 static void
6703 bxe_set_reset_in_progress(struct bxe_softc *sc)
6704 {
6705     uint32_t val;
6706     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6707                                  BXE_PATH0_RST_IN_PROG_BIT;
6708 
6709     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6710 
6711     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6712     /* Set the bit */
6713     val |= bit;
6714     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6715 
6716     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6717 }
6718 
6719 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6720 static uint8_t
6721 bxe_reset_is_done(struct bxe_softc *sc,
6722                   int              engine)
6723 {
6724     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6725     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6726                             BXE_PATH0_RST_IN_PROG_BIT;
6727 
6728     /* return false if bit is set */
6729     return (val & bit) ? FALSE : TRUE;
6730 }
6731 
6732 /* get the load status for an engine, should be run under rtnl lock */
6733 static uint8_t
6734 bxe_get_load_status(struct bxe_softc *sc,
6735                     int              engine)
6736 {
6737     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6738                              BXE_PATH0_LOAD_CNT_MASK;
6739     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6740                               BXE_PATH0_LOAD_CNT_SHIFT;
6741     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6742 
6743     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6744 
6745     val = ((val & mask) >> shift);
6746 
6747     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6748 
6749     return (val != 0);
6750 }
6751 
6752 /* set pf load mark */
6753 /* XXX needs to be under rtnl lock */
6754 static void
6755 bxe_set_pf_load(struct bxe_softc *sc)
6756 {
6757     uint32_t val;
6758     uint32_t val1;
6759     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6760                                   BXE_PATH0_LOAD_CNT_MASK;
6761     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6762                                    BXE_PATH0_LOAD_CNT_SHIFT;
6763 
6764     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6765 
6766     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6767     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6768 
6769     /* get the current counter value */
6770     val1 = ((val & mask) >> shift);
6771 
6772     /* set bit of this PF */
6773     val1 |= (1 << SC_ABS_FUNC(sc));
6774 
6775     /* clear the old value */
6776     val &= ~mask;
6777 
6778     /* set the new one */
6779     val |= ((val1 << shift) & mask);
6780 
6781     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6782 
6783     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6784 }
6785 
6786 /* clear pf load mark */
6787 /* XXX needs to be under rtnl lock */
6788 static uint8_t
6789 bxe_clear_pf_load(struct bxe_softc *sc)
6790 {
6791     uint32_t val1, val;
6792     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6793                                   BXE_PATH0_LOAD_CNT_MASK;
6794     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6795                                    BXE_PATH0_LOAD_CNT_SHIFT;
6796 
6797     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6798     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6799     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6800 
6801     /* get the current counter value */
6802     val1 = (val & mask) >> shift;
6803 
6804     /* clear bit of that PF */
6805     val1 &= ~(1 << SC_ABS_FUNC(sc));
6806 
6807     /* clear the old value */
6808     val &= ~mask;
6809 
6810     /* set the new one */
6811     val |= ((val1 << shift) & mask);
6812 
6813     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6814     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6815     return (val1 != 0);
6816 }
6817 
6818 /* send load requrest to mcp and analyze response */
6819 static int
6820 bxe_nic_load_request(struct bxe_softc *sc,
6821                      uint32_t         *load_code)
6822 {
6823     /* init fw_seq */
6824     sc->fw_seq =
6825         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6826          DRV_MSG_SEQ_NUMBER_MASK);
6827 
6828     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6829 
6830     /* get the current FW pulse sequence */
6831     sc->fw_drv_pulse_wr_seq =
6832         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6833          DRV_PULSE_SEQ_MASK);
6834 
6835     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6836           sc->fw_drv_pulse_wr_seq);
6837 
6838     /* load request */
6839     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6840                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6841 
6842     /* if the MCP fails to respond we must abort */
6843     if (!(*load_code)) {
6844         BLOGE(sc, "MCP response failure!\n");
6845         return (-1);
6846     }
6847 
6848     /* if MCP refused then must abort */
6849     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6850         BLOGE(sc, "MCP refused load request\n");
6851         return (-1);
6852     }
6853 
6854     return (0);
6855 }
6856 
6857 /*
6858  * Check whether another PF has already loaded FW to chip. In virtualized
6859  * environments a pf from anoth VM may have already initialized the device
6860  * including loading FW.
6861  */
6862 static int
6863 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6864                          uint32_t         load_code)
6865 {
6866     uint32_t my_fw, loaded_fw;
6867 
6868     /* is another pf loaded on this engine? */
6869     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6870         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6871         /* build my FW version dword */
6872         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6873                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6874                  (BCM_5710_FW_REVISION_VERSION << 16) +
6875                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6876 
6877         /* read loaded FW from chip */
6878         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6879         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6880               loaded_fw, my_fw);
6881 
6882         /* abort nic load if version mismatch */
6883         if (my_fw != loaded_fw) {
6884             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6885                   loaded_fw, my_fw);
6886             return (-1);
6887         }
6888     }
6889 
6890     return (0);
6891 }
6892 
6893 /* mark PMF if applicable */
6894 static void
6895 bxe_nic_load_pmf(struct bxe_softc *sc,
6896                  uint32_t         load_code)
6897 {
6898     uint32_t ncsi_oem_data_addr;
6899 
6900     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6901         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6902         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6903         /*
6904          * Barrier here for ordering between the writing to sc->port.pmf here
6905          * and reading it from the periodic task.
6906          */
6907         sc->port.pmf = 1;
6908         mb();
6909     } else {
6910         sc->port.pmf = 0;
6911     }
6912 
6913     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6914 
6915     /* XXX needed? */
6916     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6917         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6918             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6919             if (ncsi_oem_data_addr) {
6920                 REG_WR(sc,
6921                        (ncsi_oem_data_addr +
6922                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6923                        0);
6924             }
6925         }
6926     }
6927 }
6928 
6929 static void
6930 bxe_read_mf_cfg(struct bxe_softc *sc)
6931 {
6932     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6933     int abs_func;
6934     int vn;
6935 
6936     if (BXE_NOMCP(sc)) {
6937         return; /* what should be the default bvalue in this case */
6938     }
6939 
6940     /*
6941      * The formula for computing the absolute function number is...
6942      * For 2 port configuration (4 functions per port):
6943      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6944      * For 4 port configuration (2 functions per port):
6945      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6946      */
6947     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6948         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6949         if (abs_func >= E1H_FUNC_MAX) {
6950             break;
6951         }
6952         sc->devinfo.mf_info.mf_config[vn] =
6953             MFCFG_RD(sc, func_mf_config[abs_func].config);
6954     }
6955 
6956     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6957         FUNC_MF_CFG_FUNC_DISABLED) {
6958         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6959         sc->flags |= BXE_MF_FUNC_DIS;
6960     } else {
6961         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6962         sc->flags &= ~BXE_MF_FUNC_DIS;
6963     }
6964 }
6965 
6966 /* acquire split MCP access lock register */
6967 static int bxe_acquire_alr(struct bxe_softc *sc)
6968 {
6969     uint32_t j, val;
6970 
6971     for (j = 0; j < 1000; j++) {
6972         val = (1UL << 31);
6973         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6974         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6975         if (val & (1L << 31))
6976             break;
6977 
6978         DELAY(5000);
6979     }
6980 
6981     if (!(val & (1L << 31))) {
6982         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6983         return (-1);
6984     }
6985 
6986     return (0);
6987 }
6988 
6989 /* release split MCP access lock register */
6990 static void bxe_release_alr(struct bxe_softc *sc)
6991 {
6992     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6993 }
6994 
6995 static void
6996 bxe_fan_failure(struct bxe_softc *sc)
6997 {
6998     int port = SC_PORT(sc);
6999     uint32_t ext_phy_config;
7000 
7001     /* mark the failure */
7002     ext_phy_config =
7003         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7004 
7005     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7006     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7007     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7008              ext_phy_config);
7009 
7010     /* log the failure */
7011     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7012               "the card to prevent permanent damage. "
7013               "Please contact OEM Support for assistance\n");
7014 
7015     /* XXX */
7016 #if 1
7017     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7018 #else
7019     /*
7020      * Schedule device reset (unload)
7021      * This is due to some boards consuming sufficient power when driver is
7022      * up to overheat if fan fails.
7023      */
7024     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7025     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7026 #endif
7027 }
7028 
7029 /* this function is called upon a link interrupt */
7030 static void
7031 bxe_link_attn(struct bxe_softc *sc)
7032 {
7033     uint32_t pause_enabled = 0;
7034     struct host_port_stats *pstats;
7035     int cmng_fns;
7036     struct bxe_fastpath *fp;
7037     int i;
7038 
7039     /* Make sure that we are synced with the current statistics */
7040     bxe_stats_handle(sc, STATS_EVENT_STOP);
7041 	BLOGI(sc, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7042     elink_link_update(&sc->link_params, &sc->link_vars);
7043 
7044     if (sc->link_vars.link_up) {
7045 
7046         /* dropless flow control */
7047         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7048             pause_enabled = 0;
7049 
7050             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7051                 pause_enabled = 1;
7052             }
7053 
7054             REG_WR(sc,
7055                    (BAR_USTRORM_INTMEM +
7056                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7057                    pause_enabled);
7058         }
7059 
7060         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7061             pstats = BXE_SP(sc, port_stats);
7062             /* reset old mac stats */
7063             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7064         }
7065 
7066         if (sc->state == BXE_STATE_OPEN) {
7067             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7068         }
7069 
7070 	/* Restart tx when the link comes back. */
7071         FOR_EACH_ETH_QUEUE(sc, i) {
7072             fp = &sc->fp[i];
7073             taskqueue_enqueue(fp->tq, &fp->tx_task);
7074 	}
7075     }
7076 
7077     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7078         cmng_fns = bxe_get_cmng_fns_mode(sc);
7079 
7080         if (cmng_fns != CMNG_FNS_NONE) {
7081             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7082             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7083         } else {
7084             /* rate shaping and fairness are disabled */
7085             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7086         }
7087     }
7088 
7089     bxe_link_report_locked(sc);
7090 
7091     if (IS_MF(sc)) {
7092         ; // XXX bxe_link_sync_notify(sc);
7093     }
7094 }
7095 
7096 static void
7097 bxe_attn_int_asserted(struct bxe_softc *sc,
7098                       uint32_t         asserted)
7099 {
7100     int port = SC_PORT(sc);
7101     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7102                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7103     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7104                                         NIG_REG_MASK_INTERRUPT_PORT0;
7105     uint32_t aeu_mask;
7106     uint32_t nig_mask = 0;
7107     uint32_t reg_addr;
7108     uint32_t igu_acked;
7109     uint32_t cnt;
7110 
7111     if (sc->attn_state & asserted) {
7112         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7113     }
7114 
7115     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7116 
7117     aeu_mask = REG_RD(sc, aeu_addr);
7118 
7119     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7120           aeu_mask, asserted);
7121 
7122     aeu_mask &= ~(asserted & 0x3ff);
7123 
7124     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7125 
7126     REG_WR(sc, aeu_addr, aeu_mask);
7127 
7128     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7129 
7130     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7131     sc->attn_state |= asserted;
7132     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7133 
7134     if (asserted & ATTN_HARD_WIRED_MASK) {
7135         if (asserted & ATTN_NIG_FOR_FUNC) {
7136 
7137 	    bxe_acquire_phy_lock(sc);
7138             /* save nig interrupt mask */
7139             nig_mask = REG_RD(sc, nig_int_mask_addr);
7140 
7141             /* If nig_mask is not set, no need to call the update function */
7142             if (nig_mask) {
7143                 REG_WR(sc, nig_int_mask_addr, 0);
7144 
7145                 bxe_link_attn(sc);
7146             }
7147 
7148             /* handle unicore attn? */
7149         }
7150 
7151         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7152             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7153         }
7154 
7155         if (asserted & GPIO_2_FUNC) {
7156             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7157         }
7158 
7159         if (asserted & GPIO_3_FUNC) {
7160             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7161         }
7162 
7163         if (asserted & GPIO_4_FUNC) {
7164             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7165         }
7166 
7167         if (port == 0) {
7168             if (asserted & ATTN_GENERAL_ATTN_1) {
7169                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7170                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7171             }
7172             if (asserted & ATTN_GENERAL_ATTN_2) {
7173                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7174                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7175             }
7176             if (asserted & ATTN_GENERAL_ATTN_3) {
7177                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7178                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7179             }
7180         } else {
7181             if (asserted & ATTN_GENERAL_ATTN_4) {
7182                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7183                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7184             }
7185             if (asserted & ATTN_GENERAL_ATTN_5) {
7186                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7187                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7188             }
7189             if (asserted & ATTN_GENERAL_ATTN_6) {
7190                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7191                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7192             }
7193         }
7194     } /* hardwired */
7195 
7196     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7197         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7198     } else {
7199         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7200     }
7201 
7202     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7203           asserted,
7204           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7205     REG_WR(sc, reg_addr, asserted);
7206 
7207     /* now set back the mask */
7208     if (asserted & ATTN_NIG_FOR_FUNC) {
7209         /*
7210          * Verify that IGU ack through BAR was written before restoring
7211          * NIG mask. This loop should exit after 2-3 iterations max.
7212          */
7213         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7214             cnt = 0;
7215 
7216             do {
7217                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7218             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7219                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7220 
7221             if (!igu_acked) {
7222                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7223             }
7224 
7225             mb();
7226         }
7227 
7228         REG_WR(sc, nig_int_mask_addr, nig_mask);
7229 
7230 	bxe_release_phy_lock(sc);
7231     }
7232 }
7233 
7234 static void
7235 bxe_print_next_block(struct bxe_softc *sc,
7236                      int              idx,
7237                      const char       *blk)
7238 {
7239     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7240 }
7241 
7242 static int
7243 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7244                               uint32_t         sig,
7245                               int              par_num,
7246                               uint8_t          print)
7247 {
7248     uint32_t cur_bit = 0;
7249     int i = 0;
7250 
7251     for (i = 0; sig; i++) {
7252         cur_bit = ((uint32_t)0x1 << i);
7253         if (sig & cur_bit) {
7254             switch (cur_bit) {
7255             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7256                 if (print)
7257                     bxe_print_next_block(sc, par_num++, "BRB");
7258                 break;
7259             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7260                 if (print)
7261                     bxe_print_next_block(sc, par_num++, "PARSER");
7262                 break;
7263             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7264                 if (print)
7265                     bxe_print_next_block(sc, par_num++, "TSDM");
7266                 break;
7267             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7268                 if (print)
7269                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7270                 break;
7271             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7272                 if (print)
7273                     bxe_print_next_block(sc, par_num++, "TCM");
7274                 break;
7275             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7276                 if (print)
7277                     bxe_print_next_block(sc, par_num++, "TSEMI");
7278                 break;
7279             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7280                 if (print)
7281                     bxe_print_next_block(sc, par_num++, "XPB");
7282                 break;
7283             }
7284 
7285             /* Clear the bit */
7286             sig &= ~cur_bit;
7287         }
7288     }
7289 
7290     return (par_num);
7291 }
7292 
7293 static int
7294 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7295                               uint32_t         sig,
7296                               int              par_num,
7297                               uint8_t          *global,
7298                               uint8_t          print)
7299 {
7300     int i = 0;
7301     uint32_t cur_bit = 0;
7302     for (i = 0; sig; i++) {
7303         cur_bit = ((uint32_t)0x1 << i);
7304         if (sig & cur_bit) {
7305             switch (cur_bit) {
7306             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7307                 if (print)
7308                     bxe_print_next_block(sc, par_num++, "PBF");
7309                 break;
7310             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7311                 if (print)
7312                     bxe_print_next_block(sc, par_num++, "QM");
7313                 break;
7314             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7315                 if (print)
7316                     bxe_print_next_block(sc, par_num++, "TM");
7317                 break;
7318             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7319                 if (print)
7320                     bxe_print_next_block(sc, par_num++, "XSDM");
7321                 break;
7322             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7323                 if (print)
7324                     bxe_print_next_block(sc, par_num++, "XCM");
7325                 break;
7326             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7327                 if (print)
7328                     bxe_print_next_block(sc, par_num++, "XSEMI");
7329                 break;
7330             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7331                 if (print)
7332                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7333                 break;
7334             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7335                 if (print)
7336                     bxe_print_next_block(sc, par_num++, "NIG");
7337                 break;
7338             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7339                 if (print)
7340                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7341                 *global = TRUE;
7342                 break;
7343             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7344                 if (print)
7345                     bxe_print_next_block(sc, par_num++, "DEBUG");
7346                 break;
7347             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7348                 if (print)
7349                     bxe_print_next_block(sc, par_num++, "USDM");
7350                 break;
7351             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7352                 if (print)
7353                     bxe_print_next_block(sc, par_num++, "UCM");
7354                 break;
7355             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7356                 if (print)
7357                     bxe_print_next_block(sc, par_num++, "USEMI");
7358                 break;
7359             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7360                 if (print)
7361                     bxe_print_next_block(sc, par_num++, "UPB");
7362                 break;
7363             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7364                 if (print)
7365                     bxe_print_next_block(sc, par_num++, "CSDM");
7366                 break;
7367             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7368                 if (print)
7369                     bxe_print_next_block(sc, par_num++, "CCM");
7370                 break;
7371             }
7372 
7373             /* Clear the bit */
7374             sig &= ~cur_bit;
7375         }
7376     }
7377 
7378     return (par_num);
7379 }
7380 
7381 static int
7382 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7383                               uint32_t         sig,
7384                               int              par_num,
7385                               uint8_t          print)
7386 {
7387     uint32_t cur_bit = 0;
7388     int i = 0;
7389 
7390     for (i = 0; sig; i++) {
7391         cur_bit = ((uint32_t)0x1 << i);
7392         if (sig & cur_bit) {
7393             switch (cur_bit) {
7394             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7395                 if (print)
7396                     bxe_print_next_block(sc, par_num++, "CSEMI");
7397                 break;
7398             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7399                 if (print)
7400                     bxe_print_next_block(sc, par_num++, "PXP");
7401                 break;
7402             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7403                 if (print)
7404                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7405                 break;
7406             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7407                 if (print)
7408                     bxe_print_next_block(sc, par_num++, "CFC");
7409                 break;
7410             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7411                 if (print)
7412                     bxe_print_next_block(sc, par_num++, "CDU");
7413                 break;
7414             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7415                 if (print)
7416                     bxe_print_next_block(sc, par_num++, "DMAE");
7417                 break;
7418             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7419                 if (print)
7420                     bxe_print_next_block(sc, par_num++, "IGU");
7421                 break;
7422             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7423                 if (print)
7424                     bxe_print_next_block(sc, par_num++, "MISC");
7425                 break;
7426             }
7427 
7428             /* Clear the bit */
7429             sig &= ~cur_bit;
7430         }
7431     }
7432 
7433     return (par_num);
7434 }
7435 
7436 static int
7437 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7438                               uint32_t         sig,
7439                               int              par_num,
7440                               uint8_t          *global,
7441                               uint8_t          print)
7442 {
7443     uint32_t cur_bit = 0;
7444     int i = 0;
7445 
7446     for (i = 0; sig; i++) {
7447         cur_bit = ((uint32_t)0x1 << i);
7448         if (sig & cur_bit) {
7449             switch (cur_bit) {
7450             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7451                 if (print)
7452                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7453                 *global = TRUE;
7454                 break;
7455             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7456                 if (print)
7457                     bxe_print_next_block(sc, par_num++,
7458                               "MCP UMP RX");
7459                 *global = TRUE;
7460                 break;
7461             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7462                 if (print)
7463                     bxe_print_next_block(sc, par_num++,
7464                               "MCP UMP TX");
7465                 *global = TRUE;
7466                 break;
7467             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7468                 if (print)
7469                     bxe_print_next_block(sc, par_num++,
7470                               "MCP SCPAD");
7471                 *global = TRUE;
7472                 break;
7473             }
7474 
7475             /* Clear the bit */
7476             sig &= ~cur_bit;
7477         }
7478     }
7479 
7480     return (par_num);
7481 }
7482 
7483 static int
7484 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7485                               uint32_t         sig,
7486                               int              par_num,
7487                               uint8_t          print)
7488 {
7489     uint32_t cur_bit = 0;
7490     int i = 0;
7491 
7492     for (i = 0; sig; i++) {
7493         cur_bit = ((uint32_t)0x1 << i);
7494         if (sig & cur_bit) {
7495             switch (cur_bit) {
7496             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7497                 if (print)
7498                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7499                 break;
7500             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7501                 if (print)
7502                     bxe_print_next_block(sc, par_num++, "ATC");
7503                 break;
7504             }
7505 
7506             /* Clear the bit */
7507             sig &= ~cur_bit;
7508         }
7509     }
7510 
7511     return (par_num);
7512 }
7513 
7514 static uint8_t
7515 bxe_parity_attn(struct bxe_softc *sc,
7516                 uint8_t          *global,
7517                 uint8_t          print,
7518                 uint32_t         *sig)
7519 {
7520     int par_num = 0;
7521 
7522     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7523         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7524         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7525         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7526         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7527         BLOGE(sc, "Parity error: HW block parity attention:\n"
7528                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7529               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7530               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7531               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7532               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7533               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7534 
7535         if (print)
7536             BLOGI(sc, "Parity errors detected in blocks: ");
7537 
7538         par_num =
7539             bxe_check_blocks_with_parity0(sc, sig[0] &
7540                                           HW_PRTY_ASSERT_SET_0,
7541                                           par_num, print);
7542         par_num =
7543             bxe_check_blocks_with_parity1(sc, sig[1] &
7544                                           HW_PRTY_ASSERT_SET_1,
7545                                           par_num, global, print);
7546         par_num =
7547             bxe_check_blocks_with_parity2(sc, sig[2] &
7548                                           HW_PRTY_ASSERT_SET_2,
7549                                           par_num, print);
7550         par_num =
7551             bxe_check_blocks_with_parity3(sc, sig[3] &
7552                                           HW_PRTY_ASSERT_SET_3,
7553                                           par_num, global, print);
7554         par_num =
7555             bxe_check_blocks_with_parity4(sc, sig[4] &
7556                                           HW_PRTY_ASSERT_SET_4,
7557                                           par_num, print);
7558 
7559         if (print)
7560             BLOGI(sc, "\n");
7561 
7562         return (TRUE);
7563     }
7564 
7565     return (FALSE);
7566 }
7567 
7568 static uint8_t
7569 bxe_chk_parity_attn(struct bxe_softc *sc,
7570                     uint8_t          *global,
7571                     uint8_t          print)
7572 {
7573     struct attn_route attn = { {0} };
7574     int port = SC_PORT(sc);
7575 
7576     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7577     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7578     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7579     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7580 
7581     /*
7582      * Since MCP attentions can't be disabled inside the block, we need to
7583      * read AEU registers to see whether they're currently disabled
7584      */
7585     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7586                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7587                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7588                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7589 
7590 
7591     if (!CHIP_IS_E1x(sc))
7592         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7593 
7594     return (bxe_parity_attn(sc, global, print, attn.sig));
7595 }
7596 
7597 static void
7598 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7599                          uint32_t         attn)
7600 {
7601     uint32_t val;
7602 
7603     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7604         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7605         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7606         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7607             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7608         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7609             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7610         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7611             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7612         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7613             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7614         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7615             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7616         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7617             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7618         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7619             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7620         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7621             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7622         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7623             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7624     }
7625 
7626     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7627         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7628         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7629         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7630             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7631         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7632             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7633         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7634             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7635         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7636             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7637         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7638             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7639         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7640             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7641     }
7642 
7643     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7644                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7645         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7646               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7647                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7648     }
7649 }
7650 
7651 static void
7652 bxe_e1h_disable(struct bxe_softc *sc)
7653 {
7654     int port = SC_PORT(sc);
7655 
7656     bxe_tx_disable(sc);
7657 
7658     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7659 }
7660 
7661 static void
7662 bxe_e1h_enable(struct bxe_softc *sc)
7663 {
7664     int port = SC_PORT(sc);
7665 
7666     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7667 
7668     // XXX bxe_tx_enable(sc);
7669 }
7670 
7671 /*
7672  * called due to MCP event (on pmf):
7673  *   reread new bandwidth configuration
7674  *   configure FW
7675  *   notify others function about the change
7676  */
7677 static void
7678 bxe_config_mf_bw(struct bxe_softc *sc)
7679 {
7680     if (sc->link_vars.link_up) {
7681         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7682         // XXX bxe_link_sync_notify(sc);
7683     }
7684 
7685     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7686 }
7687 
7688 static void
7689 bxe_set_mf_bw(struct bxe_softc *sc)
7690 {
7691     bxe_config_mf_bw(sc);
7692     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7693 }
7694 
7695 static void
7696 bxe_handle_eee_event(struct bxe_softc *sc)
7697 {
7698     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7699     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7700 }
7701 
7702 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7703 
7704 static void
7705 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7706 {
7707     struct eth_stats_info *ether_stat =
7708         &sc->sp->drv_info_to_mcp.ether_stat;
7709 
7710     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7711             ETH_STAT_INFO_VERSION_LEN);
7712 
7713     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7714     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7715                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7716                                           ether_stat->mac_local + MAC_PAD,
7717                                           MAC_PAD, ETH_ALEN);
7718 
7719     ether_stat->mtu_size = sc->mtu;
7720 
7721     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7722     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7723         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7724     }
7725 
7726     // XXX ether_stat->feature_flags |= ???;
7727 
7728     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7729 
7730     ether_stat->txq_size = sc->tx_ring_size;
7731     ether_stat->rxq_size = sc->rx_ring_size;
7732 }
7733 
7734 static void
7735 bxe_handle_drv_info_req(struct bxe_softc *sc)
7736 {
7737     enum drv_info_opcode op_code;
7738     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7739 
7740     /* if drv_info version supported by MFW doesn't match - send NACK */
7741     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7742         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7743         return;
7744     }
7745 
7746     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7747                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7748 
7749     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7750 
7751     switch (op_code) {
7752     case ETH_STATS_OPCODE:
7753         bxe_drv_info_ether_stat(sc);
7754         break;
7755     case FCOE_STATS_OPCODE:
7756     case ISCSI_STATS_OPCODE:
7757     default:
7758         /* if op code isn't supported - send NACK */
7759         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7760         return;
7761     }
7762 
7763     /*
7764      * If we got drv_info attn from MFW then these fields are defined in
7765      * shmem2 for sure
7766      */
7767     SHMEM2_WR(sc, drv_info_host_addr_lo,
7768               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7769     SHMEM2_WR(sc, drv_info_host_addr_hi,
7770               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7771 
7772     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7773 }
7774 
7775 static void
7776 bxe_dcc_event(struct bxe_softc *sc,
7777               uint32_t         dcc_event)
7778 {
7779     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7780 
7781     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7782         /*
7783          * This is the only place besides the function initialization
7784          * where the sc->flags can change so it is done without any
7785          * locks
7786          */
7787         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7788             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7789             sc->flags |= BXE_MF_FUNC_DIS;
7790             bxe_e1h_disable(sc);
7791         } else {
7792             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7793             sc->flags &= ~BXE_MF_FUNC_DIS;
7794             bxe_e1h_enable(sc);
7795         }
7796         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7797     }
7798 
7799     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7800         bxe_config_mf_bw(sc);
7801         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7802     }
7803 
7804     /* Report results to MCP */
7805     if (dcc_event)
7806         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7807     else
7808         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7809 }
7810 
7811 static void
7812 bxe_pmf_update(struct bxe_softc *sc)
7813 {
7814     int port = SC_PORT(sc);
7815     uint32_t val;
7816 
7817     sc->port.pmf = 1;
7818     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7819 
7820     /*
7821      * We need the mb() to ensure the ordering between the writing to
7822      * sc->port.pmf here and reading it from the bxe_periodic_task().
7823      */
7824     mb();
7825 
7826     /* queue a periodic task */
7827     // XXX schedule task...
7828 
7829     // XXX bxe_dcbx_pmf_update(sc);
7830 
7831     /* enable nig attention */
7832     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7833     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7834         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7835         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7836     } else if (!CHIP_IS_E1x(sc)) {
7837         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7838         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7839     }
7840 
7841     bxe_stats_handle(sc, STATS_EVENT_PMF);
7842 }
7843 
7844 static int
7845 bxe_mc_assert(struct bxe_softc *sc)
7846 {
7847     char last_idx;
7848     int i, rc = 0;
7849     uint32_t row0, row1, row2, row3;
7850 
7851     /* XSTORM */
7852     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7853     if (last_idx)
7854         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7855 
7856     /* print the asserts */
7857     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7858 
7859         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7860         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7861         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7862         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7863 
7864         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7865             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7866                   i, row3, row2, row1, row0);
7867             rc++;
7868         } else {
7869             break;
7870         }
7871     }
7872 
7873     /* TSTORM */
7874     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7875     if (last_idx) {
7876         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7877     }
7878 
7879     /* print the asserts */
7880     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7881 
7882         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7883         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7884         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7885         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7886 
7887         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7888             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7889                   i, row3, row2, row1, row0);
7890             rc++;
7891         } else {
7892             break;
7893         }
7894     }
7895 
7896     /* CSTORM */
7897     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7898     if (last_idx) {
7899         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7900     }
7901 
7902     /* print the asserts */
7903     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7904 
7905         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7906         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7907         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7908         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7909 
7910         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7911             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7912                   i, row3, row2, row1, row0);
7913             rc++;
7914         } else {
7915             break;
7916         }
7917     }
7918 
7919     /* USTORM */
7920     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7921     if (last_idx) {
7922         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7923     }
7924 
7925     /* print the asserts */
7926     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7927 
7928         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7929         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7930         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7931         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7932 
7933         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7934             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7935                   i, row3, row2, row1, row0);
7936             rc++;
7937         } else {
7938             break;
7939         }
7940     }
7941 
7942     return (rc);
7943 }
7944 
7945 static void
7946 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7947                          uint32_t         attn)
7948 {
7949     int func = SC_FUNC(sc);
7950     uint32_t val;
7951 
7952     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7953 
7954         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7955 
7956             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7957             bxe_read_mf_cfg(sc);
7958             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7959                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7960             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7961 
7962             if (val & DRV_STATUS_DCC_EVENT_MASK)
7963                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7964 
7965             if (val & DRV_STATUS_SET_MF_BW)
7966                 bxe_set_mf_bw(sc);
7967 
7968             if (val & DRV_STATUS_DRV_INFO_REQ)
7969                 bxe_handle_drv_info_req(sc);
7970 
7971             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7972                 bxe_pmf_update(sc);
7973 
7974             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7975                 bxe_handle_eee_event(sc);
7976 
7977             if (sc->link_vars.periodic_flags &
7978                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7979                 /* sync with link */
7980 		bxe_acquire_phy_lock(sc);
7981                 sc->link_vars.periodic_flags &=
7982                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7983 		bxe_release_phy_lock(sc);
7984                 if (IS_MF(sc))
7985                     ; // XXX bxe_link_sync_notify(sc);
7986                 bxe_link_report(sc);
7987             }
7988 
7989             /*
7990              * Always call it here: bxe_link_report() will
7991              * prevent the link indication duplication.
7992              */
7993             bxe_link_status_update(sc);
7994 
7995         } else if (attn & BXE_MC_ASSERT_BITS) {
7996 
7997             BLOGE(sc, "MC assert!\n");
7998             bxe_mc_assert(sc);
7999             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8000             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8001             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8002             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8003             bxe_panic(sc, ("MC assert!\n"));
8004 
8005         } else if (attn & BXE_MCP_ASSERT) {
8006 
8007             BLOGE(sc, "MCP assert!\n");
8008             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8009             // XXX bxe_fw_dump(sc);
8010 
8011         } else {
8012             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8013         }
8014     }
8015 
8016     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8017         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8018         if (attn & BXE_GRC_TIMEOUT) {
8019             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8020             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8021         }
8022         if (attn & BXE_GRC_RSV) {
8023             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8024             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8025         }
8026         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8027     }
8028 }
8029 
8030 static void
8031 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8032                          uint32_t         attn)
8033 {
8034     int port = SC_PORT(sc);
8035     int reg_offset;
8036     uint32_t val0, mask0, val1, mask1;
8037     uint32_t val;
8038 
8039     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8040         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8041         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8042         /* CFC error attention */
8043         if (val & 0x2) {
8044             BLOGE(sc, "FATAL error from CFC\n");
8045         }
8046     }
8047 
8048     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8049         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8050         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8051         /* RQ_USDMDP_FIFO_OVERFLOW */
8052         if (val & 0x18000) {
8053             BLOGE(sc, "FATAL error from PXP\n");
8054         }
8055 
8056         if (!CHIP_IS_E1x(sc)) {
8057             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8058             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8059         }
8060     }
8061 
8062 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8063 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8064 
8065     if (attn & AEU_PXP2_HW_INT_BIT) {
8066         /*  CQ47854 workaround do not panic on
8067          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8068          */
8069         if (!CHIP_IS_E1x(sc)) {
8070             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8071             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8072             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8073             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8074             /*
8075              * If the only PXP2_EOP_ERROR_BIT is set in
8076              * STS0 and STS1 - clear it
8077              *
8078              * probably we lose additional attentions between
8079              * STS0 and STS_CLR0, in this case user will not
8080              * be notified about them
8081              */
8082             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8083                 !(val1 & mask1))
8084                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8085 
8086             /* print the register, since no one can restore it */
8087             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8088 
8089             /*
8090              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8091              * then notify
8092              */
8093             if (val0 & PXP2_EOP_ERROR_BIT) {
8094                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8095 
8096                 /*
8097                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8098                  * set then clear attention from PXP2 block without panic
8099                  */
8100                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8101                     ((val1 & mask1) == 0))
8102                     attn &= ~AEU_PXP2_HW_INT_BIT;
8103             }
8104         }
8105     }
8106 
8107     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8108         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8109                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8110 
8111         val = REG_RD(sc, reg_offset);
8112         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8113         REG_WR(sc, reg_offset, val);
8114 
8115         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8116               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8117         bxe_panic(sc, ("HW block attention set2\n"));
8118     }
8119 }
8120 
8121 static void
8122 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8123                          uint32_t         attn)
8124 {
8125     int port = SC_PORT(sc);
8126     int reg_offset;
8127     uint32_t val;
8128 
8129     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8130         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8131         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8132         /* DORQ discard attention */
8133         if (val & 0x2) {
8134             BLOGE(sc, "FATAL error from DORQ\n");
8135         }
8136     }
8137 
8138     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8139         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8140                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8141 
8142         val = REG_RD(sc, reg_offset);
8143         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8144         REG_WR(sc, reg_offset, val);
8145 
8146         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8147               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8148         bxe_panic(sc, ("HW block attention set1\n"));
8149     }
8150 }
8151 
8152 static void
8153 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8154                          uint32_t         attn)
8155 {
8156     int port = SC_PORT(sc);
8157     int reg_offset;
8158     uint32_t val;
8159 
8160     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8161                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8162 
8163     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8164         val = REG_RD(sc, reg_offset);
8165         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8166         REG_WR(sc, reg_offset, val);
8167 
8168         BLOGW(sc, "SPIO5 hw attention\n");
8169 
8170         /* Fan failure attention */
8171         elink_hw_reset_phy(&sc->link_params);
8172         bxe_fan_failure(sc);
8173     }
8174 
8175     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8176 	bxe_acquire_phy_lock(sc);
8177         elink_handle_module_detect_int(&sc->link_params);
8178 	bxe_release_phy_lock(sc);
8179     }
8180 
8181     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8182         val = REG_RD(sc, reg_offset);
8183         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8184         REG_WR(sc, reg_offset, val);
8185 
8186         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8187                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8188     }
8189 }
8190 
8191 static void
8192 bxe_attn_int_deasserted(struct bxe_softc *sc,
8193                         uint32_t         deasserted)
8194 {
8195     struct attn_route attn;
8196     struct attn_route *group_mask;
8197     int port = SC_PORT(sc);
8198     int index;
8199     uint32_t reg_addr;
8200     uint32_t val;
8201     uint32_t aeu_mask;
8202     uint8_t global = FALSE;
8203 
8204     /*
8205      * Need to take HW lock because MCP or other port might also
8206      * try to handle this event.
8207      */
8208     bxe_acquire_alr(sc);
8209 
8210     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8211         /* XXX
8212          * In case of parity errors don't handle attentions so that
8213          * other function would "see" parity errors.
8214          */
8215         sc->recovery_state = BXE_RECOVERY_INIT;
8216         // XXX schedule a recovery task...
8217         /* disable HW interrupts */
8218         bxe_int_disable(sc);
8219         bxe_release_alr(sc);
8220         return;
8221     }
8222 
8223     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8224     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8225     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8226     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8227     if (!CHIP_IS_E1x(sc)) {
8228         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8229     } else {
8230         attn.sig[4] = 0;
8231     }
8232 
8233     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8234           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8235 
8236     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8237         if (deasserted & (1 << index)) {
8238             group_mask = &sc->attn_group[index];
8239 
8240             BLOGD(sc, DBG_INTR,
8241                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8242                   group_mask->sig[0], group_mask->sig[1],
8243                   group_mask->sig[2], group_mask->sig[3],
8244                   group_mask->sig[4]);
8245 
8246             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8247             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8248             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8249             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8250             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8251         }
8252     }
8253 
8254     bxe_release_alr(sc);
8255 
8256     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8257         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8258                     COMMAND_REG_ATTN_BITS_CLR);
8259     } else {
8260         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8261     }
8262 
8263     val = ~deasserted;
8264     BLOGD(sc, DBG_INTR,
8265           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8266           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8267     REG_WR(sc, reg_addr, val);
8268 
8269     if (~sc->attn_state & deasserted) {
8270         BLOGE(sc, "IGU error\n");
8271     }
8272 
8273     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8274                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8275 
8276     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8277 
8278     aeu_mask = REG_RD(sc, reg_addr);
8279 
8280     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8281           aeu_mask, deasserted);
8282     aeu_mask |= (deasserted & 0x3ff);
8283     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8284 
8285     REG_WR(sc, reg_addr, aeu_mask);
8286     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8287 
8288     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8289     sc->attn_state &= ~deasserted;
8290     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8291 }
8292 
8293 static void
8294 bxe_attn_int(struct bxe_softc *sc)
8295 {
8296     /* read local copy of bits */
8297     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8298     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8299     uint32_t attn_state = sc->attn_state;
8300 
8301     /* look for changed bits */
8302     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8303     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8304 
8305     BLOGD(sc, DBG_INTR,
8306           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8307           attn_bits, attn_ack, asserted, deasserted);
8308 
8309     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8310         BLOGE(sc, "BAD attention state\n");
8311     }
8312 
8313     /* handle bits that were raised */
8314     if (asserted) {
8315         bxe_attn_int_asserted(sc, asserted);
8316     }
8317 
8318     if (deasserted) {
8319         bxe_attn_int_deasserted(sc, deasserted);
8320     }
8321 }
8322 
8323 static uint16_t
8324 bxe_update_dsb_idx(struct bxe_softc *sc)
8325 {
8326     struct host_sp_status_block *def_sb = sc->def_sb;
8327     uint16_t rc = 0;
8328 
8329     mb(); /* status block is written to by the chip */
8330 
8331     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8332         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8333         rc |= BXE_DEF_SB_ATT_IDX;
8334     }
8335 
8336     if (sc->def_idx != def_sb->sp_sb.running_index) {
8337         sc->def_idx = def_sb->sp_sb.running_index;
8338         rc |= BXE_DEF_SB_IDX;
8339     }
8340 
8341     mb();
8342 
8343     return (rc);
8344 }
8345 
8346 static inline struct ecore_queue_sp_obj *
8347 bxe_cid_to_q_obj(struct bxe_softc *sc,
8348                  uint32_t         cid)
8349 {
8350     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8351     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8352 }
8353 
8354 static void
8355 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8356 {
8357     struct ecore_mcast_ramrod_params rparam;
8358     int rc;
8359 
8360     memset(&rparam, 0, sizeof(rparam));
8361 
8362     rparam.mcast_obj = &sc->mcast_obj;
8363 
8364     BXE_MCAST_LOCK(sc);
8365 
8366     /* clear pending state for the last command */
8367     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8368 
8369     /* if there are pending mcast commands - send them */
8370     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8371         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8372         if (rc < 0) {
8373             BLOGD(sc, DBG_SP,
8374                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8375         }
8376     }
8377 
8378     BXE_MCAST_UNLOCK(sc);
8379 }
8380 
8381 static void
8382 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8383                               union event_ring_elem *elem)
8384 {
8385     unsigned long ramrod_flags = 0;
8386     int rc = 0;
8387     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8388     struct ecore_vlan_mac_obj *vlan_mac_obj;
8389 
8390     /* always push next commands out, don't wait here */
8391     bit_set(&ramrod_flags, RAMROD_CONT);
8392 
8393     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8394     case ECORE_FILTER_MAC_PENDING:
8395         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8396         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8397         break;
8398 
8399     case ECORE_FILTER_MCAST_PENDING:
8400         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8401         /*
8402          * This is only relevant for 57710 where multicast MACs are
8403          * configured as unicast MACs using the same ramrod.
8404          */
8405         bxe_handle_mcast_eqe(sc);
8406         return;
8407 
8408     default:
8409         BLOGE(sc, "Unsupported classification command: %d\n",
8410               elem->message.data.eth_event.echo);
8411         return;
8412     }
8413 
8414     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8415 
8416     if (rc < 0) {
8417         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8418     } else if (rc > 0) {
8419         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8420     }
8421 }
8422 
8423 static void
8424 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8425                        union event_ring_elem *elem)
8426 {
8427     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8428 
8429     /* send rx_mode command again if was requested */
8430     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8431                                &sc->sp_state)) {
8432         bxe_set_storm_rx_mode(sc);
8433     }
8434 }
8435 
8436 static void
8437 bxe_update_eq_prod(struct bxe_softc *sc,
8438                    uint16_t         prod)
8439 {
8440     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8441     wmb(); /* keep prod updates ordered */
8442 }
8443 
8444 static void
8445 bxe_eq_int(struct bxe_softc *sc)
8446 {
8447     uint16_t hw_cons, sw_cons, sw_prod;
8448     union event_ring_elem *elem;
8449     uint8_t echo;
8450     uint32_t cid;
8451     uint8_t opcode;
8452     int spqe_cnt = 0;
8453     struct ecore_queue_sp_obj *q_obj;
8454     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8455     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8456 
8457     hw_cons = le16toh(*sc->eq_cons_sb);
8458 
8459     /*
8460      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8461      * when we get to the next-page we need to adjust so the loop
8462      * condition below will be met. The next element is the size of a
8463      * regular element and hence incrementing by 1
8464      */
8465     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8466         hw_cons++;
8467     }
8468 
8469     /*
8470      * This function may never run in parallel with itself for a
8471      * specific sc and no need for a read memory barrier here.
8472      */
8473     sw_cons = sc->eq_cons;
8474     sw_prod = sc->eq_prod;
8475 
8476     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8477           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8478 
8479     for (;
8480          sw_cons != hw_cons;
8481          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8482 
8483         elem = &sc->eq[EQ_DESC(sw_cons)];
8484 
8485         /* elem CID originates from FW, actually LE */
8486         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8487         opcode = elem->message.opcode;
8488 
8489         /* handle eq element */
8490         switch (opcode) {
8491 
8492         case EVENT_RING_OPCODE_STAT_QUERY:
8493             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8494                   sc->stats_comp++);
8495             /* nothing to do with stats comp */
8496             goto next_spqe;
8497 
8498         case EVENT_RING_OPCODE_CFC_DEL:
8499             /* handle according to cid range */
8500             /* we may want to verify here that the sc state is HALTING */
8501             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8502             q_obj = bxe_cid_to_q_obj(sc, cid);
8503             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8504                 break;
8505             }
8506             goto next_spqe;
8507 
8508         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8509             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8510             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8511                 break;
8512             }
8513             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8514             goto next_spqe;
8515 
8516         case EVENT_RING_OPCODE_START_TRAFFIC:
8517             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8518             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8519                 break;
8520             }
8521             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8522             goto next_spqe;
8523 
8524         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8525             echo = elem->message.data.function_update_event.echo;
8526             if (echo == SWITCH_UPDATE) {
8527                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8528                 if (f_obj->complete_cmd(sc, f_obj,
8529                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8530                     break;
8531                 }
8532             }
8533             else {
8534                 BLOGD(sc, DBG_SP,
8535                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8536             }
8537             goto next_spqe;
8538 
8539         case EVENT_RING_OPCODE_FORWARD_SETUP:
8540             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8541             if (q_obj->complete_cmd(sc, q_obj,
8542                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8543                 break;
8544             }
8545             goto next_spqe;
8546 
8547         case EVENT_RING_OPCODE_FUNCTION_START:
8548             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8549             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8550                 break;
8551             }
8552             goto next_spqe;
8553 
8554         case EVENT_RING_OPCODE_FUNCTION_STOP:
8555             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8556             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8557                 break;
8558             }
8559             goto next_spqe;
8560         }
8561 
8562         switch (opcode | sc->state) {
8563         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8564         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8565             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8566             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8567             rss_raw->clear_pending(rss_raw);
8568             break;
8569 
8570         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8571         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8572         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8573         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8574         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8575         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8576             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8577             bxe_handle_classification_eqe(sc, elem);
8578             break;
8579 
8580         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8581         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8582         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8583             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8584             bxe_handle_mcast_eqe(sc);
8585             break;
8586 
8587         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8588         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8589         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8590             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8591             bxe_handle_rx_mode_eqe(sc, elem);
8592             break;
8593 
8594         default:
8595             /* unknown event log error and continue */
8596             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8597                   elem->message.opcode, sc->state);
8598         }
8599 
8600 next_spqe:
8601         spqe_cnt++;
8602     } /* for */
8603 
8604     mb();
8605     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8606 
8607     sc->eq_cons = sw_cons;
8608     sc->eq_prod = sw_prod;
8609 
8610     /* make sure that above mem writes were issued towards the memory */
8611     wmb();
8612 
8613     /* update producer */
8614     bxe_update_eq_prod(sc, sc->eq_prod);
8615 }
8616 
8617 static void
8618 bxe_handle_sp_tq(void *context,
8619                  int  pending)
8620 {
8621     struct bxe_softc *sc = (struct bxe_softc *)context;
8622     uint16_t status;
8623 
8624     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8625 
8626     /* what work needs to be performed? */
8627     status = bxe_update_dsb_idx(sc);
8628 
8629     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8630 
8631     /* HW attentions */
8632     if (status & BXE_DEF_SB_ATT_IDX) {
8633         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8634         bxe_attn_int(sc);
8635         status &= ~BXE_DEF_SB_ATT_IDX;
8636     }
8637 
8638     /* SP events: STAT_QUERY and others */
8639     if (status & BXE_DEF_SB_IDX) {
8640         /* handle EQ completions */
8641         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8642         bxe_eq_int(sc);
8643         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8644                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8645         status &= ~BXE_DEF_SB_IDX;
8646     }
8647 
8648     /* if status is non zero then something went wrong */
8649     if (__predict_false(status)) {
8650         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8651     }
8652 
8653     /* ack status block only if something was actually handled */
8654     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8655                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8656 
8657     /*
8658      * Must be called after the EQ processing (since eq leads to sriov
8659      * ramrod completion flows).
8660      * This flow may have been scheduled by the arrival of a ramrod
8661      * completion, or by the sriov code rescheduling itself.
8662      */
8663     // XXX bxe_iov_sp_task(sc);
8664 
8665 }
8666 
8667 static void
8668 bxe_handle_fp_tq(void *context,
8669                  int  pending)
8670 {
8671     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8672     struct bxe_softc *sc = fp->sc;
8673     uint8_t more_tx = FALSE;
8674     uint8_t more_rx = FALSE;
8675 
8676     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8677 
8678     /* XXX
8679      * IFF_DRV_RUNNING state can't be checked here since we process
8680      * slowpath events on a client queue during setup. Instead
8681      * we need to add a "process/continue" flag here that the driver
8682      * can use to tell the task here not to do anything.
8683      */
8684 #if 0
8685     if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8686         return;
8687     }
8688 #endif
8689 
8690     /* update the fastpath index */
8691     bxe_update_fp_sb_idx(fp);
8692 
8693     /* XXX add loop here if ever support multiple tx CoS */
8694     /* fp->txdata[cos] */
8695     if (bxe_has_tx_work(fp)) {
8696         BXE_FP_TX_LOCK(fp);
8697         more_tx = bxe_txeof(sc, fp);
8698         BXE_FP_TX_UNLOCK(fp);
8699     }
8700 
8701     if (bxe_has_rx_work(fp)) {
8702         more_rx = bxe_rxeof(sc, fp);
8703     }
8704 
8705     if (more_rx /*|| more_tx*/) {
8706         /* still more work to do */
8707         taskqueue_enqueue(fp->tq, &fp->tq_task);
8708         return;
8709     }
8710 
8711     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8712                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8713 }
8714 
8715 static void
8716 bxe_task_fp(struct bxe_fastpath *fp)
8717 {
8718     struct bxe_softc *sc = fp->sc;
8719     uint8_t more_tx = FALSE;
8720     uint8_t more_rx = FALSE;
8721 
8722     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8723 
8724     /* update the fastpath index */
8725     bxe_update_fp_sb_idx(fp);
8726 
8727     /* XXX add loop here if ever support multiple tx CoS */
8728     /* fp->txdata[cos] */
8729     if (bxe_has_tx_work(fp)) {
8730         BXE_FP_TX_LOCK(fp);
8731         more_tx = bxe_txeof(sc, fp);
8732         BXE_FP_TX_UNLOCK(fp);
8733     }
8734 
8735     if (bxe_has_rx_work(fp)) {
8736         more_rx = bxe_rxeof(sc, fp);
8737     }
8738 
8739     if (more_rx /*|| more_tx*/) {
8740         /* still more work to do, bail out if this ISR and process later */
8741         taskqueue_enqueue(fp->tq, &fp->tq_task);
8742         return;
8743     }
8744 
8745     /*
8746      * Here we write the fastpath index taken before doing any tx or rx work.
8747      * It is very well possible other hw events occurred up to this point and
8748      * they were actually processed accordingly above. Since we're going to
8749      * write an older fastpath index, an interrupt is coming which we might
8750      * not do any work in.
8751      */
8752     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8753                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8754 }
8755 
8756 /*
8757  * Legacy interrupt entry point.
8758  *
8759  * Verifies that the controller generated the interrupt and
8760  * then calls a separate routine to handle the various
8761  * interrupt causes: link, RX, and TX.
8762  */
8763 static void
8764 bxe_intr_legacy(void *xsc)
8765 {
8766     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8767     struct bxe_fastpath *fp;
8768     uint16_t status, mask;
8769     int i;
8770 
8771     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8772 
8773     /*
8774      * 0 for ustorm, 1 for cstorm
8775      * the bits returned from ack_int() are 0-15
8776      * bit 0 = attention status block
8777      * bit 1 = fast path status block
8778      * a mask of 0x2 or more = tx/rx event
8779      * a mask of 1 = slow path event
8780      */
8781 
8782     status = bxe_ack_int(sc);
8783 
8784     /* the interrupt is not for us */
8785     if (__predict_false(status == 0)) {
8786         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8787         return;
8788     }
8789 
8790     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8791 
8792     FOR_EACH_ETH_QUEUE(sc, i) {
8793         fp = &sc->fp[i];
8794         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8795         if (status & mask) {
8796             /* acknowledge and disable further fastpath interrupts */
8797             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8798             bxe_task_fp(fp);
8799             status &= ~mask;
8800         }
8801     }
8802 
8803     if (__predict_false(status & 0x1)) {
8804         /* acknowledge and disable further slowpath interrupts */
8805         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8806 
8807         /* schedule slowpath handler */
8808         taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8809 
8810         status &= ~0x1;
8811     }
8812 
8813     if (__predict_false(status)) {
8814         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8815     }
8816 }
8817 
8818 /* slowpath interrupt entry point */
8819 static void
8820 bxe_intr_sp(void *xsc)
8821 {
8822     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8823 
8824     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8825 
8826     /* acknowledge and disable further slowpath interrupts */
8827     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8828 
8829     /* schedule slowpath handler */
8830     taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8831 }
8832 
8833 /* fastpath interrupt entry point */
8834 static void
8835 bxe_intr_fp(void *xfp)
8836 {
8837     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8838     struct bxe_softc *sc = fp->sc;
8839 
8840     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8841 
8842     BLOGD(sc, DBG_INTR,
8843           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8844           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8845 
8846     /* acknowledge and disable further fastpath interrupts */
8847     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8848 
8849     bxe_task_fp(fp);
8850 }
8851 
8852 /* Release all interrupts allocated by the driver. */
8853 static void
8854 bxe_interrupt_free(struct bxe_softc *sc)
8855 {
8856     int i;
8857 
8858     switch (sc->interrupt_mode) {
8859     case INTR_MODE_INTX:
8860         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8861         if (sc->intr[0].resource != NULL) {
8862             bus_release_resource(sc->dev,
8863                                  SYS_RES_IRQ,
8864                                  sc->intr[0].rid,
8865                                  sc->intr[0].resource);
8866         }
8867         break;
8868     case INTR_MODE_MSI:
8869         for (i = 0; i < sc->intr_count; i++) {
8870             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8871             if (sc->intr[i].resource && sc->intr[i].rid) {
8872                 bus_release_resource(sc->dev,
8873                                      SYS_RES_IRQ,
8874                                      sc->intr[i].rid,
8875                                      sc->intr[i].resource);
8876             }
8877         }
8878         pci_release_msi(sc->dev);
8879         break;
8880     case INTR_MODE_MSIX:
8881         for (i = 0; i < sc->intr_count; i++) {
8882             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8883             if (sc->intr[i].resource && sc->intr[i].rid) {
8884                 bus_release_resource(sc->dev,
8885                                      SYS_RES_IRQ,
8886                                      sc->intr[i].rid,
8887                                      sc->intr[i].resource);
8888             }
8889         }
8890         pci_release_msi(sc->dev);
8891         break;
8892     default:
8893         /* nothing to do as initial allocation failed */
8894         break;
8895     }
8896 }
8897 
8898 /*
8899  * This function determines and allocates the appropriate
8900  * interrupt based on system capabilites and user request.
8901  *
8902  * The user may force a particular interrupt mode, specify
8903  * the number of receive queues, specify the method for
8904  * distribuitng received frames to receive queues, or use
8905  * the default settings which will automatically select the
8906  * best supported combination.  In addition, the OS may or
8907  * may not support certain combinations of these settings.
8908  * This routine attempts to reconcile the settings requested
8909  * by the user with the capabilites available from the system
8910  * to select the optimal combination of features.
8911  *
8912  * Returns:
8913  *   0 = Success, !0 = Failure.
8914  */
8915 static int
8916 bxe_interrupt_alloc(struct bxe_softc *sc)
8917 {
8918     int msix_count = 0;
8919     int msi_count = 0;
8920     int num_requested = 0;
8921     int num_allocated = 0;
8922     int rid, i, j;
8923     int rc;
8924 
8925     /* get the number of available MSI/MSI-X interrupts from the OS */
8926     if (sc->interrupt_mode > 0) {
8927         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8928             msix_count = pci_msix_count(sc->dev);
8929         }
8930 
8931         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8932             msi_count = pci_msi_count(sc->dev);
8933         }
8934 
8935         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8936               msi_count, msix_count);
8937     }
8938 
8939     do { /* try allocating MSI-X interrupt resources (at least 2) */
8940         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8941             break;
8942         }
8943 
8944         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8945             (msix_count < 2)) {
8946             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8947             break;
8948         }
8949 
8950         /* ask for the necessary number of MSI-X vectors */
8951         num_requested = min((sc->num_queues + 1), msix_count);
8952 
8953         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8954 
8955         num_allocated = num_requested;
8956         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8957             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8958             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8959             break;
8960         }
8961 
8962         if (num_allocated < 2) { /* possible? */
8963             BLOGE(sc, "MSI-X allocation less than 2!\n");
8964             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8965             pci_release_msi(sc->dev);
8966             break;
8967         }
8968 
8969         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8970               num_requested, num_allocated);
8971 
8972         /* best effort so use the number of vectors allocated to us */
8973         sc->intr_count = num_allocated;
8974         sc->num_queues = num_allocated - 1;
8975 
8976         rid = 1; /* initial resource identifier */
8977 
8978         /* allocate the MSI-X vectors */
8979         for (i = 0; i < num_allocated; i++) {
8980             sc->intr[i].rid = (rid + i);
8981 
8982             if ((sc->intr[i].resource =
8983                  bus_alloc_resource_any(sc->dev,
8984                                         SYS_RES_IRQ,
8985                                         &sc->intr[i].rid,
8986                                         RF_ACTIVE)) == NULL) {
8987                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8988                       i, (rid + i));
8989 
8990                 for (j = (i - 1); j >= 0; j--) {
8991                     bus_release_resource(sc->dev,
8992                                          SYS_RES_IRQ,
8993                                          sc->intr[j].rid,
8994                                          sc->intr[j].resource);
8995                 }
8996 
8997                 sc->intr_count = 0;
8998                 sc->num_queues = 0;
8999                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9000                 pci_release_msi(sc->dev);
9001                 break;
9002             }
9003 
9004             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9005         }
9006     } while (0);
9007 
9008     do { /* try allocating MSI vector resources (at least 2) */
9009         if (sc->interrupt_mode != INTR_MODE_MSI) {
9010             break;
9011         }
9012 
9013         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9014             (msi_count < 1)) {
9015             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9016             break;
9017         }
9018 
9019         /* ask for a single MSI vector */
9020         num_requested = 1;
9021 
9022         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9023 
9024         num_allocated = num_requested;
9025         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9026             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9027             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9028             break;
9029         }
9030 
9031         if (num_allocated != 1) { /* possible? */
9032             BLOGE(sc, "MSI allocation is not 1!\n");
9033             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9034             pci_release_msi(sc->dev);
9035             break;
9036         }
9037 
9038         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9039               num_requested, num_allocated);
9040 
9041         /* best effort so use the number of vectors allocated to us */
9042         sc->intr_count = num_allocated;
9043         sc->num_queues = num_allocated;
9044 
9045         rid = 1; /* initial resource identifier */
9046 
9047         sc->intr[0].rid = rid;
9048 
9049         if ((sc->intr[0].resource =
9050              bus_alloc_resource_any(sc->dev,
9051                                     SYS_RES_IRQ,
9052                                     &sc->intr[0].rid,
9053                                     RF_ACTIVE)) == NULL) {
9054             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9055             sc->intr_count = 0;
9056             sc->num_queues = 0;
9057             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9058             pci_release_msi(sc->dev);
9059             break;
9060         }
9061 
9062         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9063     } while (0);
9064 
9065     do { /* try allocating INTx vector resources */
9066         if (sc->interrupt_mode != INTR_MODE_INTX) {
9067             break;
9068         }
9069 
9070         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9071 
9072         /* only one vector for INTx */
9073         sc->intr_count = 1;
9074         sc->num_queues = 1;
9075 
9076         rid = 0; /* initial resource identifier */
9077 
9078         sc->intr[0].rid = rid;
9079 
9080         if ((sc->intr[0].resource =
9081              bus_alloc_resource_any(sc->dev,
9082                                     SYS_RES_IRQ,
9083                                     &sc->intr[0].rid,
9084                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9085             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9086             sc->intr_count = 0;
9087             sc->num_queues = 0;
9088             sc->interrupt_mode = -1; /* Failed! */
9089             break;
9090         }
9091 
9092         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9093     } while (0);
9094 
9095     if (sc->interrupt_mode == -1) {
9096         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9097         rc = 1;
9098     } else {
9099         BLOGD(sc, DBG_LOAD,
9100               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9101               sc->interrupt_mode, sc->num_queues);
9102         rc = 0;
9103     }
9104 
9105     return (rc);
9106 }
9107 
9108 static void
9109 bxe_interrupt_detach(struct bxe_softc *sc)
9110 {
9111     struct bxe_fastpath *fp;
9112     int i;
9113 
9114     /* release interrupt resources */
9115     for (i = 0; i < sc->intr_count; i++) {
9116         if (sc->intr[i].resource && sc->intr[i].tag) {
9117             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9118             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9119         }
9120     }
9121 
9122     for (i = 0; i < sc->num_queues; i++) {
9123         fp = &sc->fp[i];
9124         if (fp->tq) {
9125             taskqueue_drain(fp->tq, &fp->tq_task);
9126             taskqueue_drain(fp->tq, &fp->tx_task);
9127             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9128                 NULL))
9129                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9130             taskqueue_free(fp->tq);
9131             fp->tq = NULL;
9132         }
9133     }
9134 
9135 
9136     if (sc->sp_tq) {
9137         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9138         taskqueue_free(sc->sp_tq);
9139         sc->sp_tq = NULL;
9140     }
9141 }
9142 
9143 /*
9144  * Enables interrupts and attach to the ISR.
9145  *
9146  * When using multiple MSI/MSI-X vectors the first vector
9147  * is used for slowpath operations while all remaining
9148  * vectors are used for fastpath operations.  If only a
9149  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9150  * ISR must look for both slowpath and fastpath completions.
9151  */
9152 static int
9153 bxe_interrupt_attach(struct bxe_softc *sc)
9154 {
9155     struct bxe_fastpath *fp;
9156     int rc = 0;
9157     int i;
9158 
9159     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9160              "bxe%d_sp_tq", sc->unit);
9161     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9162     sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9163                                  taskqueue_thread_enqueue,
9164                                  &sc->sp_tq);
9165     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9166                             "%s", sc->sp_tq_name);
9167 
9168 
9169     for (i = 0; i < sc->num_queues; i++) {
9170         fp = &sc->fp[i];
9171         snprintf(fp->tq_name, sizeof(fp->tq_name),
9172                  "bxe%d_fp%d_tq", sc->unit, i);
9173         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9174         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9175         fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9176                                   taskqueue_thread_enqueue,
9177                                   &fp->tq);
9178         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9179                           bxe_tx_mq_start_deferred, fp);
9180         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9181                                 "%s", fp->tq_name);
9182     }
9183 
9184     /* setup interrupt handlers */
9185     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9186         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9187 
9188         /*
9189          * Setup the interrupt handler. Note that we pass the driver instance
9190          * to the interrupt handler for the slowpath.
9191          */
9192         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9193                                  (INTR_TYPE_NET | INTR_MPSAFE),
9194                                  NULL, bxe_intr_sp, sc,
9195                                  &sc->intr[0].tag)) != 0) {
9196             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9197             goto bxe_interrupt_attach_exit;
9198         }
9199 
9200         bus_describe_intr(sc->dev, sc->intr[0].resource,
9201                           sc->intr[0].tag, "sp");
9202 
9203         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9204 
9205         /* initialize the fastpath vectors (note the first was used for sp) */
9206         for (i = 0; i < sc->num_queues; i++) {
9207             fp = &sc->fp[i];
9208             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9209 
9210             /*
9211              * Setup the interrupt handler. Note that we pass the
9212              * fastpath context to the interrupt handler in this
9213              * case.
9214              */
9215             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9216                                      (INTR_TYPE_NET | INTR_MPSAFE),
9217                                      NULL, bxe_intr_fp, fp,
9218                                      &sc->intr[i + 1].tag)) != 0) {
9219                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9220                       (i + 1), rc);
9221                 goto bxe_interrupt_attach_exit;
9222             }
9223 
9224             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9225                               sc->intr[i + 1].tag, "fp%02d", i);
9226 
9227             /* bind the fastpath instance to a cpu */
9228             if (sc->num_queues > 1) {
9229                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9230             }
9231 
9232             fp->state = BXE_FP_STATE_IRQ;
9233         }
9234     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9235         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9236 
9237         /*
9238          * Setup the interrupt handler. Note that we pass the
9239          * driver instance to the interrupt handler which
9240          * will handle both the slowpath and fastpath.
9241          */
9242         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9243                                  (INTR_TYPE_NET | INTR_MPSAFE),
9244                                  NULL, bxe_intr_legacy, sc,
9245                                  &sc->intr[0].tag)) != 0) {
9246             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9247             goto bxe_interrupt_attach_exit;
9248         }
9249 
9250     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9251         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9252 
9253         /*
9254          * Setup the interrupt handler. Note that we pass the
9255          * driver instance to the interrupt handler which
9256          * will handle both the slowpath and fastpath.
9257          */
9258         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9259                                  (INTR_TYPE_NET | INTR_MPSAFE),
9260                                  NULL, bxe_intr_legacy, sc,
9261                                  &sc->intr[0].tag)) != 0) {
9262             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9263             goto bxe_interrupt_attach_exit;
9264         }
9265     }
9266 
9267 bxe_interrupt_attach_exit:
9268 
9269     return (rc);
9270 }
9271 
9272 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9273 static int  bxe_init_hw_common(struct bxe_softc *sc);
9274 static int  bxe_init_hw_port(struct bxe_softc *sc);
9275 static int  bxe_init_hw_func(struct bxe_softc *sc);
9276 static void bxe_reset_common(struct bxe_softc *sc);
9277 static void bxe_reset_port(struct bxe_softc *sc);
9278 static void bxe_reset_func(struct bxe_softc *sc);
9279 static int  bxe_gunzip_init(struct bxe_softc *sc);
9280 static void bxe_gunzip_end(struct bxe_softc *sc);
9281 static int  bxe_init_firmware(struct bxe_softc *sc);
9282 static void bxe_release_firmware(struct bxe_softc *sc);
9283 
9284 static struct
9285 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9286     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9287     .init_hw_cmn      = bxe_init_hw_common,
9288     .init_hw_port     = bxe_init_hw_port,
9289     .init_hw_func     = bxe_init_hw_func,
9290 
9291     .reset_hw_cmn     = bxe_reset_common,
9292     .reset_hw_port    = bxe_reset_port,
9293     .reset_hw_func    = bxe_reset_func,
9294 
9295     .gunzip_init      = bxe_gunzip_init,
9296     .gunzip_end       = bxe_gunzip_end,
9297 
9298     .init_fw          = bxe_init_firmware,
9299     .release_fw       = bxe_release_firmware,
9300 };
9301 
9302 static void
9303 bxe_init_func_obj(struct bxe_softc *sc)
9304 {
9305     sc->dmae_ready = 0;
9306 
9307     ecore_init_func_obj(sc,
9308                         &sc->func_obj,
9309                         BXE_SP(sc, func_rdata),
9310                         BXE_SP_MAPPING(sc, func_rdata),
9311                         BXE_SP(sc, func_afex_rdata),
9312                         BXE_SP_MAPPING(sc, func_afex_rdata),
9313                         &bxe_func_sp_drv);
9314 }
9315 
9316 static int
9317 bxe_init_hw(struct bxe_softc *sc,
9318             uint32_t         load_code)
9319 {
9320     struct ecore_func_state_params func_params = { NULL };
9321     int rc;
9322 
9323     /* prepare the parameters for function state transitions */
9324     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9325 
9326     func_params.f_obj = &sc->func_obj;
9327     func_params.cmd = ECORE_F_CMD_HW_INIT;
9328 
9329     func_params.params.hw_init.load_phase = load_code;
9330 
9331     /*
9332      * Via a plethora of function pointers, we will eventually reach
9333      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9334      */
9335     rc = ecore_func_state_change(sc, &func_params);
9336 
9337     return (rc);
9338 }
9339 
9340 static void
9341 bxe_fill(struct bxe_softc *sc,
9342          uint32_t         addr,
9343          int              fill,
9344          uint32_t         len)
9345 {
9346     uint32_t i;
9347 
9348     if (!(len % 4) && !(addr % 4)) {
9349         for (i = 0; i < len; i += 4) {
9350             REG_WR(sc, (addr + i), fill);
9351         }
9352     } else {
9353         for (i = 0; i < len; i++) {
9354             REG_WR8(sc, (addr + i), fill);
9355         }
9356     }
9357 }
9358 
9359 /* writes FP SP data to FW - data_size in dwords */
9360 static void
9361 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9362                   int              fw_sb_id,
9363                   uint32_t         *sb_data_p,
9364                   uint32_t         data_size)
9365 {
9366     int index;
9367 
9368     for (index = 0; index < data_size; index++) {
9369         REG_WR(sc,
9370                (BAR_CSTRORM_INTMEM +
9371                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9372                 (sizeof(uint32_t) * index)),
9373                *(sb_data_p + index));
9374     }
9375 }
9376 
9377 static void
9378 bxe_zero_fp_sb(struct bxe_softc *sc,
9379                int              fw_sb_id)
9380 {
9381     struct hc_status_block_data_e2 sb_data_e2;
9382     struct hc_status_block_data_e1x sb_data_e1x;
9383     uint32_t *sb_data_p;
9384     uint32_t data_size = 0;
9385 
9386     if (!CHIP_IS_E1x(sc)) {
9387         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9388         sb_data_e2.common.state = SB_DISABLED;
9389         sb_data_e2.common.p_func.vf_valid = FALSE;
9390         sb_data_p = (uint32_t *)&sb_data_e2;
9391         data_size = (sizeof(struct hc_status_block_data_e2) /
9392                      sizeof(uint32_t));
9393     } else {
9394         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9395         sb_data_e1x.common.state = SB_DISABLED;
9396         sb_data_e1x.common.p_func.vf_valid = FALSE;
9397         sb_data_p = (uint32_t *)&sb_data_e1x;
9398         data_size = (sizeof(struct hc_status_block_data_e1x) /
9399                      sizeof(uint32_t));
9400     }
9401 
9402     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9403 
9404     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9405              0, CSTORM_STATUS_BLOCK_SIZE);
9406     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9407              0, CSTORM_SYNC_BLOCK_SIZE);
9408 }
9409 
9410 static void
9411 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9412                   struct hc_sp_status_block_data *sp_sb_data)
9413 {
9414     int i;
9415 
9416     for (i = 0;
9417          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9418          i++) {
9419         REG_WR(sc,
9420                (BAR_CSTRORM_INTMEM +
9421                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9422                 (i * sizeof(uint32_t))),
9423                *((uint32_t *)sp_sb_data + i));
9424     }
9425 }
9426 
9427 static void
9428 bxe_zero_sp_sb(struct bxe_softc *sc)
9429 {
9430     struct hc_sp_status_block_data sp_sb_data;
9431 
9432     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9433 
9434     sp_sb_data.state           = SB_DISABLED;
9435     sp_sb_data.p_func.vf_valid = FALSE;
9436 
9437     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9438 
9439     bxe_fill(sc,
9440              (BAR_CSTRORM_INTMEM +
9441               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9442               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9443     bxe_fill(sc,
9444              (BAR_CSTRORM_INTMEM +
9445               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9446               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9447 }
9448 
9449 static void
9450 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9451                              int                       igu_sb_id,
9452                              int                       igu_seg_id)
9453 {
9454     hc_sm->igu_sb_id      = igu_sb_id;
9455     hc_sm->igu_seg_id     = igu_seg_id;
9456     hc_sm->timer_value    = 0xFF;
9457     hc_sm->time_to_expire = 0xFFFFFFFF;
9458 }
9459 
9460 static void
9461 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9462 {
9463     /* zero out state machine indices */
9464 
9465     /* rx indices */
9466     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9467 
9468     /* tx indices */
9469     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9470     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9471     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9472     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9473 
9474     /* map indices */
9475 
9476     /* rx indices */
9477     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9478         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9479 
9480     /* tx indices */
9481     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9482         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9483     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9484         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9485     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9486         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9487     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9488         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9489 }
9490 
9491 static void
9492 bxe_init_sb(struct bxe_softc *sc,
9493             bus_addr_t       busaddr,
9494             int              vfid,
9495             uint8_t          vf_valid,
9496             int              fw_sb_id,
9497             int              igu_sb_id)
9498 {
9499     struct hc_status_block_data_e2  sb_data_e2;
9500     struct hc_status_block_data_e1x sb_data_e1x;
9501     struct hc_status_block_sm       *hc_sm_p;
9502     uint32_t *sb_data_p;
9503     int igu_seg_id;
9504     int data_size;
9505 
9506     if (CHIP_INT_MODE_IS_BC(sc)) {
9507         igu_seg_id = HC_SEG_ACCESS_NORM;
9508     } else {
9509         igu_seg_id = IGU_SEG_ACCESS_NORM;
9510     }
9511 
9512     bxe_zero_fp_sb(sc, fw_sb_id);
9513 
9514     if (!CHIP_IS_E1x(sc)) {
9515         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9516         sb_data_e2.common.state = SB_ENABLED;
9517         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9518         sb_data_e2.common.p_func.vf_id = vfid;
9519         sb_data_e2.common.p_func.vf_valid = vf_valid;
9520         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9521         sb_data_e2.common.same_igu_sb_1b = TRUE;
9522         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9523         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9524         hc_sm_p = sb_data_e2.common.state_machine;
9525         sb_data_p = (uint32_t *)&sb_data_e2;
9526         data_size = (sizeof(struct hc_status_block_data_e2) /
9527                      sizeof(uint32_t));
9528         bxe_map_sb_state_machines(sb_data_e2.index_data);
9529     } else {
9530         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9531         sb_data_e1x.common.state = SB_ENABLED;
9532         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9533         sb_data_e1x.common.p_func.vf_id = 0xff;
9534         sb_data_e1x.common.p_func.vf_valid = FALSE;
9535         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9536         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9537         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9538         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9539         hc_sm_p = sb_data_e1x.common.state_machine;
9540         sb_data_p = (uint32_t *)&sb_data_e1x;
9541         data_size = (sizeof(struct hc_status_block_data_e1x) /
9542                      sizeof(uint32_t));
9543         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9544     }
9545 
9546     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9547     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9548 
9549     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9550 
9551     /* write indices to HW - PCI guarantees endianity of regpairs */
9552     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9553 }
9554 
9555 static inline uint8_t
9556 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9557 {
9558     if (CHIP_IS_E1x(fp->sc)) {
9559         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9560     } else {
9561         return (fp->cl_id);
9562     }
9563 }
9564 
9565 static inline uint32_t
9566 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9567                            struct bxe_fastpath *fp)
9568 {
9569     uint32_t offset = BAR_USTRORM_INTMEM;
9570 
9571     if (!CHIP_IS_E1x(sc)) {
9572         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9573     } else {
9574         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9575     }
9576 
9577     return (offset);
9578 }
9579 
9580 static void
9581 bxe_init_eth_fp(struct bxe_softc *sc,
9582                 int              idx)
9583 {
9584     struct bxe_fastpath *fp = &sc->fp[idx];
9585     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9586     unsigned long q_type = 0;
9587     int cos;
9588 
9589     fp->sc    = sc;
9590     fp->index = idx;
9591 
9592     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9593     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9594 
9595     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9596                     (SC_L_ID(sc) + idx) :
9597                     /* want client ID same as IGU SB ID for non-E1 */
9598                     fp->igu_sb_id;
9599     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9600 
9601     /* setup sb indices */
9602     if (!CHIP_IS_E1x(sc)) {
9603         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9604         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9605     } else {
9606         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9607         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9608     }
9609 
9610     /* init shortcut */
9611     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9612 
9613     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9614 
9615     /*
9616      * XXX If multiple CoS is ever supported then each fastpath structure
9617      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9618      */
9619     for (cos = 0; cos < sc->max_cos; cos++) {
9620         cids[cos] = idx;
9621     }
9622     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9623 
9624     /* nothing more for a VF to do */
9625     if (IS_VF(sc)) {
9626         return;
9627     }
9628 
9629     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9630                 fp->fw_sb_id, fp->igu_sb_id);
9631 
9632     bxe_update_fp_sb_idx(fp);
9633 
9634     /* Configure Queue State object */
9635     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9636     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9637 
9638     ecore_init_queue_obj(sc,
9639                          &sc->sp_objs[idx].q_obj,
9640                          fp->cl_id,
9641                          cids,
9642                          sc->max_cos,
9643                          SC_FUNC(sc),
9644                          BXE_SP(sc, q_rdata),
9645                          BXE_SP_MAPPING(sc, q_rdata),
9646                          q_type);
9647 
9648     /* configure classification DBs */
9649     ecore_init_mac_obj(sc,
9650                        &sc->sp_objs[idx].mac_obj,
9651                        fp->cl_id,
9652                        idx,
9653                        SC_FUNC(sc),
9654                        BXE_SP(sc, mac_rdata),
9655                        BXE_SP_MAPPING(sc, mac_rdata),
9656                        ECORE_FILTER_MAC_PENDING,
9657                        &sc->sp_state,
9658                        ECORE_OBJ_TYPE_RX_TX,
9659                        &sc->macs_pool);
9660 
9661     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9662           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9663 }
9664 
9665 static inline void
9666 bxe_update_rx_prod(struct bxe_softc    *sc,
9667                    struct bxe_fastpath *fp,
9668                    uint16_t            rx_bd_prod,
9669                    uint16_t            rx_cq_prod,
9670                    uint16_t            rx_sge_prod)
9671 {
9672     struct ustorm_eth_rx_producers rx_prods = { 0 };
9673     uint32_t i;
9674 
9675     /* update producers */
9676     rx_prods.bd_prod  = rx_bd_prod;
9677     rx_prods.cqe_prod = rx_cq_prod;
9678     rx_prods.sge_prod = rx_sge_prod;
9679 
9680     /*
9681      * Make sure that the BD and SGE data is updated before updating the
9682      * producers since FW might read the BD/SGE right after the producer
9683      * is updated.
9684      * This is only applicable for weak-ordered memory model archs such
9685      * as IA-64. The following barrier is also mandatory since FW will
9686      * assumes BDs must have buffers.
9687      */
9688     wmb();
9689 
9690     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9691         REG_WR(sc,
9692                (fp->ustorm_rx_prods_offset + (i * 4)),
9693                ((uint32_t *)&rx_prods)[i]);
9694     }
9695 
9696     wmb(); /* keep prod updates ordered */
9697 
9698     BLOGD(sc, DBG_RX,
9699           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9700           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9701 }
9702 
9703 static void
9704 bxe_init_rx_rings(struct bxe_softc *sc)
9705 {
9706     struct bxe_fastpath *fp;
9707     int i;
9708 
9709     for (i = 0; i < sc->num_queues; i++) {
9710         fp = &sc->fp[i];
9711 
9712         fp->rx_bd_cons = 0;
9713 
9714         /*
9715          * Activate the BD ring...
9716          * Warning, this will generate an interrupt (to the TSTORM)
9717          * so this can only be done after the chip is initialized
9718          */
9719         bxe_update_rx_prod(sc, fp,
9720                            fp->rx_bd_prod,
9721                            fp->rx_cq_prod,
9722                            fp->rx_sge_prod);
9723 
9724         if (i != 0) {
9725             continue;
9726         }
9727 
9728         if (CHIP_IS_E1(sc)) {
9729             REG_WR(sc,
9730                    (BAR_USTRORM_INTMEM +
9731                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9732                    U64_LO(fp->rcq_dma.paddr));
9733             REG_WR(sc,
9734                    (BAR_USTRORM_INTMEM +
9735                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9736                    U64_HI(fp->rcq_dma.paddr));
9737         }
9738     }
9739 }
9740 
9741 static void
9742 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9743 {
9744     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9745     fp->tx_db.data.zero_fill1 = 0;
9746     fp->tx_db.data.prod = 0;
9747 
9748     fp->tx_pkt_prod = 0;
9749     fp->tx_pkt_cons = 0;
9750     fp->tx_bd_prod = 0;
9751     fp->tx_bd_cons = 0;
9752     fp->eth_q_stats.tx_pkts = 0;
9753 }
9754 
9755 static inline void
9756 bxe_init_tx_rings(struct bxe_softc *sc)
9757 {
9758     int i;
9759 
9760     for (i = 0; i < sc->num_queues; i++) {
9761         bxe_init_tx_ring_one(&sc->fp[i]);
9762     }
9763 }
9764 
9765 static void
9766 bxe_init_def_sb(struct bxe_softc *sc)
9767 {
9768     struct host_sp_status_block *def_sb = sc->def_sb;
9769     bus_addr_t mapping = sc->def_sb_dma.paddr;
9770     int igu_sp_sb_index;
9771     int igu_seg_id;
9772     int port = SC_PORT(sc);
9773     int func = SC_FUNC(sc);
9774     int reg_offset, reg_offset_en5;
9775     uint64_t section;
9776     int index, sindex;
9777     struct hc_sp_status_block_data sp_sb_data;
9778 
9779     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9780 
9781     if (CHIP_INT_MODE_IS_BC(sc)) {
9782         igu_sp_sb_index = DEF_SB_IGU_ID;
9783         igu_seg_id = HC_SEG_ACCESS_DEF;
9784     } else {
9785         igu_sp_sb_index = sc->igu_dsb_id;
9786         igu_seg_id = IGU_SEG_ACCESS_DEF;
9787     }
9788 
9789     /* attentions */
9790     section = ((uint64_t)mapping +
9791                offsetof(struct host_sp_status_block, atten_status_block));
9792     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9793     sc->attn_state = 0;
9794 
9795     reg_offset = (port) ?
9796                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9797                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9798     reg_offset_en5 = (port) ?
9799                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9800                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9801 
9802     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9803         /* take care of sig[0]..sig[4] */
9804         for (sindex = 0; sindex < 4; sindex++) {
9805             sc->attn_group[index].sig[sindex] =
9806                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9807         }
9808 
9809         if (!CHIP_IS_E1x(sc)) {
9810             /*
9811              * enable5 is separate from the rest of the registers,
9812              * and the address skip is 4 and not 16 between the
9813              * different groups
9814              */
9815             sc->attn_group[index].sig[4] =
9816                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9817         } else {
9818             sc->attn_group[index].sig[4] = 0;
9819         }
9820     }
9821 
9822     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9823         reg_offset = (port) ?
9824                          HC_REG_ATTN_MSG1_ADDR_L :
9825                          HC_REG_ATTN_MSG0_ADDR_L;
9826         REG_WR(sc, reg_offset, U64_LO(section));
9827         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9828     } else if (!CHIP_IS_E1x(sc)) {
9829         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9830         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9831     }
9832 
9833     section = ((uint64_t)mapping +
9834                offsetof(struct host_sp_status_block, sp_sb));
9835 
9836     bxe_zero_sp_sb(sc);
9837 
9838     /* PCI guarantees endianity of regpair */
9839     sp_sb_data.state           = SB_ENABLED;
9840     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9841     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9842     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9843     sp_sb_data.igu_seg_id      = igu_seg_id;
9844     sp_sb_data.p_func.pf_id    = func;
9845     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9846     sp_sb_data.p_func.vf_id    = 0xff;
9847 
9848     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9849 
9850     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9851 }
9852 
9853 static void
9854 bxe_init_sp_ring(struct bxe_softc *sc)
9855 {
9856     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9857     sc->spq_prod_idx = 0;
9858     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9859     sc->spq_prod_bd = sc->spq;
9860     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9861 }
9862 
9863 static void
9864 bxe_init_eq_ring(struct bxe_softc *sc)
9865 {
9866     union event_ring_elem *elem;
9867     int i;
9868 
9869     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9870         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9871 
9872         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9873                                                  BCM_PAGE_SIZE *
9874                                                  (i % NUM_EQ_PAGES)));
9875         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9876                                                  BCM_PAGE_SIZE *
9877                                                  (i % NUM_EQ_PAGES)));
9878     }
9879 
9880     sc->eq_cons    = 0;
9881     sc->eq_prod    = NUM_EQ_DESC;
9882     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9883 
9884     atomic_store_rel_long(&sc->eq_spq_left,
9885                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9886                                NUM_EQ_DESC) - 1));
9887 }
9888 
9889 static void
9890 bxe_init_internal_common(struct bxe_softc *sc)
9891 {
9892     int i;
9893 
9894     /*
9895      * Zero this manually as its initialization is currently missing
9896      * in the initTool.
9897      */
9898     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9899         REG_WR(sc,
9900                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9901                0);
9902     }
9903 
9904     if (!CHIP_IS_E1x(sc)) {
9905         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9906                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9907     }
9908 }
9909 
9910 static void
9911 bxe_init_internal(struct bxe_softc *sc,
9912                   uint32_t         load_code)
9913 {
9914     switch (load_code) {
9915     case FW_MSG_CODE_DRV_LOAD_COMMON:
9916     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9917         bxe_init_internal_common(sc);
9918         /* no break */
9919 
9920     case FW_MSG_CODE_DRV_LOAD_PORT:
9921         /* nothing to do */
9922         /* no break */
9923 
9924     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9925         /* internal memory per function is initialized inside bxe_pf_init */
9926         break;
9927 
9928     default:
9929         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9930         break;
9931     }
9932 }
9933 
9934 static void
9935 storm_memset_func_cfg(struct bxe_softc                         *sc,
9936                       struct tstorm_eth_function_common_config *tcfg,
9937                       uint16_t                                  abs_fid)
9938 {
9939     uint32_t addr;
9940     size_t size;
9941 
9942     addr = (BAR_TSTRORM_INTMEM +
9943             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9944     size = sizeof(struct tstorm_eth_function_common_config);
9945     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9946 }
9947 
9948 static void
9949 bxe_func_init(struct bxe_softc            *sc,
9950               struct bxe_func_init_params *p)
9951 {
9952     struct tstorm_eth_function_common_config tcfg = { 0 };
9953 
9954     if (CHIP_IS_E1x(sc)) {
9955         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9956     }
9957 
9958     /* Enable the function in the FW */
9959     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9960     storm_memset_func_en(sc, p->func_id, 1);
9961 
9962     /* spq */
9963     if (p->func_flgs & FUNC_FLG_SPQ) {
9964         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9965         REG_WR(sc,
9966                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9967                p->spq_prod);
9968     }
9969 }
9970 
9971 /*
9972  * Calculates the sum of vn_min_rates.
9973  * It's needed for further normalizing of the min_rates.
9974  * Returns:
9975  *   sum of vn_min_rates.
9976  *     or
9977  *   0 - if all the min_rates are 0.
9978  * In the later case fainess algorithm should be deactivated.
9979  * If all min rates are not zero then those that are zeroes will be set to 1.
9980  */
9981 static void
9982 bxe_calc_vn_min(struct bxe_softc       *sc,
9983                 struct cmng_init_input *input)
9984 {
9985     uint32_t vn_cfg;
9986     uint32_t vn_min_rate;
9987     int all_zero = 1;
9988     int vn;
9989 
9990     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9991         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9992         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9993                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9994 
9995         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9996             /* skip hidden VNs */
9997             vn_min_rate = 0;
9998         } else if (!vn_min_rate) {
9999             /* If min rate is zero - set it to 100 */
10000             vn_min_rate = DEF_MIN_RATE;
10001         } else {
10002             all_zero = 0;
10003         }
10004 
10005         input->vnic_min_rate[vn] = vn_min_rate;
10006     }
10007 
10008     /* if ETS or all min rates are zeros - disable fairness */
10009     if (BXE_IS_ETS_ENABLED(sc)) {
10010         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10011         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10012     } else if (all_zero) {
10013         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10014         BLOGD(sc, DBG_LOAD,
10015               "Fariness disabled (all MIN values are zeroes)\n");
10016     } else {
10017         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10018     }
10019 }
10020 
10021 static inline uint16_t
10022 bxe_extract_max_cfg(struct bxe_softc *sc,
10023                     uint32_t         mf_cfg)
10024 {
10025     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10026                         FUNC_MF_CFG_MAX_BW_SHIFT);
10027 
10028     if (!max_cfg) {
10029         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10030         max_cfg = 100;
10031     }
10032 
10033     return (max_cfg);
10034 }
10035 
10036 static void
10037 bxe_calc_vn_max(struct bxe_softc       *sc,
10038                 int                    vn,
10039                 struct cmng_init_input *input)
10040 {
10041     uint16_t vn_max_rate;
10042     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10043     uint32_t max_cfg;
10044 
10045     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10046         vn_max_rate = 0;
10047     } else {
10048         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10049 
10050         if (IS_MF_SI(sc)) {
10051             /* max_cfg in percents of linkspeed */
10052             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10053         } else { /* SD modes */
10054             /* max_cfg is absolute in 100Mb units */
10055             vn_max_rate = (max_cfg * 100);
10056         }
10057     }
10058 
10059     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10060 
10061     input->vnic_max_rate[vn] = vn_max_rate;
10062 }
10063 
10064 static void
10065 bxe_cmng_fns_init(struct bxe_softc *sc,
10066                   uint8_t          read_cfg,
10067                   uint8_t          cmng_type)
10068 {
10069     struct cmng_init_input input;
10070     int vn;
10071 
10072     memset(&input, 0, sizeof(struct cmng_init_input));
10073 
10074     input.port_rate = sc->link_vars.line_speed;
10075 
10076     if (cmng_type == CMNG_FNS_MINMAX) {
10077         /* read mf conf from shmem */
10078         if (read_cfg) {
10079             bxe_read_mf_cfg(sc);
10080         }
10081 
10082         /* get VN min rate and enable fairness if not 0 */
10083         bxe_calc_vn_min(sc, &input);
10084 
10085         /* get VN max rate */
10086         if (sc->port.pmf) {
10087             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10088                 bxe_calc_vn_max(sc, vn, &input);
10089             }
10090         }
10091 
10092         /* always enable rate shaping and fairness */
10093         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10094 
10095         ecore_init_cmng(&input, &sc->cmng);
10096         return;
10097     }
10098 
10099     /* rate shaping and fairness are disabled */
10100     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10101 }
10102 
10103 static int
10104 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10105 {
10106     if (CHIP_REV_IS_SLOW(sc)) {
10107         return (CMNG_FNS_NONE);
10108     }
10109 
10110     if (IS_MF(sc)) {
10111         return (CMNG_FNS_MINMAX);
10112     }
10113 
10114     return (CMNG_FNS_NONE);
10115 }
10116 
10117 static void
10118 storm_memset_cmng(struct bxe_softc *sc,
10119                   struct cmng_init *cmng,
10120                   uint8_t          port)
10121 {
10122     int vn;
10123     int func;
10124     uint32_t addr;
10125     size_t size;
10126 
10127     addr = (BAR_XSTRORM_INTMEM +
10128             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10129     size = sizeof(struct cmng_struct_per_port);
10130     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10131 
10132     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10133         func = func_by_vn(sc, vn);
10134 
10135         addr = (BAR_XSTRORM_INTMEM +
10136                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10137         size = sizeof(struct rate_shaping_vars_per_vn);
10138         ecore_storm_memset_struct(sc, addr, size,
10139                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10140 
10141         addr = (BAR_XSTRORM_INTMEM +
10142                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10143         size = sizeof(struct fairness_vars_per_vn);
10144         ecore_storm_memset_struct(sc, addr, size,
10145                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10146     }
10147 }
10148 
10149 static void
10150 bxe_pf_init(struct bxe_softc *sc)
10151 {
10152     struct bxe_func_init_params func_init = { 0 };
10153     struct event_ring_data eq_data = { { 0 } };
10154     uint16_t flags;
10155 
10156     if (!CHIP_IS_E1x(sc)) {
10157         /* reset IGU PF statistics: MSIX + ATTN */
10158         /* PF */
10159         REG_WR(sc,
10160                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10161                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10162                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10163                0);
10164         /* ATTN */
10165         REG_WR(sc,
10166                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10167                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10168                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10169                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10170                0);
10171     }
10172 
10173     /* function setup flags */
10174     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10175 
10176     /*
10177      * This flag is relevant for E1x only.
10178      * E2 doesn't have a TPA configuration in a function level.
10179      */
10180     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10181 
10182     func_init.func_flgs = flags;
10183     func_init.pf_id     = SC_FUNC(sc);
10184     func_init.func_id   = SC_FUNC(sc);
10185     func_init.spq_map   = sc->spq_dma.paddr;
10186     func_init.spq_prod  = sc->spq_prod_idx;
10187 
10188     bxe_func_init(sc, &func_init);
10189 
10190     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10191 
10192     /*
10193      * Congestion management values depend on the link rate.
10194      * There is no active link so initial link rate is set to 10Gbps.
10195      * When the link comes up the congestion management values are
10196      * re-calculated according to the actual link rate.
10197      */
10198     sc->link_vars.line_speed = SPEED_10000;
10199     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10200 
10201     /* Only the PMF sets the HW */
10202     if (sc->port.pmf) {
10203         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10204     }
10205 
10206     /* init Event Queue - PCI bus guarantees correct endainity */
10207     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10208     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10209     eq_data.producer     = sc->eq_prod;
10210     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10211     eq_data.sb_id        = DEF_SB_ID;
10212     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10213 }
10214 
10215 static void
10216 bxe_hc_int_enable(struct bxe_softc *sc)
10217 {
10218     int port = SC_PORT(sc);
10219     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10220     uint32_t val = REG_RD(sc, addr);
10221     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10222     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10223                            (sc->intr_count == 1)) ? TRUE : FALSE;
10224     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10225 
10226     if (msix) {
10227         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10228                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10229         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10230                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10231         if (single_msix) {
10232             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10233         }
10234     } else if (msi) {
10235         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10236         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10237                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10238                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10239     } else {
10240         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10241                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10242                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10243                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10244 
10245         if (!CHIP_IS_E1(sc)) {
10246             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10247                   val, port, addr);
10248 
10249             REG_WR(sc, addr, val);
10250 
10251             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10252         }
10253     }
10254 
10255     if (CHIP_IS_E1(sc)) {
10256         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10257     }
10258 
10259     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10260           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10261 
10262     REG_WR(sc, addr, val);
10263 
10264     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10265     mb();
10266 
10267     if (!CHIP_IS_E1(sc)) {
10268         /* init leading/trailing edge */
10269         if (IS_MF(sc)) {
10270             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10271             if (sc->port.pmf) {
10272                 /* enable nig and gpio3 attention */
10273                 val |= 0x1100;
10274             }
10275         } else {
10276             val = 0xffff;
10277         }
10278 
10279         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10280         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10281     }
10282 
10283     /* make sure that interrupts are indeed enabled from here on */
10284     mb();
10285 }
10286 
10287 static void
10288 bxe_igu_int_enable(struct bxe_softc *sc)
10289 {
10290     uint32_t val;
10291     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10292     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10293                            (sc->intr_count == 1)) ? TRUE : FALSE;
10294     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10295 
10296     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10297 
10298     if (msix) {
10299         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10300                  IGU_PF_CONF_SINGLE_ISR_EN);
10301         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10302                 IGU_PF_CONF_ATTN_BIT_EN);
10303         if (single_msix) {
10304             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10305         }
10306     } else if (msi) {
10307         val &= ~IGU_PF_CONF_INT_LINE_EN;
10308         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10309                 IGU_PF_CONF_ATTN_BIT_EN |
10310                 IGU_PF_CONF_SINGLE_ISR_EN);
10311     } else {
10312         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10313         val |= (IGU_PF_CONF_INT_LINE_EN |
10314                 IGU_PF_CONF_ATTN_BIT_EN |
10315                 IGU_PF_CONF_SINGLE_ISR_EN);
10316     }
10317 
10318     /* clean previous status - need to configure igu prior to ack*/
10319     if ((!msix) || single_msix) {
10320         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10321         bxe_ack_int(sc);
10322     }
10323 
10324     val |= IGU_PF_CONF_FUNC_EN;
10325 
10326     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10327           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10328 
10329     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10330 
10331     mb();
10332 
10333     /* init leading/trailing edge */
10334     if (IS_MF(sc)) {
10335         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10336         if (sc->port.pmf) {
10337             /* enable nig and gpio3 attention */
10338             val |= 0x1100;
10339         }
10340     } else {
10341         val = 0xffff;
10342     }
10343 
10344     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10345     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10346 
10347     /* make sure that interrupts are indeed enabled from here on */
10348     mb();
10349 }
10350 
10351 static void
10352 bxe_int_enable(struct bxe_softc *sc)
10353 {
10354     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10355         bxe_hc_int_enable(sc);
10356     } else {
10357         bxe_igu_int_enable(sc);
10358     }
10359 }
10360 
10361 static void
10362 bxe_hc_int_disable(struct bxe_softc *sc)
10363 {
10364     int port = SC_PORT(sc);
10365     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10366     uint32_t val = REG_RD(sc, addr);
10367 
10368     /*
10369      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10370      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10371      * block
10372      */
10373     if (CHIP_IS_E1(sc)) {
10374         /*
10375          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10376          * to prevent from HC sending interrupts after we exit the function
10377          */
10378         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10379 
10380         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10381                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10382                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10383     } else {
10384         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10385                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10386                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10387                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10388     }
10389 
10390     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10391 
10392     /* flush all outstanding writes */
10393     mb();
10394 
10395     REG_WR(sc, addr, val);
10396     if (REG_RD(sc, addr) != val) {
10397         BLOGE(sc, "proper val not read from HC IGU!\n");
10398     }
10399 }
10400 
10401 static void
10402 bxe_igu_int_disable(struct bxe_softc *sc)
10403 {
10404     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10405 
10406     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10407              IGU_PF_CONF_INT_LINE_EN |
10408              IGU_PF_CONF_ATTN_BIT_EN);
10409 
10410     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10411 
10412     /* flush all outstanding writes */
10413     mb();
10414 
10415     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10416     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10417         BLOGE(sc, "proper val not read from IGU!\n");
10418     }
10419 }
10420 
10421 static void
10422 bxe_int_disable(struct bxe_softc *sc)
10423 {
10424     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10425         bxe_hc_int_disable(sc);
10426     } else {
10427         bxe_igu_int_disable(sc);
10428     }
10429 }
10430 
10431 static void
10432 bxe_nic_init(struct bxe_softc *sc,
10433              int              load_code)
10434 {
10435     int i;
10436 
10437     for (i = 0; i < sc->num_queues; i++) {
10438         bxe_init_eth_fp(sc, i);
10439     }
10440 
10441     rmb(); /* ensure status block indices were read */
10442 
10443     bxe_init_rx_rings(sc);
10444     bxe_init_tx_rings(sc);
10445 
10446     if (IS_VF(sc)) {
10447         return;
10448     }
10449 
10450     /* initialize MOD_ABS interrupts */
10451     elink_init_mod_abs_int(sc, &sc->link_vars,
10452                            sc->devinfo.chip_id,
10453                            sc->devinfo.shmem_base,
10454                            sc->devinfo.shmem2_base,
10455                            SC_PORT(sc));
10456 
10457     bxe_init_def_sb(sc);
10458     bxe_update_dsb_idx(sc);
10459     bxe_init_sp_ring(sc);
10460     bxe_init_eq_ring(sc);
10461     bxe_init_internal(sc, load_code);
10462     bxe_pf_init(sc);
10463     bxe_stats_init(sc);
10464 
10465     /* flush all before enabling interrupts */
10466     mb();
10467 
10468     bxe_int_enable(sc);
10469 
10470     /* check for SPIO5 */
10471     bxe_attn_int_deasserted0(sc,
10472                              REG_RD(sc,
10473                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10474                                      SC_PORT(sc)*4)) &
10475                              AEU_INPUTS_ATTN_BITS_SPIO5);
10476 }
10477 
10478 static inline void
10479 bxe_init_objs(struct bxe_softc *sc)
10480 {
10481     /* mcast rules must be added to tx if tx switching is enabled */
10482     ecore_obj_type o_type =
10483         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10484                                          ECORE_OBJ_TYPE_RX;
10485 
10486     /* RX_MODE controlling object */
10487     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10488 
10489     /* multicast configuration controlling object */
10490     ecore_init_mcast_obj(sc,
10491                          &sc->mcast_obj,
10492                          sc->fp[0].cl_id,
10493                          sc->fp[0].index,
10494                          SC_FUNC(sc),
10495                          SC_FUNC(sc),
10496                          BXE_SP(sc, mcast_rdata),
10497                          BXE_SP_MAPPING(sc, mcast_rdata),
10498                          ECORE_FILTER_MCAST_PENDING,
10499                          &sc->sp_state,
10500                          o_type);
10501 
10502     /* Setup CAM credit pools */
10503     ecore_init_mac_credit_pool(sc,
10504                                &sc->macs_pool,
10505                                SC_FUNC(sc),
10506                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10507                                                  VNICS_PER_PATH(sc));
10508 
10509     ecore_init_vlan_credit_pool(sc,
10510                                 &sc->vlans_pool,
10511                                 SC_ABS_FUNC(sc) >> 1,
10512                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10513                                                   VNICS_PER_PATH(sc));
10514 
10515     /* RSS configuration object */
10516     ecore_init_rss_config_obj(sc,
10517                               &sc->rss_conf_obj,
10518                               sc->fp[0].cl_id,
10519                               sc->fp[0].index,
10520                               SC_FUNC(sc),
10521                               SC_FUNC(sc),
10522                               BXE_SP(sc, rss_rdata),
10523                               BXE_SP_MAPPING(sc, rss_rdata),
10524                               ECORE_FILTER_RSS_CONF_PENDING,
10525                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10526 }
10527 
10528 /*
10529  * Initialize the function. This must be called before sending CLIENT_SETUP
10530  * for the first client.
10531  */
10532 static inline int
10533 bxe_func_start(struct bxe_softc *sc)
10534 {
10535     struct ecore_func_state_params func_params = { NULL };
10536     struct ecore_func_start_params *start_params = &func_params.params.start;
10537 
10538     /* Prepare parameters for function state transitions */
10539     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10540 
10541     func_params.f_obj = &sc->func_obj;
10542     func_params.cmd = ECORE_F_CMD_START;
10543 
10544     /* Function parameters */
10545     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10546     start_params->sd_vlan_tag = OVLAN(sc);
10547 
10548     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10549         start_params->network_cos_mode = STATIC_COS;
10550     } else { /* CHIP_IS_E1X */
10551         start_params->network_cos_mode = FW_WRR;
10552     }
10553 
10554     //start_params->gre_tunnel_mode = 0;
10555     //start_params->gre_tunnel_rss  = 0;
10556 
10557     return (ecore_func_state_change(sc, &func_params));
10558 }
10559 
10560 static int
10561 bxe_set_power_state(struct bxe_softc *sc,
10562                     uint8_t          state)
10563 {
10564     uint16_t pmcsr;
10565 
10566     /* If there is no power capability, silently succeed */
10567     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10568         BLOGW(sc, "No power capability\n");
10569         return (0);
10570     }
10571 
10572     pmcsr = pci_read_config(sc->dev,
10573                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10574                             2);
10575 
10576     switch (state) {
10577     case PCI_PM_D0:
10578         pci_write_config(sc->dev,
10579                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10580                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10581 
10582         if (pmcsr & PCIM_PSTAT_DMASK) {
10583             /* delay required during transition out of D3hot */
10584             DELAY(20000);
10585         }
10586 
10587         break;
10588 
10589     case PCI_PM_D3hot:
10590         /* XXX if there are other clients above don't shut down the power */
10591 
10592         /* don't shut down the power for emulation and FPGA */
10593         if (CHIP_REV_IS_SLOW(sc)) {
10594             return (0);
10595         }
10596 
10597         pmcsr &= ~PCIM_PSTAT_DMASK;
10598         pmcsr |= PCIM_PSTAT_D3;
10599 
10600         if (sc->wol) {
10601             pmcsr |= PCIM_PSTAT_PMEENABLE;
10602         }
10603 
10604         pci_write_config(sc->dev,
10605                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10606                          pmcsr, 4);
10607 
10608         /*
10609          * No more memory access after this point until device is brought back
10610          * to D0 state.
10611          */
10612         break;
10613 
10614     default:
10615         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10616             state, pmcsr);
10617         return (-1);
10618     }
10619 
10620     return (0);
10621 }
10622 
10623 
10624 /* return true if succeeded to acquire the lock */
10625 static uint8_t
10626 bxe_trylock_hw_lock(struct bxe_softc *sc,
10627                     uint32_t         resource)
10628 {
10629     uint32_t lock_status;
10630     uint32_t resource_bit = (1 << resource);
10631     int func = SC_FUNC(sc);
10632     uint32_t hw_lock_control_reg;
10633 
10634     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10635 
10636     /* Validating that the resource is within range */
10637     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10638         BLOGD(sc, DBG_LOAD,
10639               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10640               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10641         return (FALSE);
10642     }
10643 
10644     if (func <= 5) {
10645         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10646     } else {
10647         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10648     }
10649 
10650     /* try to acquire the lock */
10651     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10652     lock_status = REG_RD(sc, hw_lock_control_reg);
10653     if (lock_status & resource_bit) {
10654         return (TRUE);
10655     }
10656 
10657     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10658         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10659         lock_status, resource_bit);
10660 
10661     return (FALSE);
10662 }
10663 
10664 /*
10665  * Get the recovery leader resource id according to the engine this function
10666  * belongs to. Currently only only 2 engines is supported.
10667  */
10668 static int
10669 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10670 {
10671     if (SC_PATH(sc)) {
10672         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10673     } else {
10674         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10675     }
10676 }
10677 
10678 /* try to acquire a leader lock for current engine */
10679 static uint8_t
10680 bxe_trylock_leader_lock(struct bxe_softc *sc)
10681 {
10682     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10683 }
10684 
10685 static int
10686 bxe_release_leader_lock(struct bxe_softc *sc)
10687 {
10688     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10689 }
10690 
10691 /* close gates #2, #3 and #4 */
10692 static void
10693 bxe_set_234_gates(struct bxe_softc *sc,
10694                   uint8_t          close)
10695 {
10696     uint32_t val;
10697 
10698     /* gates #2 and #4a are closed/opened for "not E1" only */
10699     if (!CHIP_IS_E1(sc)) {
10700         /* #4 */
10701         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10702         /* #2 */
10703         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10704     }
10705 
10706     /* #3 */
10707     if (CHIP_IS_E1x(sc)) {
10708         /* prevent interrupts from HC on both ports */
10709         val = REG_RD(sc, HC_REG_CONFIG_1);
10710         REG_WR(sc, HC_REG_CONFIG_1,
10711                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10712                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10713 
10714         val = REG_RD(sc, HC_REG_CONFIG_0);
10715         REG_WR(sc, HC_REG_CONFIG_0,
10716                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10717                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10718     } else {
10719         /* Prevent incoming interrupts in IGU */
10720         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10721 
10722         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10723                (!close) ?
10724                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10725                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10726     }
10727 
10728     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10729           close ? "closing" : "opening");
10730 
10731     wmb();
10732 }
10733 
10734 /* poll for pending writes bit, it should get cleared in no more than 1s */
10735 static int
10736 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10737 {
10738     uint32_t cnt = 1000;
10739     uint32_t pend_bits = 0;
10740 
10741     do {
10742         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10743 
10744         if (pend_bits == 0) {
10745             break;
10746         }
10747 
10748         DELAY(1000);
10749     } while (--cnt > 0);
10750 
10751     if (cnt == 0) {
10752         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10753         return (-1);
10754     }
10755 
10756     return (0);
10757 }
10758 
10759 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10760 
10761 static void
10762 bxe_clp_reset_prep(struct bxe_softc *sc,
10763                    uint32_t         *magic_val)
10764 {
10765     /* Do some magic... */
10766     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10767     *magic_val = val & SHARED_MF_CLP_MAGIC;
10768     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10769 }
10770 
10771 /* restore the value of the 'magic' bit */
10772 static void
10773 bxe_clp_reset_done(struct bxe_softc *sc,
10774                    uint32_t         magic_val)
10775 {
10776     /* Restore the 'magic' bit value... */
10777     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10778     MFCFG_WR(sc, shared_mf_config.clp_mb,
10779               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10780 }
10781 
10782 /* prepare for MCP reset, takes care of CLP configurations */
10783 static void
10784 bxe_reset_mcp_prep(struct bxe_softc *sc,
10785                    uint32_t         *magic_val)
10786 {
10787     uint32_t shmem;
10788     uint32_t validity_offset;
10789 
10790     /* set `magic' bit in order to save MF config */
10791     if (!CHIP_IS_E1(sc)) {
10792         bxe_clp_reset_prep(sc, magic_val);
10793     }
10794 
10795     /* get shmem offset */
10796     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10797     validity_offset =
10798         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10799 
10800     /* Clear validity map flags */
10801     if (shmem > 0) {
10802         REG_WR(sc, shmem + validity_offset, 0);
10803     }
10804 }
10805 
10806 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10807 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10808 
10809 static void
10810 bxe_mcp_wait_one(struct bxe_softc *sc)
10811 {
10812     /* special handling for emulation and FPGA (10 times longer) */
10813     if (CHIP_REV_IS_SLOW(sc)) {
10814         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10815     } else {
10816         DELAY((MCP_ONE_TIMEOUT) * 1000);
10817     }
10818 }
10819 
10820 /* initialize shmem_base and waits for validity signature to appear */
10821 static int
10822 bxe_init_shmem(struct bxe_softc *sc)
10823 {
10824     int cnt = 0;
10825     uint32_t val = 0;
10826 
10827     do {
10828         sc->devinfo.shmem_base     =
10829         sc->link_params.shmem_base =
10830             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10831 
10832         if (sc->devinfo.shmem_base) {
10833             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10834             if (val & SHR_MEM_VALIDITY_MB)
10835                 return (0);
10836         }
10837 
10838         bxe_mcp_wait_one(sc);
10839 
10840     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10841 
10842     BLOGE(sc, "BAD MCP validity signature\n");
10843 
10844     return (-1);
10845 }
10846 
10847 static int
10848 bxe_reset_mcp_comp(struct bxe_softc *sc,
10849                    uint32_t         magic_val)
10850 {
10851     int rc = bxe_init_shmem(sc);
10852 
10853     /* Restore the `magic' bit value */
10854     if (!CHIP_IS_E1(sc)) {
10855         bxe_clp_reset_done(sc, magic_val);
10856     }
10857 
10858     return (rc);
10859 }
10860 
10861 static void
10862 bxe_pxp_prep(struct bxe_softc *sc)
10863 {
10864     if (!CHIP_IS_E1(sc)) {
10865         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10866         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10867         wmb();
10868     }
10869 }
10870 
10871 /*
10872  * Reset the whole chip except for:
10873  *      - PCIE core
10874  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10875  *      - IGU
10876  *      - MISC (including AEU)
10877  *      - GRC
10878  *      - RBCN, RBCP
10879  */
10880 static void
10881 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10882                             uint8_t          global)
10883 {
10884     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10885     uint32_t global_bits2, stay_reset2;
10886 
10887     /*
10888      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10889      * (per chip) blocks.
10890      */
10891     global_bits2 =
10892         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10893         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10894 
10895     /*
10896      * Don't reset the following blocks.
10897      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10898      *            reset, as in 4 port device they might still be owned
10899      *            by the MCP (there is only one leader per path).
10900      */
10901     not_reset_mask1 =
10902         MISC_REGISTERS_RESET_REG_1_RST_HC |
10903         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10904         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10905 
10906     not_reset_mask2 =
10907         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10908         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10909         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10910         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10911         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10912         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10913         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10914         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10915         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10916         MISC_REGISTERS_RESET_REG_2_PGLC |
10917         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10918         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10919         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10920         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10921         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10922         MISC_REGISTERS_RESET_REG_2_UMAC1;
10923 
10924     /*
10925      * Keep the following blocks in reset:
10926      *  - all xxMACs are handled by the elink code.
10927      */
10928     stay_reset2 =
10929         MISC_REGISTERS_RESET_REG_2_XMAC |
10930         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10931 
10932     /* Full reset masks according to the chip */
10933     reset_mask1 = 0xffffffff;
10934 
10935     if (CHIP_IS_E1(sc))
10936         reset_mask2 = 0xffff;
10937     else if (CHIP_IS_E1H(sc))
10938         reset_mask2 = 0x1ffff;
10939     else if (CHIP_IS_E2(sc))
10940         reset_mask2 = 0xfffff;
10941     else /* CHIP_IS_E3 */
10942         reset_mask2 = 0x3ffffff;
10943 
10944     /* Don't reset global blocks unless we need to */
10945     if (!global)
10946         reset_mask2 &= ~global_bits2;
10947 
10948     /*
10949      * In case of attention in the QM, we need to reset PXP
10950      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10951      * because otherwise QM reset would release 'close the gates' shortly
10952      * before resetting the PXP, then the PSWRQ would send a write
10953      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10954      * read the payload data from PSWWR, but PSWWR would not
10955      * respond. The write queue in PGLUE would stuck, dmae commands
10956      * would not return. Therefore it's important to reset the second
10957      * reset register (containing the
10958      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10959      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10960      * bit).
10961      */
10962     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10963            reset_mask2 & (~not_reset_mask2));
10964 
10965     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10966            reset_mask1 & (~not_reset_mask1));
10967 
10968     mb();
10969     wmb();
10970 
10971     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10972            reset_mask2 & (~stay_reset2));
10973 
10974     mb();
10975     wmb();
10976 
10977     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10978     wmb();
10979 }
10980 
10981 static int
10982 bxe_process_kill(struct bxe_softc *sc,
10983                  uint8_t          global)
10984 {
10985     int cnt = 1000;
10986     uint32_t val = 0;
10987     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10988     uint32_t tags_63_32 = 0;
10989 
10990     /* Empty the Tetris buffer, wait for 1s */
10991     do {
10992         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10993         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10994         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10995         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10996         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10997         if (CHIP_IS_E3(sc)) {
10998             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10999         }
11000 
11001         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11002             ((port_is_idle_0 & 0x1) == 0x1) &&
11003             ((port_is_idle_1 & 0x1) == 0x1) &&
11004             (pgl_exp_rom2 == 0xffffffff) &&
11005             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11006             break;
11007         DELAY(1000);
11008     } while (cnt-- > 0);
11009 
11010     if (cnt <= 0) {
11011         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11012                   "are still outstanding read requests after 1s! "
11013                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11014                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11015               sr_cnt, blk_cnt, port_is_idle_0,
11016               port_is_idle_1, pgl_exp_rom2);
11017         return (-1);
11018     }
11019 
11020     mb();
11021 
11022     /* Close gates #2, #3 and #4 */
11023     bxe_set_234_gates(sc, TRUE);
11024 
11025     /* Poll for IGU VQs for 57712 and newer chips */
11026     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11027         return (-1);
11028     }
11029 
11030     /* XXX indicate that "process kill" is in progress to MCP */
11031 
11032     /* clear "unprepared" bit */
11033     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11034     mb();
11035 
11036     /* Make sure all is written to the chip before the reset */
11037     wmb();
11038 
11039     /*
11040      * Wait for 1ms to empty GLUE and PCI-E core queues,
11041      * PSWHST, GRC and PSWRD Tetris buffer.
11042      */
11043     DELAY(1000);
11044 
11045     /* Prepare to chip reset: */
11046     /* MCP */
11047     if (global) {
11048         bxe_reset_mcp_prep(sc, &val);
11049     }
11050 
11051     /* PXP */
11052     bxe_pxp_prep(sc);
11053     mb();
11054 
11055     /* reset the chip */
11056     bxe_process_kill_chip_reset(sc, global);
11057     mb();
11058 
11059     /* clear errors in PGB */
11060     if (!CHIP_IS_E1(sc))
11061         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11062 
11063     /* Recover after reset: */
11064     /* MCP */
11065     if (global && bxe_reset_mcp_comp(sc, val)) {
11066         return (-1);
11067     }
11068 
11069     /* XXX add resetting the NO_MCP mode DB here */
11070 
11071     /* Open the gates #2, #3 and #4 */
11072     bxe_set_234_gates(sc, FALSE);
11073 
11074     /* XXX
11075      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11076      * re-enable attentions
11077      */
11078 
11079     return (0);
11080 }
11081 
11082 static int
11083 bxe_leader_reset(struct bxe_softc *sc)
11084 {
11085     int rc = 0;
11086     uint8_t global = bxe_reset_is_global(sc);
11087     uint32_t load_code;
11088 
11089     /*
11090      * If not going to reset MCP, load "fake" driver to reset HW while
11091      * driver is owner of the HW.
11092      */
11093     if (!global && !BXE_NOMCP(sc)) {
11094         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11095                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11096         if (!load_code) {
11097             BLOGE(sc, "MCP response failure, aborting\n");
11098             rc = -1;
11099             goto exit_leader_reset;
11100         }
11101 
11102         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11103             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11104             BLOGE(sc, "MCP unexpected response, aborting\n");
11105             rc = -1;
11106             goto exit_leader_reset2;
11107         }
11108 
11109         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11110         if (!load_code) {
11111             BLOGE(sc, "MCP response failure, aborting\n");
11112             rc = -1;
11113             goto exit_leader_reset2;
11114         }
11115     }
11116 
11117     /* try to recover after the failure */
11118     if (bxe_process_kill(sc, global)) {
11119         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11120         rc = -1;
11121         goto exit_leader_reset2;
11122     }
11123 
11124     /*
11125      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11126      * state.
11127      */
11128     bxe_set_reset_done(sc);
11129     if (global) {
11130         bxe_clear_reset_global(sc);
11131     }
11132 
11133 exit_leader_reset2:
11134 
11135     /* unload "fake driver" if it was loaded */
11136     if (!global && !BXE_NOMCP(sc)) {
11137         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11138         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11139     }
11140 
11141 exit_leader_reset:
11142 
11143     sc->is_leader = 0;
11144     bxe_release_leader_lock(sc);
11145 
11146     mb();
11147     return (rc);
11148 }
11149 
11150 /*
11151  * prepare INIT transition, parameters configured:
11152  *   - HC configuration
11153  *   - Queue's CDU context
11154  */
11155 static void
11156 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11157                    struct bxe_fastpath            *fp,
11158                    struct ecore_queue_init_params *init_params)
11159 {
11160     uint8_t cos;
11161     int cxt_index, cxt_offset;
11162 
11163     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11164     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11165 
11166     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11167     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11168 
11169     /* HC rate */
11170     init_params->rx.hc_rate =
11171         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11172     init_params->tx.hc_rate =
11173         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11174 
11175     /* FW SB ID */
11176     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11177 
11178     /* CQ index among the SB indices */
11179     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11180     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11181 
11182     /* set maximum number of COSs supported by this queue */
11183     init_params->max_cos = sc->max_cos;
11184 
11185     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11186           fp->index, init_params->max_cos);
11187 
11188     /* set the context pointers queue object */
11189     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11190         /* XXX change index/cid here if ever support multiple tx CoS */
11191         /* fp->txdata[cos]->cid */
11192         cxt_index = fp->index / ILT_PAGE_CIDS;
11193         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11194         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11195     }
11196 }
11197 
11198 /* set flags that are common for the Tx-only and not normal connections */
11199 static unsigned long
11200 bxe_get_common_flags(struct bxe_softc    *sc,
11201                      struct bxe_fastpath *fp,
11202                      uint8_t             zero_stats)
11203 {
11204     unsigned long flags = 0;
11205 
11206     /* PF driver will always initialize the Queue to an ACTIVE state */
11207     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11208 
11209     /*
11210      * tx only connections collect statistics (on the same index as the
11211      * parent connection). The statistics are zeroed when the parent
11212      * connection is initialized.
11213      */
11214 
11215     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11216     if (zero_stats) {
11217         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11218     }
11219 
11220     /*
11221      * tx only connections can support tx-switching, though their
11222      * CoS-ness doesn't survive the loopback
11223      */
11224     if (sc->flags & BXE_TX_SWITCHING) {
11225         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11226     }
11227 
11228     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11229 
11230     return (flags);
11231 }
11232 
11233 static unsigned long
11234 bxe_get_q_flags(struct bxe_softc    *sc,
11235                 struct bxe_fastpath *fp,
11236                 uint8_t             leading)
11237 {
11238     unsigned long flags = 0;
11239 
11240     if (IS_MF_SD(sc)) {
11241         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11242     }
11243 
11244     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11245         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11246 #if __FreeBSD_version >= 800000
11247         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11248 #endif
11249     }
11250 
11251     if (leading) {
11252         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11253         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11254     }
11255 
11256     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11257 
11258     /* merge with common flags */
11259     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11260 }
11261 
11262 static void
11263 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11264                       struct bxe_fastpath               *fp,
11265                       struct ecore_general_setup_params *gen_init,
11266                       uint8_t                           cos)
11267 {
11268     gen_init->stat_id = bxe_stats_id(fp);
11269     gen_init->spcl_id = fp->cl_id;
11270     gen_init->mtu = sc->mtu;
11271     gen_init->cos = cos;
11272 }
11273 
11274 static void
11275 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11276                  struct bxe_fastpath           *fp,
11277                  struct rxq_pause_params       *pause,
11278                  struct ecore_rxq_setup_params *rxq_init)
11279 {
11280     uint8_t max_sge = 0;
11281     uint16_t sge_sz = 0;
11282     uint16_t tpa_agg_size = 0;
11283 
11284     pause->sge_th_lo = SGE_TH_LO(sc);
11285     pause->sge_th_hi = SGE_TH_HI(sc);
11286 
11287     /* validate SGE ring has enough to cross high threshold */
11288     if (sc->dropless_fc &&
11289             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11290             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11291         BLOGW(sc, "sge ring threshold limit\n");
11292     }
11293 
11294     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11295     tpa_agg_size = (2 * sc->mtu);
11296     if (tpa_agg_size < sc->max_aggregation_size) {
11297         tpa_agg_size = sc->max_aggregation_size;
11298     }
11299 
11300     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11301     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11302                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11303     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11304 
11305     /* pause - not for e1 */
11306     if (!CHIP_IS_E1(sc)) {
11307         pause->bd_th_lo = BD_TH_LO(sc);
11308         pause->bd_th_hi = BD_TH_HI(sc);
11309 
11310         pause->rcq_th_lo = RCQ_TH_LO(sc);
11311         pause->rcq_th_hi = RCQ_TH_HI(sc);
11312 
11313         /* validate rings have enough entries to cross high thresholds */
11314         if (sc->dropless_fc &&
11315             pause->bd_th_hi + FW_PREFETCH_CNT >
11316             sc->rx_ring_size) {
11317             BLOGW(sc, "rx bd ring threshold limit\n");
11318         }
11319 
11320         if (sc->dropless_fc &&
11321             pause->rcq_th_hi + FW_PREFETCH_CNT >
11322             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11323             BLOGW(sc, "rcq ring threshold limit\n");
11324         }
11325 
11326         pause->pri_map = 1;
11327     }
11328 
11329     /* rxq setup */
11330     rxq_init->dscr_map   = fp->rx_dma.paddr;
11331     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11332     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11333     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11334 
11335     /*
11336      * This should be a maximum number of data bytes that may be
11337      * placed on the BD (not including paddings).
11338      */
11339     rxq_init->buf_sz = (fp->rx_buf_size -
11340                         IP_HEADER_ALIGNMENT_PADDING);
11341 
11342     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11343     rxq_init->tpa_agg_sz      = tpa_agg_size;
11344     rxq_init->sge_buf_sz      = sge_sz;
11345     rxq_init->max_sges_pkt    = max_sge;
11346     rxq_init->rss_engine_id   = SC_FUNC(sc);
11347     rxq_init->mcast_engine_id = SC_FUNC(sc);
11348 
11349     /*
11350      * Maximum number or simultaneous TPA aggregation for this Queue.
11351      * For PF Clients it should be the maximum available number.
11352      * VF driver(s) may want to define it to a smaller value.
11353      */
11354     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11355 
11356     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11357     rxq_init->fw_sb_id = fp->fw_sb_id;
11358 
11359     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11360 
11361     /*
11362      * configure silent vlan removal
11363      * if multi function mode is afex, then mask default vlan
11364      */
11365     if (IS_MF_AFEX(sc)) {
11366         rxq_init->silent_removal_value =
11367             sc->devinfo.mf_info.afex_def_vlan_tag;
11368         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11369     }
11370 }
11371 
11372 static void
11373 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11374                  struct bxe_fastpath           *fp,
11375                  struct ecore_txq_setup_params *txq_init,
11376                  uint8_t                       cos)
11377 {
11378     /*
11379      * XXX If multiple CoS is ever supported then each fastpath structure
11380      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11381      * fp->txdata[cos]->tx_dma.paddr;
11382      */
11383     txq_init->dscr_map     = fp->tx_dma.paddr;
11384     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11385     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11386     txq_init->fw_sb_id     = fp->fw_sb_id;
11387 
11388     /*
11389      * set the TSS leading client id for TX classfication to the
11390      * leading RSS client id
11391      */
11392     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11393 }
11394 
11395 /*
11396  * This function performs 2 steps in a queue state machine:
11397  *   1) RESET->INIT
11398  *   2) INIT->SETUP
11399  */
11400 static int
11401 bxe_setup_queue(struct bxe_softc    *sc,
11402                 struct bxe_fastpath *fp,
11403                 uint8_t             leading)
11404 {
11405     struct ecore_queue_state_params q_params = { NULL };
11406     struct ecore_queue_setup_params *setup_params =
11407                         &q_params.params.setup;
11408     int rc;
11409 
11410     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11411 
11412     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11413 
11414     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11415 
11416     /* we want to wait for completion in this context */
11417     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11418 
11419     /* prepare the INIT parameters */
11420     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11421 
11422     /* Set the command */
11423     q_params.cmd = ECORE_Q_CMD_INIT;
11424 
11425     /* Change the state to INIT */
11426     rc = ecore_queue_state_change(sc, &q_params);
11427     if (rc) {
11428         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11429         return (rc);
11430     }
11431 
11432     BLOGD(sc, DBG_LOAD, "init complete\n");
11433 
11434     /* now move the Queue to the SETUP state */
11435     memset(setup_params, 0, sizeof(*setup_params));
11436 
11437     /* set Queue flags */
11438     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11439 
11440     /* set general SETUP parameters */
11441     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11442                           FIRST_TX_COS_INDEX);
11443 
11444     bxe_pf_rx_q_prep(sc, fp,
11445                      &setup_params->pause_params,
11446                      &setup_params->rxq_params);
11447 
11448     bxe_pf_tx_q_prep(sc, fp,
11449                      &setup_params->txq_params,
11450                      FIRST_TX_COS_INDEX);
11451 
11452     /* Set the command */
11453     q_params.cmd = ECORE_Q_CMD_SETUP;
11454 
11455     /* change the state to SETUP */
11456     rc = ecore_queue_state_change(sc, &q_params);
11457     if (rc) {
11458         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11459         return (rc);
11460     }
11461 
11462     return (rc);
11463 }
11464 
11465 static int
11466 bxe_setup_leading(struct bxe_softc *sc)
11467 {
11468     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11469 }
11470 
11471 static int
11472 bxe_config_rss_pf(struct bxe_softc            *sc,
11473                   struct ecore_rss_config_obj *rss_obj,
11474                   uint8_t                     config_hash)
11475 {
11476     struct ecore_config_rss_params params = { NULL };
11477     int i;
11478 
11479     /*
11480      * Although RSS is meaningless when there is a single HW queue we
11481      * still need it enabled in order to have HW Rx hash generated.
11482      */
11483 
11484     params.rss_obj = rss_obj;
11485 
11486     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11487 
11488     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11489 
11490     /* RSS configuration */
11491     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11492     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11493     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11494     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11495     if (rss_obj->udp_rss_v4) {
11496         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11497     }
11498     if (rss_obj->udp_rss_v6) {
11499         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11500     }
11501 
11502     /* Hash bits */
11503     params.rss_result_mask = MULTI_MASK;
11504 
11505     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11506 
11507     if (config_hash) {
11508         /* RSS keys */
11509         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11510             params.rss_key[i] = arc4random();
11511         }
11512 
11513         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11514     }
11515 
11516     return (ecore_config_rss(sc, &params));
11517 }
11518 
11519 static int
11520 bxe_config_rss_eth(struct bxe_softc *sc,
11521                    uint8_t          config_hash)
11522 {
11523     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11524 }
11525 
11526 static int
11527 bxe_init_rss_pf(struct bxe_softc *sc)
11528 {
11529     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11530     int i;
11531 
11532     /*
11533      * Prepare the initial contents of the indirection table if
11534      * RSS is enabled
11535      */
11536     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11537         sc->rss_conf_obj.ind_table[i] =
11538             (sc->fp->cl_id + (i % num_eth_queues));
11539     }
11540 
11541     if (sc->udp_rss) {
11542         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11543     }
11544 
11545     /*
11546      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11547      * per-port, so if explicit configuration is needed, do it only
11548      * for a PMF.
11549      *
11550      * For 57712 and newer it's a per-function configuration.
11551      */
11552     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11553 }
11554 
11555 static int
11556 bxe_set_mac_one(struct bxe_softc          *sc,
11557                 uint8_t                   *mac,
11558                 struct ecore_vlan_mac_obj *obj,
11559                 uint8_t                   set,
11560                 int                       mac_type,
11561                 unsigned long             *ramrod_flags)
11562 {
11563     struct ecore_vlan_mac_ramrod_params ramrod_param;
11564     int rc;
11565 
11566     memset(&ramrod_param, 0, sizeof(ramrod_param));
11567 
11568     /* fill in general parameters */
11569     ramrod_param.vlan_mac_obj = obj;
11570     ramrod_param.ramrod_flags = *ramrod_flags;
11571 
11572     /* fill a user request section if needed */
11573     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11574         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11575 
11576         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11577 
11578         /* Set the command: ADD or DEL */
11579         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11580                                             ECORE_VLAN_MAC_DEL;
11581     }
11582 
11583     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11584 
11585     if (rc == ECORE_EXISTS) {
11586         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11587         /* do not treat adding same MAC as error */
11588         rc = 0;
11589     } else if (rc < 0) {
11590         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11591     }
11592 
11593     return (rc);
11594 }
11595 
11596 static int
11597 bxe_set_eth_mac(struct bxe_softc *sc,
11598                 uint8_t          set)
11599 {
11600     unsigned long ramrod_flags = 0;
11601 
11602     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11603 
11604     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11605 
11606     /* Eth MAC is set on RSS leading client (fp[0]) */
11607     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11608                             &sc->sp_objs->mac_obj,
11609                             set, ECORE_ETH_MAC, &ramrod_flags));
11610 }
11611 
11612 static int
11613 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11614 {
11615     uint32_t sel_phy_idx = 0;
11616 
11617     if (sc->link_params.num_phys <= 1) {
11618         return (ELINK_INT_PHY);
11619     }
11620 
11621     if (sc->link_vars.link_up) {
11622         sel_phy_idx = ELINK_EXT_PHY1;
11623         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11624         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11625             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11626              ELINK_SUPPORTED_FIBRE))
11627             sel_phy_idx = ELINK_EXT_PHY2;
11628     } else {
11629         switch (elink_phy_selection(&sc->link_params)) {
11630         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11631         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11632         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11633                sel_phy_idx = ELINK_EXT_PHY1;
11634                break;
11635         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11636         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11637                sel_phy_idx = ELINK_EXT_PHY2;
11638                break;
11639         }
11640     }
11641 
11642     return (sel_phy_idx);
11643 }
11644 
11645 static int
11646 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11647 {
11648     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11649 
11650     /*
11651      * The selected activated PHY is always after swapping (in case PHY
11652      * swapping is enabled). So when swapping is enabled, we need to reverse
11653      * the configuration
11654      */
11655 
11656     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11657         if (sel_phy_idx == ELINK_EXT_PHY1)
11658             sel_phy_idx = ELINK_EXT_PHY2;
11659         else if (sel_phy_idx == ELINK_EXT_PHY2)
11660             sel_phy_idx = ELINK_EXT_PHY1;
11661     }
11662 
11663     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11664 }
11665 
11666 static void
11667 bxe_set_requested_fc(struct bxe_softc *sc)
11668 {
11669     /*
11670      * Initialize link parameters structure variables
11671      * It is recommended to turn off RX FC for jumbo frames
11672      * for better performance
11673      */
11674     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11675         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11676     } else {
11677         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11678     }
11679 }
11680 
11681 static void
11682 bxe_calc_fc_adv(struct bxe_softc *sc)
11683 {
11684     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11685 
11686 
11687     sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11688                                            ADVERTISED_Pause);
11689 
11690     switch (sc->link_vars.ieee_fc &
11691             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11692 
11693     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11694         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11695                                           ADVERTISED_Pause);
11696         break;
11697 
11698     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11699         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11700         break;
11701 
11702     default:
11703         break;
11704 
11705     }
11706 }
11707 
11708 static uint16_t
11709 bxe_get_mf_speed(struct bxe_softc *sc)
11710 {
11711     uint16_t line_speed = sc->link_vars.line_speed;
11712     if (IS_MF(sc)) {
11713         uint16_t maxCfg =
11714             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11715 
11716         /* calculate the current MAX line speed limit for the MF devices */
11717         if (IS_MF_SI(sc)) {
11718             line_speed = (line_speed * maxCfg) / 100;
11719         } else { /* SD mode */
11720             uint16_t vn_max_rate = maxCfg * 100;
11721 
11722             if (vn_max_rate < line_speed) {
11723                 line_speed = vn_max_rate;
11724             }
11725         }
11726     }
11727 
11728     return (line_speed);
11729 }
11730 
11731 static void
11732 bxe_fill_report_data(struct bxe_softc            *sc,
11733                      struct bxe_link_report_data *data)
11734 {
11735     uint16_t line_speed = bxe_get_mf_speed(sc);
11736 
11737     memset(data, 0, sizeof(*data));
11738 
11739     /* fill the report data with the effective line speed */
11740     data->line_speed = line_speed;
11741 
11742     /* Link is down */
11743     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11744         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11745     }
11746 
11747     /* Full DUPLEX */
11748     if (sc->link_vars.duplex == DUPLEX_FULL) {
11749         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11750     }
11751 
11752     /* Rx Flow Control is ON */
11753     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11754         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11755     }
11756 
11757     /* Tx Flow Control is ON */
11758     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11759         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11760     }
11761 }
11762 
11763 /* report link status to OS, should be called under phy_lock */
11764 static void
11765 bxe_link_report_locked(struct bxe_softc *sc)
11766 {
11767     struct bxe_link_report_data cur_data;
11768 
11769     /* reread mf_cfg */
11770     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11771         bxe_read_mf_cfg(sc);
11772     }
11773 
11774     /* Read the current link report info */
11775     bxe_fill_report_data(sc, &cur_data);
11776 
11777     /* Don't report link down or exactly the same link status twice */
11778     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11779         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11780                       &sc->last_reported_link.link_report_flags) &&
11781          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11782                       &cur_data.link_report_flags))) {
11783         return;
11784     }
11785 
11786 	ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11787 					cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11788     sc->link_cnt++;
11789 
11790 	ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11791     /* report new link params and remember the state for the next time */
11792     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11793 
11794     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11795                      &cur_data.link_report_flags)) {
11796         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11797     } else {
11798         const char *duplex;
11799         const char *flow;
11800 
11801         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11802                                    &cur_data.link_report_flags)) {
11803             duplex = "full";
11804 			ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11805         } else {
11806             duplex = "half";
11807 			ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11808         }
11809 
11810         /*
11811          * Handle the FC at the end so that only these flags would be
11812          * possibly set. This way we may easily check if there is no FC
11813          * enabled.
11814          */
11815         if (cur_data.link_report_flags) {
11816             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11817                              &cur_data.link_report_flags) &&
11818                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11819                              &cur_data.link_report_flags)) {
11820                 flow = "ON - receive & transmit";
11821             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11822                                     &cur_data.link_report_flags) &&
11823                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11824                                      &cur_data.link_report_flags)) {
11825                 flow = "ON - receive";
11826             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11827                                      &cur_data.link_report_flags) &&
11828                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11829                                     &cur_data.link_report_flags)) {
11830                 flow = "ON - transmit";
11831             } else {
11832                 flow = "none"; /* possible? */
11833             }
11834         } else {
11835             flow = "none";
11836         }
11837 
11838         if_link_state_change(sc->ifp, LINK_STATE_UP);
11839         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11840               cur_data.line_speed, duplex, flow);
11841     }
11842 }
11843 
11844 static void
11845 bxe_link_report(struct bxe_softc *sc)
11846 {
11847     bxe_acquire_phy_lock(sc);
11848     bxe_link_report_locked(sc);
11849     bxe_release_phy_lock(sc);
11850 }
11851 
11852 static void
11853 bxe_link_status_update(struct bxe_softc *sc)
11854 {
11855     if (sc->state != BXE_STATE_OPEN) {
11856         return;
11857     }
11858 
11859     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11860         elink_link_status_update(&sc->link_params, &sc->link_vars);
11861     } else {
11862         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11863                                   ELINK_SUPPORTED_10baseT_Full |
11864                                   ELINK_SUPPORTED_100baseT_Half |
11865                                   ELINK_SUPPORTED_100baseT_Full |
11866                                   ELINK_SUPPORTED_1000baseT_Full |
11867                                   ELINK_SUPPORTED_2500baseX_Full |
11868                                   ELINK_SUPPORTED_10000baseT_Full |
11869                                   ELINK_SUPPORTED_TP |
11870                                   ELINK_SUPPORTED_FIBRE |
11871                                   ELINK_SUPPORTED_Autoneg |
11872                                   ELINK_SUPPORTED_Pause |
11873                                   ELINK_SUPPORTED_Asym_Pause);
11874         sc->port.advertising[0] = sc->port.supported[0];
11875 
11876         sc->link_params.sc                = sc;
11877         sc->link_params.port              = SC_PORT(sc);
11878         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11879         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11880         sc->link_params.req_line_speed[0] = SPEED_10000;
11881         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11882         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11883 
11884         if (CHIP_REV_IS_FPGA(sc)) {
11885             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11886             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11887             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11888                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11889         } else {
11890             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11891             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11892             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11893                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11894         }
11895 
11896         sc->link_vars.link_up = 1;
11897 
11898         sc->link_vars.duplex    = DUPLEX_FULL;
11899         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11900 
11901         if (IS_PF(sc)) {
11902             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11903             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11904             bxe_link_report(sc);
11905         }
11906     }
11907 
11908     if (IS_PF(sc)) {
11909         if (sc->link_vars.link_up) {
11910             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11911         } else {
11912             bxe_stats_handle(sc, STATS_EVENT_STOP);
11913         }
11914         bxe_link_report(sc);
11915     } else {
11916         bxe_link_report(sc);
11917         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11918     }
11919 }
11920 
11921 static int
11922 bxe_initial_phy_init(struct bxe_softc *sc,
11923                      int              load_mode)
11924 {
11925     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11926     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11927     struct elink_params *lp = &sc->link_params;
11928 
11929     bxe_set_requested_fc(sc);
11930 
11931     if (CHIP_REV_IS_SLOW(sc)) {
11932         uint32_t bond = CHIP_BOND_ID(sc);
11933         uint32_t feat = 0;
11934 
11935         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11936             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11937         } else if (bond & 0x4) {
11938             if (CHIP_IS_E3(sc)) {
11939                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11940             } else {
11941                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11942             }
11943         } else if (bond & 0x8) {
11944             if (CHIP_IS_E3(sc)) {
11945                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11946             } else {
11947                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11948             }
11949         }
11950 
11951         /* disable EMAC for E3 and above */
11952         if (bond & 0x2) {
11953             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11954         }
11955 
11956         sc->link_params.feature_config_flags |= feat;
11957     }
11958 
11959     bxe_acquire_phy_lock(sc);
11960 
11961     if (load_mode == LOAD_DIAG) {
11962         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11963         /* Prefer doing PHY loopback at 10G speed, if possible */
11964         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11965             if (lp->speed_cap_mask[cfg_idx] &
11966                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11967                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11968             } else {
11969                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11970             }
11971         }
11972     }
11973 
11974     if (load_mode == LOAD_LOOPBACK_EXT) {
11975         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11976     }
11977 
11978     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11979 
11980     bxe_release_phy_lock(sc);
11981 
11982     bxe_calc_fc_adv(sc);
11983 
11984     if (sc->link_vars.link_up) {
11985         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11986         bxe_link_report(sc);
11987     }
11988 
11989     if (!CHIP_REV_IS_SLOW(sc)) {
11990         bxe_periodic_start(sc);
11991     }
11992 
11993     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11994     return (rc);
11995 }
11996 
11997 /* must be called under IF_ADDR_LOCK */
11998 static int
11999 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12000                          struct ecore_mcast_ramrod_params *p)
12001 {
12002     if_t ifp = sc->ifp;
12003     int mc_count = 0;
12004     struct ifmultiaddr *ifma;
12005     struct ecore_mcast_list_elem *mc_mac;
12006 
12007     CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12008         if (ifma->ifma_addr->sa_family != AF_LINK) {
12009             continue;
12010         }
12011 
12012         mc_count++;
12013     }
12014 
12015     ECORE_LIST_INIT(&p->mcast_list);
12016     p->mcast_list_len = 0;
12017 
12018     if (!mc_count) {
12019         return (0);
12020     }
12021 
12022     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12023                     (M_NOWAIT | M_ZERO));
12024     if (!mc_mac) {
12025         BLOGE(sc, "Failed to allocate temp mcast list\n");
12026         return (-1);
12027     }
12028     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12029 
12030     CK_STAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12031         if (ifma->ifma_addr->sa_family != AF_LINK) {
12032             continue;
12033         }
12034 
12035         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12036         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12037 
12038         BLOGD(sc, DBG_LOAD,
12039               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X and mc_count %d\n",
12040               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12041               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5], mc_count);
12042        mc_mac++;
12043     }
12044 
12045     p->mcast_list_len = mc_count;
12046 
12047     return (0);
12048 }
12049 
12050 static void
12051 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12052 {
12053     struct ecore_mcast_list_elem *mc_mac =
12054         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12055                                struct ecore_mcast_list_elem,
12056                                link);
12057 
12058     if (mc_mac) {
12059         /* only a single free as all mc_macs are in the same heap array */
12060         free(mc_mac, M_DEVBUF);
12061     }
12062 }
12063 static int
12064 bxe_set_mc_list(struct bxe_softc *sc)
12065 {
12066     struct ecore_mcast_ramrod_params rparam = { NULL };
12067     int rc = 0;
12068 
12069     rparam.mcast_obj = &sc->mcast_obj;
12070 
12071     BXE_MCAST_LOCK(sc);
12072 
12073     /* first, clear all configured multicast MACs */
12074     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12075     if (rc < 0) {
12076         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12077         /* Manual backport parts of FreeBSD upstream r284470. */
12078         BXE_MCAST_UNLOCK(sc);
12079         return (rc);
12080     }
12081 
12082     /* configure a new MACs list */
12083     rc = bxe_init_mcast_macs_list(sc, &rparam);
12084     if (rc) {
12085         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12086         BXE_MCAST_UNLOCK(sc);
12087         return (rc);
12088     }
12089 
12090     /* Now add the new MACs */
12091     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12092     if (rc < 0) {
12093         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12094     }
12095 
12096     bxe_free_mcast_macs_list(&rparam);
12097 
12098     BXE_MCAST_UNLOCK(sc);
12099 
12100     return (rc);
12101 }
12102 
12103 static int
12104 bxe_set_uc_list(struct bxe_softc *sc)
12105 {
12106     if_t ifp = sc->ifp;
12107     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12108     struct ifaddr *ifa;
12109     unsigned long ramrod_flags = 0;
12110     int rc;
12111 
12112 #if __FreeBSD_version < 800000
12113     IF_ADDR_LOCK(ifp);
12114 #else
12115     if_addr_rlock(ifp);
12116 #endif
12117 
12118     /* first schedule a cleanup up of old configuration */
12119     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12120     if (rc < 0) {
12121         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12122 #if __FreeBSD_version < 800000
12123         IF_ADDR_UNLOCK(ifp);
12124 #else
12125         if_addr_runlock(ifp);
12126 #endif
12127         return (rc);
12128     }
12129 
12130     ifa = if_getifaddr(ifp); /* XXX Is this structure */
12131     while (ifa) {
12132         if (ifa->ifa_addr->sa_family != AF_LINK) {
12133             ifa = CK_STAILQ_NEXT(ifa, ifa_link);
12134             continue;
12135         }
12136 
12137         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12138                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12139         if (rc == -EEXIST) {
12140             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12141             /* do not treat adding same MAC as an error */
12142             rc = 0;
12143         } else if (rc < 0) {
12144             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12145 #if __FreeBSD_version < 800000
12146             IF_ADDR_UNLOCK(ifp);
12147 #else
12148             if_addr_runlock(ifp);
12149 #endif
12150             return (rc);
12151         }
12152 
12153         ifa = CK_STAILQ_NEXT(ifa, ifa_link);
12154     }
12155 
12156 #if __FreeBSD_version < 800000
12157     IF_ADDR_UNLOCK(ifp);
12158 #else
12159     if_addr_runlock(ifp);
12160 #endif
12161 
12162     /* Execute the pending commands */
12163     bit_set(&ramrod_flags, RAMROD_CONT);
12164     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12165                             ECORE_UC_LIST_MAC, &ramrod_flags));
12166 }
12167 
12168 static void
12169 bxe_set_rx_mode(struct bxe_softc *sc)
12170 {
12171     if_t ifp = sc->ifp;
12172     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12173 
12174     if (sc->state != BXE_STATE_OPEN) {
12175         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12176         return;
12177     }
12178 
12179     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12180 
12181     if (if_getflags(ifp) & IFF_PROMISC) {
12182         rx_mode = BXE_RX_MODE_PROMISC;
12183     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12184                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12185                 CHIP_IS_E1(sc))) {
12186         rx_mode = BXE_RX_MODE_ALLMULTI;
12187     } else {
12188         if (IS_PF(sc)) {
12189             /* some multicasts */
12190             if (bxe_set_mc_list(sc) < 0) {
12191                 rx_mode = BXE_RX_MODE_ALLMULTI;
12192             }
12193             if (bxe_set_uc_list(sc) < 0) {
12194                 rx_mode = BXE_RX_MODE_PROMISC;
12195             }
12196         }
12197     }
12198 
12199     sc->rx_mode = rx_mode;
12200 
12201     /* schedule the rx_mode command */
12202     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12203         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12204         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12205         return;
12206     }
12207 
12208     if (IS_PF(sc)) {
12209         bxe_set_storm_rx_mode(sc);
12210     }
12211 }
12212 
12213 
12214 /* update flags in shmem */
12215 static void
12216 bxe_update_drv_flags(struct bxe_softc *sc,
12217                      uint32_t         flags,
12218                      uint32_t         set)
12219 {
12220     uint32_t drv_flags;
12221 
12222     if (SHMEM2_HAS(sc, drv_flags)) {
12223         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12224         drv_flags = SHMEM2_RD(sc, drv_flags);
12225 
12226         if (set) {
12227             SET_FLAGS(drv_flags, flags);
12228         } else {
12229             RESET_FLAGS(drv_flags, flags);
12230         }
12231 
12232         SHMEM2_WR(sc, drv_flags, drv_flags);
12233         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12234 
12235         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12236     }
12237 }
12238 
12239 /* periodic timer callout routine, only runs when the interface is up */
12240 
12241 static void
12242 bxe_periodic_callout_func(void *xsc)
12243 {
12244     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12245     int i;
12246 
12247     if (!BXE_CORE_TRYLOCK(sc)) {
12248         /* just bail and try again next time */
12249 
12250         if ((sc->state == BXE_STATE_OPEN) &&
12251             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12252             /* schedule the next periodic callout */
12253             callout_reset(&sc->periodic_callout, hz,
12254                           bxe_periodic_callout_func, sc);
12255         }
12256 
12257         return;
12258     }
12259 
12260     if ((sc->state != BXE_STATE_OPEN) ||
12261         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12262         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12263         BXE_CORE_UNLOCK(sc);
12264         return;
12265         }
12266 
12267 
12268     /* Check for TX timeouts on any fastpath. */
12269     FOR_EACH_QUEUE(sc, i) {
12270         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12271             /* Ruh-Roh, chip was reset! */
12272             break;
12273         }
12274     }
12275 
12276     if (!CHIP_REV_IS_SLOW(sc)) {
12277         /*
12278          * This barrier is needed to ensure the ordering between the writing
12279          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12280          * the reading here.
12281          */
12282         mb();
12283         if (sc->port.pmf) {
12284 	    bxe_acquire_phy_lock(sc);
12285             elink_period_func(&sc->link_params, &sc->link_vars);
12286 	    bxe_release_phy_lock(sc);
12287         }
12288     }
12289 
12290     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12291         int mb_idx = SC_FW_MB_IDX(sc);
12292         uint32_t drv_pulse;
12293         uint32_t mcp_pulse;
12294 
12295         ++sc->fw_drv_pulse_wr_seq;
12296         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12297 
12298         drv_pulse = sc->fw_drv_pulse_wr_seq;
12299         bxe_drv_pulse(sc);
12300 
12301         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12302                      MCP_PULSE_SEQ_MASK);
12303 
12304         /*
12305          * The delta between driver pulse and mcp response should
12306          * be 1 (before mcp response) or 0 (after mcp response).
12307          */
12308         if ((drv_pulse != mcp_pulse) &&
12309             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12310             /* someone lost a heartbeat... */
12311             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12312                   drv_pulse, mcp_pulse);
12313         }
12314     }
12315 
12316     /* state is BXE_STATE_OPEN */
12317     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12318 
12319     BXE_CORE_UNLOCK(sc);
12320 
12321     if ((sc->state == BXE_STATE_OPEN) &&
12322         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12323         /* schedule the next periodic callout */
12324         callout_reset(&sc->periodic_callout, hz,
12325                       bxe_periodic_callout_func, sc);
12326     }
12327 }
12328 
12329 static void
12330 bxe_periodic_start(struct bxe_softc *sc)
12331 {
12332     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12333     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12334 }
12335 
12336 static void
12337 bxe_periodic_stop(struct bxe_softc *sc)
12338 {
12339     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12340     callout_drain(&sc->periodic_callout);
12341 }
12342 
12343 /* start the controller */
12344 static __noinline int
12345 bxe_nic_load(struct bxe_softc *sc,
12346              int              load_mode)
12347 {
12348     uint32_t val;
12349     int load_code = 0;
12350     int i, rc = 0;
12351 
12352     BXE_CORE_LOCK_ASSERT(sc);
12353 
12354     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12355 
12356     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12357 
12358     if (IS_PF(sc)) {
12359         /* must be called before memory allocation and HW init */
12360         bxe_ilt_set_info(sc);
12361     }
12362 
12363     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12364 
12365     bxe_set_fp_rx_buf_size(sc);
12366 
12367     if (bxe_alloc_fp_buffers(sc) != 0) {
12368         BLOGE(sc, "Failed to allocate fastpath memory\n");
12369         sc->state = BXE_STATE_CLOSED;
12370         rc = ENOMEM;
12371         goto bxe_nic_load_error0;
12372     }
12373 
12374     if (bxe_alloc_mem(sc) != 0) {
12375         sc->state = BXE_STATE_CLOSED;
12376         rc = ENOMEM;
12377         goto bxe_nic_load_error0;
12378     }
12379 
12380     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12381         sc->state = BXE_STATE_CLOSED;
12382         rc = ENOMEM;
12383         goto bxe_nic_load_error0;
12384     }
12385 
12386     if (IS_PF(sc)) {
12387         /* set pf load just before approaching the MCP */
12388         bxe_set_pf_load(sc);
12389 
12390         /* if MCP exists send load request and analyze response */
12391         if (!BXE_NOMCP(sc)) {
12392             /* attempt to load pf */
12393             if (bxe_nic_load_request(sc, &load_code) != 0) {
12394                 sc->state = BXE_STATE_CLOSED;
12395                 rc = ENXIO;
12396                 goto bxe_nic_load_error1;
12397             }
12398 
12399             /* what did the MCP say? */
12400             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12401                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12402                 sc->state = BXE_STATE_CLOSED;
12403                 rc = ENXIO;
12404                 goto bxe_nic_load_error2;
12405             }
12406         } else {
12407             BLOGI(sc, "Device has no MCP!\n");
12408             load_code = bxe_nic_load_no_mcp(sc);
12409         }
12410 
12411         /* mark PMF if applicable */
12412         bxe_nic_load_pmf(sc, load_code);
12413 
12414         /* Init Function state controlling object */
12415         bxe_init_func_obj(sc);
12416 
12417         /* Initialize HW */
12418         if (bxe_init_hw(sc, load_code) != 0) {
12419             BLOGE(sc, "HW init failed\n");
12420             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12421             sc->state = BXE_STATE_CLOSED;
12422             rc = ENXIO;
12423             goto bxe_nic_load_error2;
12424         }
12425     }
12426 
12427     /* set ALWAYS_ALIVE bit in shmem */
12428     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12429     bxe_drv_pulse(sc);
12430     sc->flags |= BXE_NO_PULSE;
12431 
12432     /* attach interrupts */
12433     if (bxe_interrupt_attach(sc) != 0) {
12434         sc->state = BXE_STATE_CLOSED;
12435         rc = ENXIO;
12436         goto bxe_nic_load_error2;
12437     }
12438 
12439     bxe_nic_init(sc, load_code);
12440 
12441     /* Init per-function objects */
12442     if (IS_PF(sc)) {
12443         bxe_init_objs(sc);
12444         // XXX bxe_iov_nic_init(sc);
12445 
12446         /* set AFEX default VLAN tag to an invalid value */
12447         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12448         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12449 
12450         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12451         rc = bxe_func_start(sc);
12452         if (rc) {
12453             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12454             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12455             sc->state = BXE_STATE_ERROR;
12456             goto bxe_nic_load_error3;
12457         }
12458 
12459         /* send LOAD_DONE command to MCP */
12460         if (!BXE_NOMCP(sc)) {
12461             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12462             if (!load_code) {
12463                 BLOGE(sc, "MCP response failure, aborting\n");
12464                 sc->state = BXE_STATE_ERROR;
12465                 rc = ENXIO;
12466                 goto bxe_nic_load_error3;
12467             }
12468         }
12469 
12470         rc = bxe_setup_leading(sc);
12471         if (rc) {
12472             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12473             sc->state = BXE_STATE_ERROR;
12474             goto bxe_nic_load_error3;
12475         }
12476 
12477         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12478             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12479             if (rc) {
12480                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12481                 sc->state = BXE_STATE_ERROR;
12482                 goto bxe_nic_load_error3;
12483             }
12484         }
12485 
12486         rc = bxe_init_rss_pf(sc);
12487         if (rc) {
12488             BLOGE(sc, "PF RSS init failed\n");
12489             sc->state = BXE_STATE_ERROR;
12490             goto bxe_nic_load_error3;
12491         }
12492     }
12493     /* XXX VF */
12494 
12495     /* now when Clients are configured we are ready to work */
12496     sc->state = BXE_STATE_OPEN;
12497 
12498     /* Configure a ucast MAC */
12499     if (IS_PF(sc)) {
12500         rc = bxe_set_eth_mac(sc, TRUE);
12501     }
12502     if (rc) {
12503         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12504         sc->state = BXE_STATE_ERROR;
12505         goto bxe_nic_load_error3;
12506     }
12507 
12508     if (sc->port.pmf) {
12509         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12510         if (rc) {
12511             sc->state = BXE_STATE_ERROR;
12512             goto bxe_nic_load_error3;
12513         }
12514     }
12515 
12516     sc->link_params.feature_config_flags &=
12517         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12518 
12519     /* start fast path */
12520 
12521     /* Initialize Rx filter */
12522     bxe_set_rx_mode(sc);
12523 
12524     /* start the Tx */
12525     switch (/* XXX load_mode */LOAD_OPEN) {
12526     case LOAD_NORMAL:
12527     case LOAD_OPEN:
12528         break;
12529 
12530     case LOAD_DIAG:
12531     case LOAD_LOOPBACK_EXT:
12532         sc->state = BXE_STATE_DIAG;
12533         break;
12534 
12535     default:
12536         break;
12537     }
12538 
12539     if (sc->port.pmf) {
12540         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12541     } else {
12542         bxe_link_status_update(sc);
12543     }
12544 
12545     /* start the periodic timer callout */
12546     bxe_periodic_start(sc);
12547 
12548     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12549         /* mark driver is loaded in shmem2 */
12550         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12551         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12552                   (val |
12553                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12554                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12555     }
12556 
12557     /* wait for all pending SP commands to complete */
12558     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12559         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12560         bxe_periodic_stop(sc);
12561         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12562         return (ENXIO);
12563     }
12564 
12565     /* Tell the stack the driver is running! */
12566     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12567 
12568     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12569 
12570     return (0);
12571 
12572 bxe_nic_load_error3:
12573 
12574     if (IS_PF(sc)) {
12575         bxe_int_disable_sync(sc, 1);
12576 
12577         /* clean out queued objects */
12578         bxe_squeeze_objects(sc);
12579     }
12580 
12581     bxe_interrupt_detach(sc);
12582 
12583 bxe_nic_load_error2:
12584 
12585     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12586         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12587         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12588     }
12589 
12590     sc->port.pmf = 0;
12591 
12592 bxe_nic_load_error1:
12593 
12594     /* clear pf_load status, as it was already set */
12595     if (IS_PF(sc)) {
12596         bxe_clear_pf_load(sc);
12597     }
12598 
12599 bxe_nic_load_error0:
12600 
12601     bxe_free_fw_stats_mem(sc);
12602     bxe_free_fp_buffers(sc);
12603     bxe_free_mem(sc);
12604 
12605     return (rc);
12606 }
12607 
12608 static int
12609 bxe_init_locked(struct bxe_softc *sc)
12610 {
12611     int other_engine = SC_PATH(sc) ? 0 : 1;
12612     uint8_t other_load_status, load_status;
12613     uint8_t global = FALSE;
12614     int rc;
12615 
12616     BXE_CORE_LOCK_ASSERT(sc);
12617 
12618     /* check if the driver is already running */
12619     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12620         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12621         return (0);
12622     }
12623 
12624     bxe_set_power_state(sc, PCI_PM_D0);
12625 
12626     /*
12627      * If parity occurred during the unload, then attentions and/or
12628      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12629      * loaded on the current engine to complete the recovery. Parity recovery
12630      * is only relevant for PF driver.
12631      */
12632     if (IS_PF(sc)) {
12633         other_load_status = bxe_get_load_status(sc, other_engine);
12634         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12635 
12636         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12637             bxe_chk_parity_attn(sc, &global, TRUE)) {
12638             do {
12639                 /*
12640                  * If there are attentions and they are in global blocks, set
12641                  * the GLOBAL_RESET bit regardless whether it will be this
12642                  * function that will complete the recovery or not.
12643                  */
12644                 if (global) {
12645                     bxe_set_reset_global(sc);
12646                 }
12647 
12648                 /*
12649                  * Only the first function on the current engine should try
12650                  * to recover in open. In case of attentions in global blocks
12651                  * only the first in the chip should try to recover.
12652                  */
12653                 if ((!load_status && (!global || !other_load_status)) &&
12654                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12655                     BLOGI(sc, "Recovered during init\n");
12656                     break;
12657                 }
12658 
12659                 /* recovery has failed... */
12660                 bxe_set_power_state(sc, PCI_PM_D3hot);
12661                 sc->recovery_state = BXE_RECOVERY_FAILED;
12662 
12663                 BLOGE(sc, "Recovery flow hasn't properly "
12664                           "completed yet, try again later. "
12665                           "If you still see this message after a "
12666                           "few retries then power cycle is required.\n");
12667 
12668                 rc = ENXIO;
12669                 goto bxe_init_locked_done;
12670             } while (0);
12671         }
12672     }
12673 
12674     sc->recovery_state = BXE_RECOVERY_DONE;
12675 
12676     rc = bxe_nic_load(sc, LOAD_OPEN);
12677 
12678 bxe_init_locked_done:
12679 
12680     if (rc) {
12681         /* Tell the stack the driver is NOT running! */
12682         BLOGE(sc, "Initialization failed, "
12683                   "stack notified driver is NOT running!\n");
12684 	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
12685     }
12686 
12687     return (rc);
12688 }
12689 
12690 static int
12691 bxe_stop_locked(struct bxe_softc *sc)
12692 {
12693     BXE_CORE_LOCK_ASSERT(sc);
12694     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12695 }
12696 
12697 /*
12698  * Handles controller initialization when called from an unlocked routine.
12699  * ifconfig calls this function.
12700  *
12701  * Returns:
12702  *   void
12703  */
12704 static void
12705 bxe_init(void *xsc)
12706 {
12707     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12708 
12709     BXE_CORE_LOCK(sc);
12710     bxe_init_locked(sc);
12711     BXE_CORE_UNLOCK(sc);
12712 }
12713 
12714 static int
12715 bxe_init_ifnet(struct bxe_softc *sc)
12716 {
12717     if_t ifp;
12718     int capabilities;
12719 
12720     /* ifconfig entrypoint for media type/status reporting */
12721     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12722                  bxe_ifmedia_update,
12723                  bxe_ifmedia_status);
12724 
12725     /* set the default interface values */
12726     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12727     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12728     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12729 
12730     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12731 	BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
12732 
12733     /* allocate the ifnet structure */
12734     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
12735         BLOGE(sc, "Interface allocation failed!\n");
12736         return (ENXIO);
12737     }
12738 
12739     if_setsoftc(ifp, sc);
12740     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12741     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
12742     if_setioctlfn(ifp, bxe_ioctl);
12743     if_setstartfn(ifp, bxe_tx_start);
12744     if_setgetcounterfn(ifp, bxe_get_counter);
12745 #if __FreeBSD_version >= 901504
12746     if_settransmitfn(ifp, bxe_tx_mq_start);
12747     if_setqflushfn(ifp, bxe_mq_flush);
12748 #endif
12749 #ifdef FreeBSD8_0
12750     if_settimer(ifp, 0);
12751 #endif
12752     if_setinitfn(ifp, bxe_init);
12753     if_setmtu(ifp, sc->mtu);
12754     if_sethwassist(ifp, (CSUM_IP      |
12755                         CSUM_TCP      |
12756                         CSUM_UDP      |
12757                         CSUM_TSO      |
12758                         CSUM_TCP_IPV6 |
12759                         CSUM_UDP_IPV6));
12760 
12761     capabilities =
12762 #if __FreeBSD_version < 700000
12763         (IFCAP_VLAN_MTU       |
12764          IFCAP_VLAN_HWTAGGING |
12765          IFCAP_HWCSUM         |
12766          IFCAP_JUMBO_MTU      |
12767          IFCAP_LRO);
12768 #else
12769         (IFCAP_VLAN_MTU       |
12770          IFCAP_VLAN_HWTAGGING |
12771          IFCAP_VLAN_HWTSO     |
12772          IFCAP_VLAN_HWFILTER  |
12773          IFCAP_VLAN_HWCSUM    |
12774          IFCAP_HWCSUM         |
12775          IFCAP_JUMBO_MTU      |
12776          IFCAP_LRO            |
12777          IFCAP_TSO4           |
12778          IFCAP_TSO6           |
12779          IFCAP_WOL_MAGIC);
12780 #endif
12781     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
12782     if_setcapenable(ifp, if_getcapabilities(ifp));
12783     if_setbaudrate(ifp, IF_Gbps(10));
12784 /* XXX */
12785     if_setsendqlen(ifp, sc->tx_ring_size);
12786     if_setsendqready(ifp);
12787 /* XXX */
12788 
12789     sc->ifp = ifp;
12790 
12791     /* attach to the Ethernet interface list */
12792     ether_ifattach(ifp, sc->link_params.mac_addr);
12793 
12794     /* Attach driver netdump methods. */
12795     NETDUMP_SET(ifp, bxe);
12796 
12797     return (0);
12798 }
12799 
12800 static void
12801 bxe_deallocate_bars(struct bxe_softc *sc)
12802 {
12803     int i;
12804 
12805     for (i = 0; i < MAX_BARS; i++) {
12806         if (sc->bar[i].resource != NULL) {
12807             bus_release_resource(sc->dev,
12808                                  SYS_RES_MEMORY,
12809                                  sc->bar[i].rid,
12810                                  sc->bar[i].resource);
12811             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12812                   i, PCIR_BAR(i));
12813         }
12814     }
12815 }
12816 
12817 static int
12818 bxe_allocate_bars(struct bxe_softc *sc)
12819 {
12820     u_int flags;
12821     int i;
12822 
12823     memset(sc->bar, 0, sizeof(sc->bar));
12824 
12825     for (i = 0; i < MAX_BARS; i++) {
12826 
12827         /* memory resources reside at BARs 0, 2, 4 */
12828         /* Run `pciconf -lb` to see mappings */
12829         if ((i != 0) && (i != 2) && (i != 4)) {
12830             continue;
12831         }
12832 
12833         sc->bar[i].rid = PCIR_BAR(i);
12834 
12835         flags = RF_ACTIVE;
12836         if (i == 0) {
12837             flags |= RF_SHAREABLE;
12838         }
12839 
12840         if ((sc->bar[i].resource =
12841              bus_alloc_resource_any(sc->dev,
12842                                     SYS_RES_MEMORY,
12843                                     &sc->bar[i].rid,
12844                                     flags)) == NULL) {
12845             return (0);
12846         }
12847 
12848         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12849         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12850         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12851 
12852         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %#jx-%#jx (%jd) -> %#jx\n",
12853               i, PCIR_BAR(i),
12854               rman_get_start(sc->bar[i].resource),
12855               rman_get_end(sc->bar[i].resource),
12856               rman_get_size(sc->bar[i].resource),
12857               (uintmax_t)sc->bar[i].kva);
12858     }
12859 
12860     return (0);
12861 }
12862 
12863 static void
12864 bxe_get_function_num(struct bxe_softc *sc)
12865 {
12866     uint32_t val = 0;
12867 
12868     /*
12869      * Read the ME register to get the function number. The ME register
12870      * holds the relative-function number and absolute-function number. The
12871      * absolute-function number appears only in E2 and above. Before that
12872      * these bits always contained zero, therefore we cannot blindly use them.
12873      */
12874 
12875     val = REG_RD(sc, BAR_ME_REGISTER);
12876 
12877     sc->pfunc_rel =
12878         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12879     sc->path_id =
12880         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12881 
12882     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12883         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12884     } else {
12885         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12886     }
12887 
12888     BLOGD(sc, DBG_LOAD,
12889           "Relative function %d, Absolute function %d, Path %d\n",
12890           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12891 }
12892 
12893 static uint32_t
12894 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12895 {
12896     uint32_t shmem2_size;
12897     uint32_t offset;
12898     uint32_t mf_cfg_offset_value;
12899 
12900     /* Non 57712 */
12901     offset = (SHMEM_RD(sc, func_mb) +
12902               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12903 
12904     /* 57712 plus */
12905     if (sc->devinfo.shmem2_base != 0) {
12906         shmem2_size = SHMEM2_RD(sc, size);
12907         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12908             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12909             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12910                 offset = mf_cfg_offset_value;
12911             }
12912         }
12913     }
12914 
12915     return (offset);
12916 }
12917 
12918 static uint32_t
12919 bxe_pcie_capability_read(struct bxe_softc *sc,
12920                          int    reg,
12921                          int    width)
12922 {
12923     int pcie_reg;
12924 
12925     /* ensure PCIe capability is enabled */
12926     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12927         if (pcie_reg != 0) {
12928             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12929             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12930         }
12931     }
12932 
12933     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12934 
12935     return (0);
12936 }
12937 
12938 static uint8_t
12939 bxe_is_pcie_pending(struct bxe_softc *sc)
12940 {
12941     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12942             PCIM_EXP_STA_TRANSACTION_PND);
12943 }
12944 
12945 /*
12946  * Walk the PCI capabiites list for the device to find what features are
12947  * supported. These capabilites may be enabled/disabled by firmware so it's
12948  * best to walk the list rather than make assumptions.
12949  */
12950 static void
12951 bxe_probe_pci_caps(struct bxe_softc *sc)
12952 {
12953     uint16_t link_status;
12954     int reg;
12955 
12956     /* check if PCI Power Management is enabled */
12957     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12958         if (reg != 0) {
12959             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12960 
12961             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12962             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12963         }
12964     }
12965 
12966     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12967 
12968     /* handle PCIe 2.0 workarounds for 57710 */
12969     if (CHIP_IS_E1(sc)) {
12970         /* workaround for 57710 errata E4_57710_27462 */
12971         sc->devinfo.pcie_link_speed =
12972             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12973 
12974         /* workaround for 57710 errata E4_57710_27488 */
12975         sc->devinfo.pcie_link_width =
12976             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12977         if (sc->devinfo.pcie_link_speed > 1) {
12978             sc->devinfo.pcie_link_width =
12979                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12980         }
12981     } else {
12982         sc->devinfo.pcie_link_speed =
12983             (link_status & PCIM_LINK_STA_SPEED);
12984         sc->devinfo.pcie_link_width =
12985             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12986     }
12987 
12988     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12989           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12990 
12991     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12992     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12993 
12994     /* check if MSI capability is enabled */
12995     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12996         if (reg != 0) {
12997             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
12998 
12999             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13000             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13001         }
13002     }
13003 
13004     /* check if MSI-X capability is enabled */
13005     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13006         if (reg != 0) {
13007             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13008 
13009             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13010             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13011         }
13012     }
13013 }
13014 
13015 static int
13016 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13017 {
13018     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13019     uint32_t val;
13020 
13021     /* get the outer vlan if we're in switch-dependent mode */
13022 
13023     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13024     mf_info->ext_id = (uint16_t)val;
13025 
13026     mf_info->multi_vnics_mode = 1;
13027 
13028     if (!VALID_OVLAN(mf_info->ext_id)) {
13029         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13030         return (1);
13031     }
13032 
13033     /* get the capabilities */
13034     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13035         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13036         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13037     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13038                FUNC_MF_CFG_PROTOCOL_FCOE) {
13039         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13040     } else {
13041         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13042     }
13043 
13044     mf_info->vnics_per_port =
13045         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13046 
13047     return (0);
13048 }
13049 
13050 static uint32_t
13051 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13052 {
13053     uint32_t retval = 0;
13054     uint32_t val;
13055 
13056     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13057 
13058     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13059         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13060             retval |= MF_PROTO_SUPPORT_ETHERNET;
13061         }
13062         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13063             retval |= MF_PROTO_SUPPORT_ISCSI;
13064         }
13065         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13066             retval |= MF_PROTO_SUPPORT_FCOE;
13067         }
13068     }
13069 
13070     return (retval);
13071 }
13072 
13073 static int
13074 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13075 {
13076     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13077     uint32_t val;
13078 
13079     /*
13080      * There is no outer vlan if we're in switch-independent mode.
13081      * If the mac is valid then assume multi-function.
13082      */
13083 
13084     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13085 
13086     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13087 
13088     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13089 
13090     mf_info->vnics_per_port =
13091         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13092 
13093     return (0);
13094 }
13095 
13096 static int
13097 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13098 {
13099     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13100     uint32_t e1hov_tag;
13101     uint32_t func_config;
13102     uint32_t niv_config;
13103 
13104     mf_info->multi_vnics_mode = 1;
13105 
13106     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13107     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13108     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13109 
13110     mf_info->ext_id =
13111         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13112                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13113 
13114     mf_info->default_vlan =
13115         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13116                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13117 
13118     mf_info->niv_allowed_priorities =
13119         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13120                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13121 
13122     mf_info->niv_default_cos =
13123         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13124                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13125 
13126     mf_info->afex_vlan_mode =
13127         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13128          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13129 
13130     mf_info->niv_mba_enabled =
13131         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13132          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13133 
13134     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13135 
13136     mf_info->vnics_per_port =
13137         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13138 
13139     return (0);
13140 }
13141 
13142 static int
13143 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13144 {
13145     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13146     uint32_t mf_cfg1;
13147     uint32_t mf_cfg2;
13148     uint32_t ovlan1;
13149     uint32_t ovlan2;
13150     uint8_t i, j;
13151 
13152     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13153           SC_PORT(sc));
13154     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13155           mf_info->mf_config[SC_VN(sc)]);
13156     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13157           mf_info->multi_vnics_mode);
13158     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13159           mf_info->vnics_per_port);
13160     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13161           mf_info->ext_id);
13162     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13163           mf_info->min_bw[0], mf_info->min_bw[1],
13164           mf_info->min_bw[2], mf_info->min_bw[3]);
13165     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13166           mf_info->max_bw[0], mf_info->max_bw[1],
13167           mf_info->max_bw[2], mf_info->max_bw[3]);
13168     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13169           sc->mac_addr_str);
13170 
13171     /* various MF mode sanity checks... */
13172 
13173     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13174         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13175               SC_PORT(sc));
13176         return (1);
13177     }
13178 
13179     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13180         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13181               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13182         return (1);
13183     }
13184 
13185     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13186         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13187         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13188             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13189                   SC_VN(sc), OVLAN(sc));
13190             return (1);
13191         }
13192 
13193         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13194             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13195                   mf_info->multi_vnics_mode, OVLAN(sc));
13196             return (1);
13197         }
13198 
13199         /*
13200          * Verify all functions are either MF or SF mode. If MF, make sure
13201          * sure that all non-hidden functions have a valid ovlan. If SF,
13202          * make sure that all non-hidden functions have an invalid ovlan.
13203          */
13204         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13205             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13206             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13207             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13208                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13209                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13210                 BLOGE(sc, "mf_mode=SD function %d MF config "
13211                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13212                       i, mf_info->multi_vnics_mode, ovlan1);
13213                 return (1);
13214             }
13215         }
13216 
13217         /* Verify all funcs on the same port each have a different ovlan. */
13218         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13219             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13220             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13221             /* iterate from the next function on the port to the max func */
13222             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13223                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13224                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13225                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13226                     VALID_OVLAN(ovlan1) &&
13227                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13228                     VALID_OVLAN(ovlan2) &&
13229                     (ovlan1 == ovlan2)) {
13230                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13231                               "have the same ovlan (%d)\n",
13232                           i, j, ovlan1);
13233                     return (1);
13234                 }
13235             }
13236         }
13237     } /* MULTI_FUNCTION_SD */
13238 
13239     return (0);
13240 }
13241 
13242 static int
13243 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13244 {
13245     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13246     uint32_t val, mac_upper;
13247     uint8_t i, vnic;
13248 
13249     /* initialize mf_info defaults */
13250     mf_info->vnics_per_port   = 1;
13251     mf_info->multi_vnics_mode = FALSE;
13252     mf_info->path_has_ovlan   = FALSE;
13253     mf_info->mf_mode          = SINGLE_FUNCTION;
13254 
13255     if (!CHIP_IS_MF_CAP(sc)) {
13256         return (0);
13257     }
13258 
13259     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13260         BLOGE(sc, "Invalid mf_cfg_base!\n");
13261         return (1);
13262     }
13263 
13264     /* get the MF mode (switch dependent / independent / single-function) */
13265 
13266     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13267 
13268     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13269     {
13270     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13271 
13272         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13273 
13274         /* check for legal upper mac bytes */
13275         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13276             mf_info->mf_mode = MULTI_FUNCTION_SI;
13277         } else {
13278             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13279         }
13280 
13281         break;
13282 
13283     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13284     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13285 
13286         /* get outer vlan configuration */
13287         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13288 
13289         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13290             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13291             mf_info->mf_mode = MULTI_FUNCTION_SD;
13292         } else {
13293             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13294         }
13295 
13296         break;
13297 
13298     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13299 
13300         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13301         return (0);
13302 
13303     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13304 
13305         /*
13306          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13307          * and the MAC address is valid.
13308          */
13309         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13310 
13311         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13312             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13313             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13314         } else {
13315             BLOGE(sc, "Invalid config for AFEX mode\n");
13316         }
13317 
13318         break;
13319 
13320     default:
13321 
13322         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13323               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13324 
13325         return (1);
13326     }
13327 
13328     /* set path mf_mode (which could be different than function mf_mode) */
13329     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13330         mf_info->path_has_ovlan = TRUE;
13331     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13332         /*
13333          * Decide on path multi vnics mode. If we're not in MF mode and in
13334          * 4-port mode, this is good enough to check vnic-0 of the other port
13335          * on the same path
13336          */
13337         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13338             uint8_t other_port = !(PORT_ID(sc) & 1);
13339             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13340 
13341             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13342 
13343             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13344         }
13345     }
13346 
13347     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13348         /* invalid MF config */
13349         if (SC_VN(sc) >= 1) {
13350             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13351             return (1);
13352         }
13353 
13354         return (0);
13355     }
13356 
13357     /* get the MF configuration */
13358     mf_info->mf_config[SC_VN(sc)] =
13359         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13360 
13361     switch(mf_info->mf_mode)
13362     {
13363     case MULTI_FUNCTION_SD:
13364 
13365         bxe_get_shmem_mf_cfg_info_sd(sc);
13366         break;
13367 
13368     case MULTI_FUNCTION_SI:
13369 
13370         bxe_get_shmem_mf_cfg_info_si(sc);
13371         break;
13372 
13373     case MULTI_FUNCTION_AFEX:
13374 
13375         bxe_get_shmem_mf_cfg_info_niv(sc);
13376         break;
13377 
13378     default:
13379 
13380         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13381               mf_info->mf_mode);
13382         return (1);
13383     }
13384 
13385     /* get the congestion management parameters */
13386 
13387     vnic = 0;
13388     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13389         /* get min/max bw */
13390         val = MFCFG_RD(sc, func_mf_config[i].config);
13391         mf_info->min_bw[vnic] =
13392             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13393         mf_info->max_bw[vnic] =
13394             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13395         vnic++;
13396     }
13397 
13398     return (bxe_check_valid_mf_cfg(sc));
13399 }
13400 
13401 static int
13402 bxe_get_shmem_info(struct bxe_softc *sc)
13403 {
13404     int port;
13405     uint32_t mac_hi, mac_lo, val;
13406 
13407     port = SC_PORT(sc);
13408     mac_hi = mac_lo = 0;
13409 
13410     sc->link_params.sc   = sc;
13411     sc->link_params.port = port;
13412 
13413     /* get the hardware config info */
13414     sc->devinfo.hw_config =
13415         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13416     sc->devinfo.hw_config2 =
13417         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13418 
13419     sc->link_params.hw_led_mode =
13420         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13421          SHARED_HW_CFG_LED_MODE_SHIFT);
13422 
13423     /* get the port feature config */
13424     sc->port.config =
13425         SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13426 
13427     /* get the link params */
13428     sc->link_params.speed_cap_mask[0] =
13429         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13430     sc->link_params.speed_cap_mask[1] =
13431         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13432 
13433     /* get the lane config */
13434     sc->link_params.lane_config =
13435         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13436 
13437     /* get the link config */
13438     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13439     sc->port.link_config[ELINK_INT_PHY] = val;
13440     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13441     sc->port.link_config[ELINK_EXT_PHY1] =
13442         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13443 
13444     /* get the override preemphasis flag and enable it or turn it off */
13445     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13446     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13447         sc->link_params.feature_config_flags |=
13448             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13449     } else {
13450         sc->link_params.feature_config_flags &=
13451             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13452     }
13453 
13454     /* get the initial value of the link params */
13455     sc->link_params.multi_phy_config =
13456         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13457 
13458     /* get external phy info */
13459     sc->port.ext_phy_config =
13460         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13461 
13462     /* get the multifunction configuration */
13463     bxe_get_mf_cfg_info(sc);
13464 
13465     /* get the mac address */
13466     if (IS_MF(sc)) {
13467         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13468         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13469     } else {
13470         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13471         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13472     }
13473 
13474     if ((mac_lo == 0) && (mac_hi == 0)) {
13475         *sc->mac_addr_str = 0;
13476         BLOGE(sc, "No Ethernet address programmed!\n");
13477     } else {
13478         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13479         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13480         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13481         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13482         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13483         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13484         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13485                  "%02x:%02x:%02x:%02x:%02x:%02x",
13486                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13487                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13488                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13489         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13490     }
13491 
13492     return (0);
13493 }
13494 
13495 static void
13496 bxe_get_tunable_params(struct bxe_softc *sc)
13497 {
13498     /* sanity checks */
13499 
13500     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13501         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13502         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13503         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13504         bxe_interrupt_mode = INTR_MODE_MSIX;
13505     }
13506 
13507     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13508         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13509         bxe_queue_count = 0;
13510     }
13511 
13512     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13513         if (bxe_max_rx_bufs == 0) {
13514             bxe_max_rx_bufs = RX_BD_USABLE;
13515         } else {
13516             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13517             bxe_max_rx_bufs = 2048;
13518         }
13519     }
13520 
13521     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13522         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13523         bxe_hc_rx_ticks = 25;
13524     }
13525 
13526     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13527         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13528         bxe_hc_tx_ticks = 50;
13529     }
13530 
13531     if (bxe_max_aggregation_size == 0) {
13532         bxe_max_aggregation_size = TPA_AGG_SIZE;
13533     }
13534 
13535     if (bxe_max_aggregation_size > 0xffff) {
13536         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13537               bxe_max_aggregation_size);
13538         bxe_max_aggregation_size = TPA_AGG_SIZE;
13539     }
13540 
13541     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13542         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13543         bxe_mrrs = -1;
13544     }
13545 
13546     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13547         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13548         bxe_autogreeen = 0;
13549     }
13550 
13551     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13552         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13553         bxe_udp_rss = 0;
13554     }
13555 
13556     /* pull in user settings */
13557 
13558     sc->interrupt_mode       = bxe_interrupt_mode;
13559     sc->max_rx_bufs          = bxe_max_rx_bufs;
13560     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13561     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13562     sc->max_aggregation_size = bxe_max_aggregation_size;
13563     sc->mrrs                 = bxe_mrrs;
13564     sc->autogreeen           = bxe_autogreeen;
13565     sc->udp_rss              = bxe_udp_rss;
13566 
13567     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13568         sc->num_queues = 1;
13569     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13570         sc->num_queues =
13571             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13572                 MAX_RSS_CHAINS);
13573         if (sc->num_queues > mp_ncpus) {
13574             sc->num_queues = mp_ncpus;
13575         }
13576     }
13577 
13578     BLOGD(sc, DBG_LOAD,
13579           "User Config: "
13580           "debug=0x%lx "
13581           "interrupt_mode=%d "
13582           "queue_count=%d "
13583           "hc_rx_ticks=%d "
13584           "hc_tx_ticks=%d "
13585           "rx_budget=%d "
13586           "max_aggregation_size=%d "
13587           "mrrs=%d "
13588           "autogreeen=%d "
13589           "udp_rss=%d\n",
13590           bxe_debug,
13591           sc->interrupt_mode,
13592           sc->num_queues,
13593           sc->hc_rx_ticks,
13594           sc->hc_tx_ticks,
13595           bxe_rx_budget,
13596           sc->max_aggregation_size,
13597           sc->mrrs,
13598           sc->autogreeen,
13599           sc->udp_rss);
13600 }
13601 
13602 static int
13603 bxe_media_detect(struct bxe_softc *sc)
13604 {
13605     int port_type;
13606     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13607 
13608     switch (sc->link_params.phy[phy_idx].media_type) {
13609     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13610     case ELINK_ETH_PHY_XFP_FIBER:
13611         BLOGI(sc, "Found 10Gb Fiber media.\n");
13612         sc->media = IFM_10G_SR;
13613         port_type = PORT_FIBRE;
13614         break;
13615     case ELINK_ETH_PHY_SFP_1G_FIBER:
13616         BLOGI(sc, "Found 1Gb Fiber media.\n");
13617         sc->media = IFM_1000_SX;
13618         port_type = PORT_FIBRE;
13619         break;
13620     case ELINK_ETH_PHY_KR:
13621     case ELINK_ETH_PHY_CX4:
13622         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13623         sc->media = IFM_10G_CX4;
13624         port_type = PORT_FIBRE;
13625         break;
13626     case ELINK_ETH_PHY_DA_TWINAX:
13627         BLOGI(sc, "Found 10Gb Twinax media.\n");
13628         sc->media = IFM_10G_TWINAX;
13629         port_type = PORT_DA;
13630         break;
13631     case ELINK_ETH_PHY_BASE_T:
13632         if (sc->link_params.speed_cap_mask[0] &
13633             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13634             BLOGI(sc, "Found 10GBase-T media.\n");
13635             sc->media = IFM_10G_T;
13636             port_type = PORT_TP;
13637         } else {
13638             BLOGI(sc, "Found 1000Base-T media.\n");
13639             sc->media = IFM_1000_T;
13640             port_type = PORT_TP;
13641         }
13642         break;
13643     case ELINK_ETH_PHY_NOT_PRESENT:
13644         BLOGI(sc, "Media not present.\n");
13645         sc->media = 0;
13646         port_type = PORT_OTHER;
13647         break;
13648     case ELINK_ETH_PHY_UNSPECIFIED:
13649     default:
13650         BLOGI(sc, "Unknown media!\n");
13651         sc->media = 0;
13652         port_type = PORT_OTHER;
13653         break;
13654     }
13655     return port_type;
13656 }
13657 
13658 #define GET_FIELD(value, fname)                     \
13659     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13660 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13661 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13662 
13663 static int
13664 bxe_get_igu_cam_info(struct bxe_softc *sc)
13665 {
13666     int pfid = SC_FUNC(sc);
13667     int igu_sb_id;
13668     uint32_t val;
13669     uint8_t fid, igu_sb_cnt = 0;
13670 
13671     sc->igu_base_sb = 0xff;
13672 
13673     if (CHIP_INT_MODE_IS_BC(sc)) {
13674         int vn = SC_VN(sc);
13675         igu_sb_cnt = sc->igu_sb_cnt;
13676         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13677                            FP_SB_MAX_E1x);
13678         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13679                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13680         return (0);
13681     }
13682 
13683     /* IGU in normal mode - read CAM */
13684     for (igu_sb_id = 0;
13685          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13686          igu_sb_id++) {
13687         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13688         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13689             continue;
13690         }
13691         fid = IGU_FID(val);
13692         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13693             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13694                 continue;
13695             }
13696             if (IGU_VEC(val) == 0) {
13697                 /* default status block */
13698                 sc->igu_dsb_id = igu_sb_id;
13699             } else {
13700                 if (sc->igu_base_sb == 0xff) {
13701                     sc->igu_base_sb = igu_sb_id;
13702                 }
13703                 igu_sb_cnt++;
13704             }
13705         }
13706     }
13707 
13708     /*
13709      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13710      * that number of CAM entries will not be equal to the value advertised in
13711      * PCI. Driver should use the minimal value of both as the actual status
13712      * block count
13713      */
13714     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13715 
13716     if (igu_sb_cnt == 0) {
13717         BLOGE(sc, "CAM configuration error\n");
13718         return (-1);
13719     }
13720 
13721     return (0);
13722 }
13723 
13724 /*
13725  * Gather various information from the device config space, the device itself,
13726  * shmem, and the user input.
13727  */
13728 static int
13729 bxe_get_device_info(struct bxe_softc *sc)
13730 {
13731     uint32_t val;
13732     int rc;
13733 
13734     /* Get the data for the device */
13735     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13736     sc->devinfo.device_id    = pci_get_device(sc->dev);
13737     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13738     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13739 
13740     /* get the chip revision (chip metal comes from pci config space) */
13741     sc->devinfo.chip_id     =
13742     sc->link_params.chip_id =
13743         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13744          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13745          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13746          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13747 
13748     /* force 57811 according to MISC register */
13749     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13750         if (CHIP_IS_57810(sc)) {
13751             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13752                                    (sc->devinfo.chip_id & 0x0000ffff));
13753         } else if (CHIP_IS_57810_MF(sc)) {
13754             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13755                                    (sc->devinfo.chip_id & 0x0000ffff));
13756         }
13757         sc->devinfo.chip_id |= 0x1;
13758     }
13759 
13760     BLOGD(sc, DBG_LOAD,
13761           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13762           sc->devinfo.chip_id,
13763           ((sc->devinfo.chip_id >> 16) & 0xffff),
13764           ((sc->devinfo.chip_id >> 12) & 0xf),
13765           ((sc->devinfo.chip_id >>  4) & 0xff),
13766           ((sc->devinfo.chip_id >>  0) & 0xf));
13767 
13768     val = (REG_RD(sc, 0x2874) & 0x55);
13769     if ((sc->devinfo.chip_id & 0x1) ||
13770         (CHIP_IS_E1(sc) && val) ||
13771         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13772         sc->flags |= BXE_ONE_PORT_FLAG;
13773         BLOGD(sc, DBG_LOAD, "single port device\n");
13774     }
13775 
13776     /* set the doorbell size */
13777     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13778 
13779     /* determine whether the device is in 2 port or 4 port mode */
13780     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13781     if (CHIP_IS_E2E3(sc)) {
13782         /*
13783          * Read port4mode_en_ovwr[0]:
13784          *   If 1, four port mode is in port4mode_en_ovwr[1].
13785          *   If 0, four port mode is in port4mode_en[0].
13786          */
13787         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13788         if (val & 1) {
13789             val = ((val >> 1) & 1);
13790         } else {
13791             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13792         }
13793 
13794         sc->devinfo.chip_port_mode =
13795             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13796 
13797         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13798     }
13799 
13800     /* get the function and path info for the device */
13801     bxe_get_function_num(sc);
13802 
13803     /* get the shared memory base address */
13804     sc->devinfo.shmem_base     =
13805     sc->link_params.shmem_base =
13806         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13807     sc->devinfo.shmem2_base =
13808         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13809                                   MISC_REG_GENERIC_CR_0));
13810 
13811     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13812           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13813 
13814     if (!sc->devinfo.shmem_base) {
13815         /* this should ONLY prevent upcoming shmem reads */
13816         BLOGI(sc, "MCP not active\n");
13817         sc->flags |= BXE_NO_MCP_FLAG;
13818         return (0);
13819     }
13820 
13821     /* make sure the shared memory contents are valid */
13822     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13823     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13824         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13825         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13826         return (0);
13827     }
13828     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13829 
13830     /* get the bootcode version */
13831     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13832     snprintf(sc->devinfo.bc_ver_str,
13833              sizeof(sc->devinfo.bc_ver_str),
13834              "%d.%d.%d",
13835              ((sc->devinfo.bc_ver >> 24) & 0xff),
13836              ((sc->devinfo.bc_ver >> 16) & 0xff),
13837              ((sc->devinfo.bc_ver >>  8) & 0xff));
13838     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13839 
13840     /* get the bootcode shmem address */
13841     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13842     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13843 
13844     /* clean indirect addresses as they're not used */
13845     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13846     if (IS_PF(sc)) {
13847         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13848         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13849         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13850         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13851         if (CHIP_IS_E1x(sc)) {
13852             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13853             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13854             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13855             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13856         }
13857 
13858         /*
13859          * Enable internal target-read (in case we are probed after PF
13860          * FLR). Must be done prior to any BAR read access. Only for
13861          * 57712 and up
13862          */
13863         if (!CHIP_IS_E1x(sc)) {
13864             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13865         }
13866     }
13867 
13868     /* get the nvram size */
13869     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13870     sc->devinfo.flash_size =
13871         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13872     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13873 
13874     /* get PCI capabilites */
13875     bxe_probe_pci_caps(sc);
13876 
13877     bxe_set_power_state(sc, PCI_PM_D0);
13878 
13879     /* get various configuration parameters from shmem */
13880     bxe_get_shmem_info(sc);
13881 
13882     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13883         val = pci_read_config(sc->dev,
13884                               (sc->devinfo.pcie_msix_cap_reg +
13885                                PCIR_MSIX_CTRL),
13886                               2);
13887         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13888     } else {
13889         sc->igu_sb_cnt = 1;
13890     }
13891 
13892     sc->igu_base_addr = BAR_IGU_INTMEM;
13893 
13894     /* initialize IGU parameters */
13895     if (CHIP_IS_E1x(sc)) {
13896         sc->devinfo.int_block = INT_BLOCK_HC;
13897         sc->igu_dsb_id = DEF_SB_IGU_ID;
13898         sc->igu_base_sb = 0;
13899     } else {
13900         sc->devinfo.int_block = INT_BLOCK_IGU;
13901 
13902         /* do not allow device reset during IGU info preocessing */
13903         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13904 
13905         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13906 
13907         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13908             int tout = 5000;
13909 
13910             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13911 
13912             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13913             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13914             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13915 
13916             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13917                 tout--;
13918                 DELAY(1000);
13919             }
13920 
13921             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13922                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13923                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13924                 return (-1);
13925             }
13926         }
13927 
13928         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13929             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13930             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13931         } else {
13932             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13933         }
13934 
13935         rc = bxe_get_igu_cam_info(sc);
13936 
13937         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13938 
13939         if (rc) {
13940             return (rc);
13941         }
13942     }
13943 
13944     /*
13945      * Get base FW non-default (fast path) status block ID. This value is
13946      * used to initialize the fw_sb_id saved on the fp/queue structure to
13947      * determine the id used by the FW.
13948      */
13949     if (CHIP_IS_E1x(sc)) {
13950         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13951     } else {
13952         /*
13953          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13954          * the same queue are indicated on the same IGU SB). So we prefer
13955          * FW and IGU SBs to be the same value.
13956          */
13957         sc->base_fw_ndsb = sc->igu_base_sb;
13958     }
13959 
13960     BLOGD(sc, DBG_LOAD,
13961           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13962           sc->igu_dsb_id, sc->igu_base_sb,
13963           sc->igu_sb_cnt, sc->base_fw_ndsb);
13964 
13965     elink_phy_probe(&sc->link_params);
13966 
13967     return (0);
13968 }
13969 
13970 static void
13971 bxe_link_settings_supported(struct bxe_softc *sc,
13972                             uint32_t         switch_cfg)
13973 {
13974     uint32_t cfg_size = 0;
13975     uint32_t idx;
13976     uint8_t port = SC_PORT(sc);
13977 
13978     /* aggregation of supported attributes of all external phys */
13979     sc->port.supported[0] = 0;
13980     sc->port.supported[1] = 0;
13981 
13982     switch (sc->link_params.num_phys) {
13983     case 1:
13984         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13985         cfg_size = 1;
13986         break;
13987     case 2:
13988         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13989         cfg_size = 1;
13990         break;
13991     case 3:
13992         if (sc->link_params.multi_phy_config &
13993             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13994             sc->port.supported[1] =
13995                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13996             sc->port.supported[0] =
13997                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13998         } else {
13999             sc->port.supported[0] =
14000                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14001             sc->port.supported[1] =
14002                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14003         }
14004         cfg_size = 2;
14005         break;
14006     }
14007 
14008     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14009         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14010               SHMEM_RD(sc,
14011                        dev_info.port_hw_config[port].external_phy_config),
14012               SHMEM_RD(sc,
14013                        dev_info.port_hw_config[port].external_phy_config2));
14014         return;
14015     }
14016 
14017     if (CHIP_IS_E3(sc))
14018         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14019     else {
14020         switch (switch_cfg) {
14021         case ELINK_SWITCH_CFG_1G:
14022             sc->port.phy_addr =
14023                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14024             break;
14025         case ELINK_SWITCH_CFG_10G:
14026             sc->port.phy_addr =
14027                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14028             break;
14029         default:
14030             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14031                   sc->port.link_config[0]);
14032             return;
14033         }
14034     }
14035 
14036     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14037 
14038     /* mask what we support according to speed_cap_mask per configuration */
14039     for (idx = 0; idx < cfg_size; idx++) {
14040         if (!(sc->link_params.speed_cap_mask[idx] &
14041               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14042             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14043         }
14044 
14045         if (!(sc->link_params.speed_cap_mask[idx] &
14046               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14047             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14048         }
14049 
14050         if (!(sc->link_params.speed_cap_mask[idx] &
14051               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14052             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14053         }
14054 
14055         if (!(sc->link_params.speed_cap_mask[idx] &
14056               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14057             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14058         }
14059 
14060         if (!(sc->link_params.speed_cap_mask[idx] &
14061               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14062             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14063         }
14064 
14065         if (!(sc->link_params.speed_cap_mask[idx] &
14066               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14067             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14068         }
14069 
14070         if (!(sc->link_params.speed_cap_mask[idx] &
14071               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14072             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14073         }
14074 
14075         if (!(sc->link_params.speed_cap_mask[idx] &
14076               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14077             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14078         }
14079     }
14080 
14081     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14082           sc->port.supported[0], sc->port.supported[1]);
14083 	ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14084 					sc->port.supported[0], sc->port.supported[1]);
14085 }
14086 
14087 static void
14088 bxe_link_settings_requested(struct bxe_softc *sc)
14089 {
14090     uint32_t link_config;
14091     uint32_t idx;
14092     uint32_t cfg_size = 0;
14093 
14094     sc->port.advertising[0] = 0;
14095     sc->port.advertising[1] = 0;
14096 
14097     switch (sc->link_params.num_phys) {
14098     case 1:
14099     case 2:
14100         cfg_size = 1;
14101         break;
14102     case 3:
14103         cfg_size = 2;
14104         break;
14105     }
14106 
14107     for (idx = 0; idx < cfg_size; idx++) {
14108         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14109         link_config = sc->port.link_config[idx];
14110 
14111         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14112         case PORT_FEATURE_LINK_SPEED_AUTO:
14113             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14114                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14115                 sc->port.advertising[idx] |= sc->port.supported[idx];
14116                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14117                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14118                     sc->port.advertising[idx] |=
14119                         (ELINK_SUPPORTED_100baseT_Half |
14120                          ELINK_SUPPORTED_100baseT_Full);
14121             } else {
14122                 /* force 10G, no AN */
14123                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14124                 sc->port.advertising[idx] |=
14125                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14126                 continue;
14127             }
14128             break;
14129 
14130         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14131             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14132                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14133                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14134                                               ADVERTISED_TP);
14135             } else {
14136                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14137                           "speed_cap_mask=0x%08x\n",
14138                       link_config, sc->link_params.speed_cap_mask[idx]);
14139                 return;
14140             }
14141             break;
14142 
14143         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14144             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14145                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14146                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14147                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14148                                               ADVERTISED_TP);
14149 				ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14150 								sc->link_params.req_duplex[idx]);
14151             } else {
14152                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14153                           "speed_cap_mask=0x%08x\n",
14154                       link_config, sc->link_params.speed_cap_mask[idx]);
14155                 return;
14156             }
14157             break;
14158 
14159         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14160             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14161                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14162                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14163                                               ADVERTISED_TP);
14164             } else {
14165                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14166                           "speed_cap_mask=0x%08x\n",
14167                       link_config, sc->link_params.speed_cap_mask[idx]);
14168                 return;
14169             }
14170             break;
14171 
14172         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14173             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14174                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14175                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14176                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14177                                               ADVERTISED_TP);
14178             } else {
14179                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14180                           "speed_cap_mask=0x%08x\n",
14181                       link_config, sc->link_params.speed_cap_mask[idx]);
14182                 return;
14183             }
14184             break;
14185 
14186         case PORT_FEATURE_LINK_SPEED_1G:
14187             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14188                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14189                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14190                                               ADVERTISED_TP);
14191             } else {
14192                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14193                           "speed_cap_mask=0x%08x\n",
14194                       link_config, sc->link_params.speed_cap_mask[idx]);
14195                 return;
14196             }
14197             break;
14198 
14199         case PORT_FEATURE_LINK_SPEED_2_5G:
14200             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14201                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14202                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14203                                               ADVERTISED_TP);
14204             } else {
14205                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14206                           "speed_cap_mask=0x%08x\n",
14207                       link_config, sc->link_params.speed_cap_mask[idx]);
14208                 return;
14209             }
14210             break;
14211 
14212         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14213             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14214                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14215                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14216                                               ADVERTISED_FIBRE);
14217             } else {
14218                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14219                           "speed_cap_mask=0x%08x\n",
14220                       link_config, sc->link_params.speed_cap_mask[idx]);
14221                 return;
14222             }
14223             break;
14224 
14225         case PORT_FEATURE_LINK_SPEED_20G:
14226             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14227             break;
14228 
14229         default:
14230             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14231                       "speed_cap_mask=0x%08x\n",
14232                   link_config, sc->link_params.speed_cap_mask[idx]);
14233             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14234             sc->port.advertising[idx] = sc->port.supported[idx];
14235             break;
14236         }
14237 
14238         sc->link_params.req_flow_ctrl[idx] =
14239             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14240 
14241         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14242             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14243                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14244             } else {
14245                 bxe_set_requested_fc(sc);
14246             }
14247         }
14248 
14249         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14250                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14251               sc->link_params.req_line_speed[idx],
14252               sc->link_params.req_duplex[idx],
14253               sc->link_params.req_flow_ctrl[idx],
14254               sc->port.advertising[idx]);
14255 		ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14256 						"advertising=0x%x\n",
14257 						sc->link_params.req_line_speed[idx],
14258 						sc->link_params.req_duplex[idx],
14259 						sc->port.advertising[idx]);
14260     }
14261 }
14262 
14263 static void
14264 bxe_get_phy_info(struct bxe_softc *sc)
14265 {
14266     uint8_t port = SC_PORT(sc);
14267     uint32_t config = sc->port.config;
14268     uint32_t eee_mode;
14269 
14270     /* shmem data already read in bxe_get_shmem_info() */
14271 
14272     ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14273                         "link_config0=0x%08x\n",
14274                sc->link_params.lane_config,
14275                sc->link_params.speed_cap_mask[0],
14276                sc->port.link_config[0]);
14277 
14278 
14279     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14280     bxe_link_settings_requested(sc);
14281 
14282     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14283         sc->link_params.feature_config_flags |=
14284             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14285     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14286         sc->link_params.feature_config_flags &=
14287             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14288     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14289         sc->link_params.feature_config_flags |=
14290             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14291     }
14292 
14293     /* configure link feature according to nvram value */
14294     eee_mode =
14295         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14296           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14297          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14298     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14299         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14300                                     ELINK_EEE_MODE_ENABLE_LPI |
14301                                     ELINK_EEE_MODE_OUTPUT_TIME);
14302     } else {
14303         sc->link_params.eee_mode = 0;
14304     }
14305 
14306     /* get the media type */
14307     bxe_media_detect(sc);
14308 	ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14309 }
14310 
14311 static void
14312 bxe_get_params(struct bxe_softc *sc)
14313 {
14314     /* get user tunable params */
14315     bxe_get_tunable_params(sc);
14316 
14317     /* select the RX and TX ring sizes */
14318     sc->tx_ring_size = TX_BD_USABLE;
14319     sc->rx_ring_size = RX_BD_USABLE;
14320 
14321     /* XXX disable WoL */
14322     sc->wol = 0;
14323 }
14324 
14325 static void
14326 bxe_set_modes_bitmap(struct bxe_softc *sc)
14327 {
14328     uint32_t flags = 0;
14329 
14330     if (CHIP_REV_IS_FPGA(sc)) {
14331         SET_FLAGS(flags, MODE_FPGA);
14332     } else if (CHIP_REV_IS_EMUL(sc)) {
14333         SET_FLAGS(flags, MODE_EMUL);
14334     } else {
14335         SET_FLAGS(flags, MODE_ASIC);
14336     }
14337 
14338     if (CHIP_IS_MODE_4_PORT(sc)) {
14339         SET_FLAGS(flags, MODE_PORT4);
14340     } else {
14341         SET_FLAGS(flags, MODE_PORT2);
14342     }
14343 
14344     if (CHIP_IS_E2(sc)) {
14345         SET_FLAGS(flags, MODE_E2);
14346     } else if (CHIP_IS_E3(sc)) {
14347         SET_FLAGS(flags, MODE_E3);
14348         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14349             SET_FLAGS(flags, MODE_E3_A0);
14350         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14351             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14352         }
14353     }
14354 
14355     if (IS_MF(sc)) {
14356         SET_FLAGS(flags, MODE_MF);
14357         switch (sc->devinfo.mf_info.mf_mode) {
14358         case MULTI_FUNCTION_SD:
14359             SET_FLAGS(flags, MODE_MF_SD);
14360             break;
14361         case MULTI_FUNCTION_SI:
14362             SET_FLAGS(flags, MODE_MF_SI);
14363             break;
14364         case MULTI_FUNCTION_AFEX:
14365             SET_FLAGS(flags, MODE_MF_AFEX);
14366             break;
14367         }
14368     } else {
14369         SET_FLAGS(flags, MODE_SF);
14370     }
14371 
14372 #if defined(__LITTLE_ENDIAN)
14373     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14374 #else /* __BIG_ENDIAN */
14375     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14376 #endif
14377 
14378     INIT_MODE_FLAGS(sc) = flags;
14379 }
14380 
14381 static int
14382 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14383 {
14384     struct bxe_fastpath *fp;
14385     bus_addr_t busaddr;
14386     int max_agg_queues;
14387     int max_segments;
14388     bus_size_t max_size;
14389     bus_size_t max_seg_size;
14390     char buf[32];
14391     int rc;
14392     int i, j;
14393 
14394     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14395 
14396     /* allocate the parent bus DMA tag */
14397     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14398                             1,                        /* alignment */
14399                             0,                        /* boundary limit */
14400                             BUS_SPACE_MAXADDR,        /* restricted low */
14401                             BUS_SPACE_MAXADDR,        /* restricted hi */
14402                             NULL,                     /* addr filter() */
14403                             NULL,                     /* addr filter() arg */
14404                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14405                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14406                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14407                             0,                        /* flags */
14408                             NULL,                     /* lock() */
14409                             NULL,                     /* lock() arg */
14410                             &sc->parent_dma_tag);     /* returned dma tag */
14411     if (rc != 0) {
14412         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14413         return (1);
14414     }
14415 
14416     /************************/
14417     /* DEFAULT STATUS BLOCK */
14418     /************************/
14419 
14420     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14421                       &sc->def_sb_dma, "default status block") != 0) {
14422         /* XXX */
14423         bus_dma_tag_destroy(sc->parent_dma_tag);
14424         return (1);
14425     }
14426 
14427     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14428 
14429     /***************/
14430     /* EVENT QUEUE */
14431     /***************/
14432 
14433     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14434                       &sc->eq_dma, "event queue") != 0) {
14435         /* XXX */
14436         bxe_dma_free(sc, &sc->def_sb_dma);
14437         sc->def_sb = NULL;
14438         bus_dma_tag_destroy(sc->parent_dma_tag);
14439         return (1);
14440     }
14441 
14442     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14443 
14444     /*************/
14445     /* SLOW PATH */
14446     /*************/
14447 
14448     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14449                       &sc->sp_dma, "slow path") != 0) {
14450         /* XXX */
14451         bxe_dma_free(sc, &sc->eq_dma);
14452         sc->eq = NULL;
14453         bxe_dma_free(sc, &sc->def_sb_dma);
14454         sc->def_sb = NULL;
14455         bus_dma_tag_destroy(sc->parent_dma_tag);
14456         return (1);
14457     }
14458 
14459     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14460 
14461     /*******************/
14462     /* SLOW PATH QUEUE */
14463     /*******************/
14464 
14465     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14466                       &sc->spq_dma, "slow path queue") != 0) {
14467         /* XXX */
14468         bxe_dma_free(sc, &sc->sp_dma);
14469         sc->sp = NULL;
14470         bxe_dma_free(sc, &sc->eq_dma);
14471         sc->eq = NULL;
14472         bxe_dma_free(sc, &sc->def_sb_dma);
14473         sc->def_sb = NULL;
14474         bus_dma_tag_destroy(sc->parent_dma_tag);
14475         return (1);
14476     }
14477 
14478     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14479 
14480     /***************************/
14481     /* FW DECOMPRESSION BUFFER */
14482     /***************************/
14483 
14484     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14485                       "fw decompression buffer") != 0) {
14486         /* XXX */
14487         bxe_dma_free(sc, &sc->spq_dma);
14488         sc->spq = NULL;
14489         bxe_dma_free(sc, &sc->sp_dma);
14490         sc->sp = NULL;
14491         bxe_dma_free(sc, &sc->eq_dma);
14492         sc->eq = NULL;
14493         bxe_dma_free(sc, &sc->def_sb_dma);
14494         sc->def_sb = NULL;
14495         bus_dma_tag_destroy(sc->parent_dma_tag);
14496         return (1);
14497     }
14498 
14499     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14500 
14501     if ((sc->gz_strm =
14502          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14503         /* XXX */
14504         bxe_dma_free(sc, &sc->gz_buf_dma);
14505         sc->gz_buf = NULL;
14506         bxe_dma_free(sc, &sc->spq_dma);
14507         sc->spq = NULL;
14508         bxe_dma_free(sc, &sc->sp_dma);
14509         sc->sp = NULL;
14510         bxe_dma_free(sc, &sc->eq_dma);
14511         sc->eq = NULL;
14512         bxe_dma_free(sc, &sc->def_sb_dma);
14513         sc->def_sb = NULL;
14514         bus_dma_tag_destroy(sc->parent_dma_tag);
14515         return (1);
14516     }
14517 
14518     /*************/
14519     /* FASTPATHS */
14520     /*************/
14521 
14522     /* allocate DMA memory for each fastpath structure */
14523     for (i = 0; i < sc->num_queues; i++) {
14524         fp = &sc->fp[i];
14525         fp->sc    = sc;
14526         fp->index = i;
14527 
14528         /*******************/
14529         /* FP STATUS BLOCK */
14530         /*******************/
14531 
14532         snprintf(buf, sizeof(buf), "fp %d status block", i);
14533         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14534                           &fp->sb_dma, buf) != 0) {
14535             /* XXX unwind and free previous fastpath allocations */
14536             BLOGE(sc, "Failed to alloc %s\n", buf);
14537             return (1);
14538         } else {
14539             if (CHIP_IS_E2E3(sc)) {
14540                 fp->status_block.e2_sb =
14541                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14542             } else {
14543                 fp->status_block.e1x_sb =
14544                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14545             }
14546         }
14547 
14548         /******************/
14549         /* FP TX BD CHAIN */
14550         /******************/
14551 
14552         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14553         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14554                           &fp->tx_dma, buf) != 0) {
14555             /* XXX unwind and free previous fastpath allocations */
14556             BLOGE(sc, "Failed to alloc %s\n", buf);
14557             return (1);
14558         } else {
14559             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14560         }
14561 
14562         /* link together the tx bd chain pages */
14563         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14564             /* index into the tx bd chain array to last entry per page */
14565             struct eth_tx_next_bd *tx_next_bd =
14566                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14567             /* point to the next page and wrap from last page */
14568             busaddr = (fp->tx_dma.paddr +
14569                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14570             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14571             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14572         }
14573 
14574         /******************/
14575         /* FP RX BD CHAIN */
14576         /******************/
14577 
14578         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14579         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14580                           &fp->rx_dma, buf) != 0) {
14581             /* XXX unwind and free previous fastpath allocations */
14582             BLOGE(sc, "Failed to alloc %s\n", buf);
14583             return (1);
14584         } else {
14585             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14586         }
14587 
14588         /* link together the rx bd chain pages */
14589         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14590             /* index into the rx bd chain array to last entry per page */
14591             struct eth_rx_bd *rx_bd =
14592                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14593             /* point to the next page and wrap from last page */
14594             busaddr = (fp->rx_dma.paddr +
14595                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14596             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14597             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14598         }
14599 
14600         /*******************/
14601         /* FP RX RCQ CHAIN */
14602         /*******************/
14603 
14604         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14605         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14606                           &fp->rcq_dma, buf) != 0) {
14607             /* XXX unwind and free previous fastpath allocations */
14608             BLOGE(sc, "Failed to alloc %s\n", buf);
14609             return (1);
14610         } else {
14611             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14612         }
14613 
14614         /* link together the rcq chain pages */
14615         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14616             /* index into the rcq chain array to last entry per page */
14617             struct eth_rx_cqe_next_page *rx_cqe_next =
14618                 (struct eth_rx_cqe_next_page *)
14619                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14620             /* point to the next page and wrap from last page */
14621             busaddr = (fp->rcq_dma.paddr +
14622                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14623             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14624             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14625         }
14626 
14627         /*******************/
14628         /* FP RX SGE CHAIN */
14629         /*******************/
14630 
14631         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14632         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14633                           &fp->rx_sge_dma, buf) != 0) {
14634             /* XXX unwind and free previous fastpath allocations */
14635             BLOGE(sc, "Failed to alloc %s\n", buf);
14636             return (1);
14637         } else {
14638             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14639         }
14640 
14641         /* link together the sge chain pages */
14642         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14643             /* index into the rcq chain array to last entry per page */
14644             struct eth_rx_sge *rx_sge =
14645                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14646             /* point to the next page and wrap from last page */
14647             busaddr = (fp->rx_sge_dma.paddr +
14648                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14649             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14650             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14651         }
14652 
14653         /***********************/
14654         /* FP TX MBUF DMA MAPS */
14655         /***********************/
14656 
14657         /* set required sizes before mapping to conserve resources */
14658         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14659             max_size     = BXE_TSO_MAX_SIZE;
14660             max_segments = BXE_TSO_MAX_SEGMENTS;
14661             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14662         } else {
14663             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14664             max_segments = BXE_MAX_SEGMENTS;
14665             max_seg_size = MCLBYTES;
14666         }
14667 
14668         /* create a dma tag for the tx mbufs */
14669         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14670                                 1,                  /* alignment */
14671                                 0,                  /* boundary limit */
14672                                 BUS_SPACE_MAXADDR,  /* restricted low */
14673                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14674                                 NULL,               /* addr filter() */
14675                                 NULL,               /* addr filter() arg */
14676                                 max_size,           /* max map size */
14677                                 max_segments,       /* num discontinuous */
14678                                 max_seg_size,       /* max seg size */
14679                                 0,                  /* flags */
14680                                 NULL,               /* lock() */
14681                                 NULL,               /* lock() arg */
14682                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14683         if (rc != 0) {
14684             /* XXX unwind and free previous fastpath allocations */
14685             BLOGE(sc, "Failed to create dma tag for "
14686                       "'fp %d tx mbufs' (%d)\n", i, rc);
14687             return (1);
14688         }
14689 
14690         /* create dma maps for each of the tx mbuf clusters */
14691         for (j = 0; j < TX_BD_TOTAL; j++) {
14692             if (bus_dmamap_create(fp->tx_mbuf_tag,
14693                                   BUS_DMA_NOWAIT,
14694                                   &fp->tx_mbuf_chain[j].m_map)) {
14695                 /* XXX unwind and free previous fastpath allocations */
14696                 BLOGE(sc, "Failed to create dma map for "
14697                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14698                 return (1);
14699             }
14700         }
14701 
14702         /***********************/
14703         /* FP RX MBUF DMA MAPS */
14704         /***********************/
14705 
14706         /* create a dma tag for the rx mbufs */
14707         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14708                                 1,                  /* alignment */
14709                                 0,                  /* boundary limit */
14710                                 BUS_SPACE_MAXADDR,  /* restricted low */
14711                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14712                                 NULL,               /* addr filter() */
14713                                 NULL,               /* addr filter() arg */
14714                                 MJUM9BYTES,         /* max map size */
14715                                 1,                  /* num discontinuous */
14716                                 MJUM9BYTES,         /* max seg size */
14717                                 0,                  /* flags */
14718                                 NULL,               /* lock() */
14719                                 NULL,               /* lock() arg */
14720                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14721         if (rc != 0) {
14722             /* XXX unwind and free previous fastpath allocations */
14723             BLOGE(sc, "Failed to create dma tag for "
14724                       "'fp %d rx mbufs' (%d)\n", i, rc);
14725             return (1);
14726         }
14727 
14728         /* create dma maps for each of the rx mbuf clusters */
14729         for (j = 0; j < RX_BD_TOTAL; j++) {
14730             if (bus_dmamap_create(fp->rx_mbuf_tag,
14731                                   BUS_DMA_NOWAIT,
14732                                   &fp->rx_mbuf_chain[j].m_map)) {
14733                 /* XXX unwind and free previous fastpath allocations */
14734                 BLOGE(sc, "Failed to create dma map for "
14735                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14736                 return (1);
14737             }
14738         }
14739 
14740         /* create dma map for the spare rx mbuf cluster */
14741         if (bus_dmamap_create(fp->rx_mbuf_tag,
14742                               BUS_DMA_NOWAIT,
14743                               &fp->rx_mbuf_spare_map)) {
14744             /* XXX unwind and free previous fastpath allocations */
14745             BLOGE(sc, "Failed to create dma map for "
14746                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14747             return (1);
14748         }
14749 
14750         /***************************/
14751         /* FP RX SGE MBUF DMA MAPS */
14752         /***************************/
14753 
14754         /* create a dma tag for the rx sge mbufs */
14755         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14756                                 1,                  /* alignment */
14757                                 0,                  /* boundary limit */
14758                                 BUS_SPACE_MAXADDR,  /* restricted low */
14759                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14760                                 NULL,               /* addr filter() */
14761                                 NULL,               /* addr filter() arg */
14762                                 BCM_PAGE_SIZE,      /* max map size */
14763                                 1,                  /* num discontinuous */
14764                                 BCM_PAGE_SIZE,      /* max seg size */
14765                                 0,                  /* flags */
14766                                 NULL,               /* lock() */
14767                                 NULL,               /* lock() arg */
14768                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14769         if (rc != 0) {
14770             /* XXX unwind and free previous fastpath allocations */
14771             BLOGE(sc, "Failed to create dma tag for "
14772                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14773             return (1);
14774         }
14775 
14776         /* create dma maps for the rx sge mbuf clusters */
14777         for (j = 0; j < RX_SGE_TOTAL; j++) {
14778             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14779                                   BUS_DMA_NOWAIT,
14780                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14781                 /* XXX unwind and free previous fastpath allocations */
14782                 BLOGE(sc, "Failed to create dma map for "
14783                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14784                 return (1);
14785             }
14786         }
14787 
14788         /* create dma map for the spare rx sge mbuf cluster */
14789         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14790                               BUS_DMA_NOWAIT,
14791                               &fp->rx_sge_mbuf_spare_map)) {
14792             /* XXX unwind and free previous fastpath allocations */
14793             BLOGE(sc, "Failed to create dma map for "
14794                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14795             return (1);
14796         }
14797 
14798         /***************************/
14799         /* FP RX TPA MBUF DMA MAPS */
14800         /***************************/
14801 
14802         /* create dma maps for the rx tpa mbuf clusters */
14803         max_agg_queues = MAX_AGG_QS(sc);
14804 
14805         for (j = 0; j < max_agg_queues; j++) {
14806             if (bus_dmamap_create(fp->rx_mbuf_tag,
14807                                   BUS_DMA_NOWAIT,
14808                                   &fp->rx_tpa_info[j].bd.m_map)) {
14809                 /* XXX unwind and free previous fastpath allocations */
14810                 BLOGE(sc, "Failed to create dma map for "
14811                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14812                 return (1);
14813             }
14814         }
14815 
14816         /* create dma map for the spare rx tpa mbuf cluster */
14817         if (bus_dmamap_create(fp->rx_mbuf_tag,
14818                               BUS_DMA_NOWAIT,
14819                               &fp->rx_tpa_info_mbuf_spare_map)) {
14820             /* XXX unwind and free previous fastpath allocations */
14821             BLOGE(sc, "Failed to create dma map for "
14822                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14823             return (1);
14824         }
14825 
14826         bxe_init_sge_ring_bit_mask(fp);
14827     }
14828 
14829     return (0);
14830 }
14831 
14832 static void
14833 bxe_free_hsi_mem(struct bxe_softc *sc)
14834 {
14835     struct bxe_fastpath *fp;
14836     int max_agg_queues;
14837     int i, j;
14838 
14839     if (sc->parent_dma_tag == NULL) {
14840         return; /* assume nothing was allocated */
14841     }
14842 
14843     for (i = 0; i < sc->num_queues; i++) {
14844         fp = &sc->fp[i];
14845 
14846         /*******************/
14847         /* FP STATUS BLOCK */
14848         /*******************/
14849 
14850         bxe_dma_free(sc, &fp->sb_dma);
14851         memset(&fp->status_block, 0, sizeof(fp->status_block));
14852 
14853         /******************/
14854         /* FP TX BD CHAIN */
14855         /******************/
14856 
14857         bxe_dma_free(sc, &fp->tx_dma);
14858         fp->tx_chain = NULL;
14859 
14860         /******************/
14861         /* FP RX BD CHAIN */
14862         /******************/
14863 
14864         bxe_dma_free(sc, &fp->rx_dma);
14865         fp->rx_chain = NULL;
14866 
14867         /*******************/
14868         /* FP RX RCQ CHAIN */
14869         /*******************/
14870 
14871         bxe_dma_free(sc, &fp->rcq_dma);
14872         fp->rcq_chain = NULL;
14873 
14874         /*******************/
14875         /* FP RX SGE CHAIN */
14876         /*******************/
14877 
14878         bxe_dma_free(sc, &fp->rx_sge_dma);
14879         fp->rx_sge_chain = NULL;
14880 
14881         /***********************/
14882         /* FP TX MBUF DMA MAPS */
14883         /***********************/
14884 
14885         if (fp->tx_mbuf_tag != NULL) {
14886             for (j = 0; j < TX_BD_TOTAL; j++) {
14887                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14888                     bus_dmamap_unload(fp->tx_mbuf_tag,
14889                                       fp->tx_mbuf_chain[j].m_map);
14890                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14891                                        fp->tx_mbuf_chain[j].m_map);
14892                 }
14893             }
14894 
14895             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14896             fp->tx_mbuf_tag = NULL;
14897         }
14898 
14899         /***********************/
14900         /* FP RX MBUF DMA MAPS */
14901         /***********************/
14902 
14903         if (fp->rx_mbuf_tag != NULL) {
14904             for (j = 0; j < RX_BD_TOTAL; j++) {
14905                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14906                     bus_dmamap_unload(fp->rx_mbuf_tag,
14907                                       fp->rx_mbuf_chain[j].m_map);
14908                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14909                                        fp->rx_mbuf_chain[j].m_map);
14910                 }
14911             }
14912 
14913             if (fp->rx_mbuf_spare_map != NULL) {
14914                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14915                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14916             }
14917 
14918             /***************************/
14919             /* FP RX TPA MBUF DMA MAPS */
14920             /***************************/
14921 
14922             max_agg_queues = MAX_AGG_QS(sc);
14923 
14924             for (j = 0; j < max_agg_queues; j++) {
14925                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14926                     bus_dmamap_unload(fp->rx_mbuf_tag,
14927                                       fp->rx_tpa_info[j].bd.m_map);
14928                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14929                                        fp->rx_tpa_info[j].bd.m_map);
14930                 }
14931             }
14932 
14933             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14934                 bus_dmamap_unload(fp->rx_mbuf_tag,
14935                                   fp->rx_tpa_info_mbuf_spare_map);
14936                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14937                                    fp->rx_tpa_info_mbuf_spare_map);
14938             }
14939 
14940             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14941             fp->rx_mbuf_tag = NULL;
14942         }
14943 
14944         /***************************/
14945         /* FP RX SGE MBUF DMA MAPS */
14946         /***************************/
14947 
14948         if (fp->rx_sge_mbuf_tag != NULL) {
14949             for (j = 0; j < RX_SGE_TOTAL; j++) {
14950                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14951                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14952                                       fp->rx_sge_mbuf_chain[j].m_map);
14953                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14954                                        fp->rx_sge_mbuf_chain[j].m_map);
14955                 }
14956             }
14957 
14958             if (fp->rx_sge_mbuf_spare_map != NULL) {
14959                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14960                                   fp->rx_sge_mbuf_spare_map);
14961                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14962                                    fp->rx_sge_mbuf_spare_map);
14963             }
14964 
14965             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14966             fp->rx_sge_mbuf_tag = NULL;
14967         }
14968     }
14969 
14970     /***************************/
14971     /* FW DECOMPRESSION BUFFER */
14972     /***************************/
14973 
14974     bxe_dma_free(sc, &sc->gz_buf_dma);
14975     sc->gz_buf = NULL;
14976     free(sc->gz_strm, M_DEVBUF);
14977     sc->gz_strm = NULL;
14978 
14979     /*******************/
14980     /* SLOW PATH QUEUE */
14981     /*******************/
14982 
14983     bxe_dma_free(sc, &sc->spq_dma);
14984     sc->spq = NULL;
14985 
14986     /*************/
14987     /* SLOW PATH */
14988     /*************/
14989 
14990     bxe_dma_free(sc, &sc->sp_dma);
14991     sc->sp = NULL;
14992 
14993     /***************/
14994     /* EVENT QUEUE */
14995     /***************/
14996 
14997     bxe_dma_free(sc, &sc->eq_dma);
14998     sc->eq = NULL;
14999 
15000     /************************/
15001     /* DEFAULT STATUS BLOCK */
15002     /************************/
15003 
15004     bxe_dma_free(sc, &sc->def_sb_dma);
15005     sc->def_sb = NULL;
15006 
15007     bus_dma_tag_destroy(sc->parent_dma_tag);
15008     sc->parent_dma_tag = NULL;
15009 }
15010 
15011 /*
15012  * Previous driver DMAE transaction may have occurred when pre-boot stage
15013  * ended and boot began. This would invalidate the addresses of the
15014  * transaction, resulting in was-error bit set in the PCI causing all
15015  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15016  * the interrupt which detected this from the pglueb and the was-done bit
15017  */
15018 static void
15019 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15020 {
15021     uint32_t val;
15022 
15023     if (!CHIP_IS_E1x(sc)) {
15024         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15025         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15026             BLOGD(sc, DBG_LOAD,
15027                   "Clearing 'was-error' bit that was set in pglueb");
15028             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15029         }
15030     }
15031 }
15032 
15033 static int
15034 bxe_prev_mcp_done(struct bxe_softc *sc)
15035 {
15036     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15037                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15038     if (!rc) {
15039         BLOGE(sc, "MCP response failure, aborting\n");
15040         return (-1);
15041     }
15042 
15043     return (0);
15044 }
15045 
15046 static struct bxe_prev_list_node *
15047 bxe_prev_path_get_entry(struct bxe_softc *sc)
15048 {
15049     struct bxe_prev_list_node *tmp;
15050 
15051     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15052         if ((sc->pcie_bus == tmp->bus) &&
15053             (sc->pcie_device == tmp->slot) &&
15054             (SC_PATH(sc) == tmp->path)) {
15055             return (tmp);
15056         }
15057     }
15058 
15059     return (NULL);
15060 }
15061 
15062 static uint8_t
15063 bxe_prev_is_path_marked(struct bxe_softc *sc)
15064 {
15065     struct bxe_prev_list_node *tmp;
15066     int rc = FALSE;
15067 
15068     mtx_lock(&bxe_prev_mtx);
15069 
15070     tmp = bxe_prev_path_get_entry(sc);
15071     if (tmp) {
15072         if (tmp->aer) {
15073             BLOGD(sc, DBG_LOAD,
15074                   "Path %d/%d/%d was marked by AER\n",
15075                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15076         } else {
15077             rc = TRUE;
15078             BLOGD(sc, DBG_LOAD,
15079                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15080                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15081         }
15082     }
15083 
15084     mtx_unlock(&bxe_prev_mtx);
15085 
15086     return (rc);
15087 }
15088 
15089 static int
15090 bxe_prev_mark_path(struct bxe_softc *sc,
15091                    uint8_t          after_undi)
15092 {
15093     struct bxe_prev_list_node *tmp;
15094 
15095     mtx_lock(&bxe_prev_mtx);
15096 
15097     /* Check whether the entry for this path already exists */
15098     tmp = bxe_prev_path_get_entry(sc);
15099     if (tmp) {
15100         if (!tmp->aer) {
15101             BLOGD(sc, DBG_LOAD,
15102                   "Re-marking AER in path %d/%d/%d\n",
15103                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15104         } else {
15105             BLOGD(sc, DBG_LOAD,
15106                   "Removing AER indication from path %d/%d/%d\n",
15107                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15108             tmp->aer = 0;
15109         }
15110 
15111         mtx_unlock(&bxe_prev_mtx);
15112         return (0);
15113     }
15114 
15115     mtx_unlock(&bxe_prev_mtx);
15116 
15117     /* Create an entry for this path and add it */
15118     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15119                  (M_NOWAIT | M_ZERO));
15120     if (!tmp) {
15121         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15122         return (-1);
15123     }
15124 
15125     tmp->bus  = sc->pcie_bus;
15126     tmp->slot = sc->pcie_device;
15127     tmp->path = SC_PATH(sc);
15128     tmp->aer  = 0;
15129     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15130 
15131     mtx_lock(&bxe_prev_mtx);
15132 
15133     BLOGD(sc, DBG_LOAD,
15134           "Marked path %d/%d/%d - finished previous unload\n",
15135           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15136     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15137 
15138     mtx_unlock(&bxe_prev_mtx);
15139 
15140     return (0);
15141 }
15142 
15143 static int
15144 bxe_do_flr(struct bxe_softc *sc)
15145 {
15146     int i;
15147 
15148     /* only E2 and onwards support FLR */
15149     if (CHIP_IS_E1x(sc)) {
15150         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15151         return (-1);
15152     }
15153 
15154     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15155     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15156         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15157               sc->devinfo.bc_ver);
15158         return (-1);
15159     }
15160 
15161     /* Wait for Transaction Pending bit clean */
15162     for (i = 0; i < 4; i++) {
15163         if (i) {
15164             DELAY(((1 << (i - 1)) * 100) * 1000);
15165         }
15166 
15167         if (!bxe_is_pcie_pending(sc)) {
15168             goto clear;
15169         }
15170     }
15171 
15172     BLOGE(sc, "PCIE transaction is not cleared, "
15173               "proceeding with reset anyway\n");
15174 
15175 clear:
15176 
15177     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15178     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15179 
15180     return (0);
15181 }
15182 
15183 struct bxe_mac_vals {
15184     uint32_t xmac_addr;
15185     uint32_t xmac_val;
15186     uint32_t emac_addr;
15187     uint32_t emac_val;
15188     uint32_t umac_addr;
15189     uint32_t umac_val;
15190     uint32_t bmac_addr;
15191     uint32_t bmac_val[2];
15192 };
15193 
15194 static void
15195 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15196                           struct bxe_mac_vals *vals)
15197 {
15198     uint32_t val, base_addr, offset, mask, reset_reg;
15199     uint8_t mac_stopped = FALSE;
15200     uint8_t port = SC_PORT(sc);
15201     uint32_t wb_data[2];
15202 
15203     /* reset addresses as they also mark which values were changed */
15204     vals->bmac_addr = 0;
15205     vals->umac_addr = 0;
15206     vals->xmac_addr = 0;
15207     vals->emac_addr = 0;
15208 
15209     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15210 
15211     if (!CHIP_IS_E3(sc)) {
15212         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15213         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15214         if ((mask & reset_reg) && val) {
15215             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15216             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15217                                     : NIG_REG_INGRESS_BMAC0_MEM;
15218             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15219                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15220 
15221             /*
15222              * use rd/wr since we cannot use dmae. This is safe
15223              * since MCP won't access the bus due to the request
15224              * to unload, and no function on the path can be
15225              * loaded at this time.
15226              */
15227             wb_data[0] = REG_RD(sc, base_addr + offset);
15228             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15229             vals->bmac_addr = base_addr + offset;
15230             vals->bmac_val[0] = wb_data[0];
15231             vals->bmac_val[1] = wb_data[1];
15232             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15233             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15234             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15235         }
15236 
15237         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15238         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15239         vals->emac_val = REG_RD(sc, vals->emac_addr);
15240         REG_WR(sc, vals->emac_addr, 0);
15241         mac_stopped = TRUE;
15242     } else {
15243         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15244             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15245             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15246             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15247             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15248             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15249             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15250             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15251             REG_WR(sc, vals->xmac_addr, 0);
15252             mac_stopped = TRUE;
15253         }
15254 
15255         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15256         if (mask & reset_reg) {
15257             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15258             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15259             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15260             vals->umac_val = REG_RD(sc, vals->umac_addr);
15261             REG_WR(sc, vals->umac_addr, 0);
15262             mac_stopped = TRUE;
15263         }
15264     }
15265 
15266     if (mac_stopped) {
15267         DELAY(20000);
15268     }
15269 }
15270 
15271 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15272 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15273 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15274 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15275 
15276 static void
15277 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15278                          uint8_t          port,
15279                          uint8_t          inc)
15280 {
15281     uint16_t rcq, bd;
15282     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15283 
15284     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15285     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15286 
15287     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15288     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15289 
15290     BLOGD(sc, DBG_LOAD,
15291           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15292           port, bd, rcq);
15293 }
15294 
15295 static int
15296 bxe_prev_unload_common(struct bxe_softc *sc)
15297 {
15298     uint32_t reset_reg, tmp_reg = 0, rc;
15299     uint8_t prev_undi = FALSE;
15300     struct bxe_mac_vals mac_vals;
15301     uint32_t timer_count = 1000;
15302     uint32_t prev_brb;
15303 
15304     /*
15305      * It is possible a previous function received 'common' answer,
15306      * but hasn't loaded yet, therefore creating a scenario of
15307      * multiple functions receiving 'common' on the same path.
15308      */
15309     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15310 
15311     memset(&mac_vals, 0, sizeof(mac_vals));
15312 
15313     if (bxe_prev_is_path_marked(sc)) {
15314         return (bxe_prev_mcp_done(sc));
15315     }
15316 
15317     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15318 
15319     /* Reset should be performed after BRB is emptied */
15320     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15321         /* Close the MAC Rx to prevent BRB from filling up */
15322         bxe_prev_unload_close_mac(sc, &mac_vals);
15323 
15324         /* close LLH filters towards the BRB */
15325         elink_set_rx_filter(&sc->link_params, 0);
15326 
15327         /*
15328          * Check if the UNDI driver was previously loaded.
15329          * UNDI driver initializes CID offset for normal bell to 0x7
15330          */
15331         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15332             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15333             if (tmp_reg == 0x7) {
15334                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15335                 prev_undi = TRUE;
15336                 /* clear the UNDI indication */
15337                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15338                 /* clear possible idle check errors */
15339                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15340             }
15341         }
15342 
15343         /* wait until BRB is empty */
15344         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15345         while (timer_count) {
15346             prev_brb = tmp_reg;
15347 
15348             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15349             if (!tmp_reg) {
15350                 break;
15351             }
15352 
15353             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15354 
15355             /* reset timer as long as BRB actually gets emptied */
15356             if (prev_brb > tmp_reg) {
15357                 timer_count = 1000;
15358             } else {
15359                 timer_count--;
15360             }
15361 
15362             /* If UNDI resides in memory, manually increment it */
15363             if (prev_undi) {
15364                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15365             }
15366 
15367             DELAY(10);
15368         }
15369 
15370         if (!timer_count) {
15371             BLOGE(sc, "Failed to empty BRB\n");
15372         }
15373     }
15374 
15375     /* No packets are in the pipeline, path is ready for reset */
15376     bxe_reset_common(sc);
15377 
15378     if (mac_vals.xmac_addr) {
15379         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15380     }
15381     if (mac_vals.umac_addr) {
15382         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15383     }
15384     if (mac_vals.emac_addr) {
15385         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15386     }
15387     if (mac_vals.bmac_addr) {
15388         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15389         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15390     }
15391 
15392     rc = bxe_prev_mark_path(sc, prev_undi);
15393     if (rc) {
15394         bxe_prev_mcp_done(sc);
15395         return (rc);
15396     }
15397 
15398     return (bxe_prev_mcp_done(sc));
15399 }
15400 
15401 static int
15402 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15403 {
15404     int rc;
15405 
15406     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15407 
15408     /* Test if previous unload process was already finished for this path */
15409     if (bxe_prev_is_path_marked(sc)) {
15410         return (bxe_prev_mcp_done(sc));
15411     }
15412 
15413     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15414 
15415     /*
15416      * If function has FLR capabilities, and existing FW version matches
15417      * the one required, then FLR will be sufficient to clean any residue
15418      * left by previous driver
15419      */
15420     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15421     if (!rc) {
15422         /* fw version is good */
15423         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15424         rc = bxe_do_flr(sc);
15425     }
15426 
15427     if (!rc) {
15428         /* FLR was performed */
15429         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15430         return (0);
15431     }
15432 
15433     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15434 
15435     /* Close the MCP request, return failure*/
15436     rc = bxe_prev_mcp_done(sc);
15437     if (!rc) {
15438         rc = BXE_PREV_WAIT_NEEDED;
15439     }
15440 
15441     return (rc);
15442 }
15443 
15444 static int
15445 bxe_prev_unload(struct bxe_softc *sc)
15446 {
15447     int time_counter = 10;
15448     uint32_t fw, hw_lock_reg, hw_lock_val;
15449     uint32_t rc = 0;
15450 
15451     /*
15452      * Clear HW from errors which may have resulted from an interrupted
15453      * DMAE transaction.
15454      */
15455     bxe_prev_interrupted_dmae(sc);
15456 
15457     /* Release previously held locks */
15458     hw_lock_reg =
15459         (SC_FUNC(sc) <= 5) ?
15460             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15461             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15462 
15463     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15464     if (hw_lock_val) {
15465         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15466             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15467             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15468                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15469         }
15470         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15471         REG_WR(sc, hw_lock_reg, 0xffffffff);
15472     } else {
15473         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15474     }
15475 
15476     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15477         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15478         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15479     }
15480 
15481     do {
15482         /* Lock MCP using an unload request */
15483         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15484         if (!fw) {
15485             BLOGE(sc, "MCP response failure, aborting\n");
15486             rc = -1;
15487             break;
15488         }
15489 
15490         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15491             rc = bxe_prev_unload_common(sc);
15492             break;
15493         }
15494 
15495         /* non-common reply from MCP night require looping */
15496         rc = bxe_prev_unload_uncommon(sc);
15497         if (rc != BXE_PREV_WAIT_NEEDED) {
15498             break;
15499         }
15500 
15501         DELAY(20000);
15502     } while (--time_counter);
15503 
15504     if (!time_counter || rc) {
15505         BLOGE(sc, "Failed to unload previous driver!"
15506             " time_counter %d rc %d\n", time_counter, rc);
15507         rc = -1;
15508     }
15509 
15510     return (rc);
15511 }
15512 
15513 void
15514 bxe_dcbx_set_state(struct bxe_softc *sc,
15515                    uint8_t          dcb_on,
15516                    uint32_t         dcbx_enabled)
15517 {
15518     if (!CHIP_IS_E1x(sc)) {
15519         sc->dcb_state = dcb_on;
15520         sc->dcbx_enabled = dcbx_enabled;
15521     } else {
15522         sc->dcb_state = FALSE;
15523         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15524     }
15525     BLOGD(sc, DBG_LOAD,
15526           "DCB state [%s:%s]\n",
15527           dcb_on ? "ON" : "OFF",
15528           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15529           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15530           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15531           "on-chip with negotiation" : "invalid");
15532 }
15533 
15534 /* must be called after sriov-enable */
15535 static int
15536 bxe_set_qm_cid_count(struct bxe_softc *sc)
15537 {
15538     int cid_count = BXE_L2_MAX_CID(sc);
15539 
15540     if (IS_SRIOV(sc)) {
15541         cid_count += BXE_VF_CIDS;
15542     }
15543 
15544     if (CNIC_SUPPORT(sc)) {
15545         cid_count += CNIC_CID_MAX;
15546     }
15547 
15548     return (roundup(cid_count, QM_CID_ROUND));
15549 }
15550 
15551 static void
15552 bxe_init_multi_cos(struct bxe_softc *sc)
15553 {
15554     int pri, cos;
15555 
15556     uint32_t pri_map = 0; /* XXX change to user config */
15557 
15558     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15559         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15560         if (cos < sc->max_cos) {
15561             sc->prio_to_cos[pri] = cos;
15562         } else {
15563             BLOGW(sc, "Invalid COS %d for priority %d "
15564                       "(max COS is %d), setting to 0\n",
15565                   cos, pri, (sc->max_cos - 1));
15566             sc->prio_to_cos[pri] = 0;
15567         }
15568     }
15569 }
15570 
15571 static int
15572 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15573 {
15574     struct bxe_softc *sc;
15575     int error, result;
15576 
15577     result = 0;
15578     error = sysctl_handle_int(oidp, &result, 0, req);
15579 
15580     if (error || !req->newptr) {
15581         return (error);
15582     }
15583 
15584     if (result == 1) {
15585         uint32_t  temp;
15586         sc = (struct bxe_softc *)arg1;
15587 
15588         BLOGI(sc, "... dumping driver state ...\n");
15589         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15590         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15591     }
15592 
15593     return (error);
15594 }
15595 
15596 static int
15597 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15598 {
15599     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15600     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15601     uint32_t *offset;
15602     uint64_t value = 0;
15603     int index = (int)arg2;
15604 
15605     if (index >= BXE_NUM_ETH_STATS) {
15606         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15607         return (-1);
15608     }
15609 
15610     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15611 
15612     switch (bxe_eth_stats_arr[index].size) {
15613     case 4:
15614         value = (uint64_t)*offset;
15615         break;
15616     case 8:
15617         value = HILO_U64(*offset, *(offset + 1));
15618         break;
15619     default:
15620         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15621               index, bxe_eth_stats_arr[index].size);
15622         return (-1);
15623     }
15624 
15625     return (sysctl_handle_64(oidp, &value, 0, req));
15626 }
15627 
15628 static int
15629 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15630 {
15631     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15632     uint32_t *eth_stats;
15633     uint32_t *offset;
15634     uint64_t value = 0;
15635     uint32_t q_stat = (uint32_t)arg2;
15636     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15637     uint32_t index = (q_stat & 0xffff);
15638 
15639     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15640 
15641     if (index >= BXE_NUM_ETH_Q_STATS) {
15642         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15643         return (-1);
15644     }
15645 
15646     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15647 
15648     switch (bxe_eth_q_stats_arr[index].size) {
15649     case 4:
15650         value = (uint64_t)*offset;
15651         break;
15652     case 8:
15653         value = HILO_U64(*offset, *(offset + 1));
15654         break;
15655     default:
15656         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15657               index, bxe_eth_q_stats_arr[index].size);
15658         return (-1);
15659     }
15660 
15661     return (sysctl_handle_64(oidp, &value, 0, req));
15662 }
15663 
15664 static void bxe_force_link_reset(struct bxe_softc *sc)
15665 {
15666 
15667         bxe_acquire_phy_lock(sc);
15668         elink_link_reset(&sc->link_params, &sc->link_vars, 1);
15669         bxe_release_phy_lock(sc);
15670 }
15671 
15672 static int
15673 bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
15674 {
15675         struct bxe_softc *sc = (struct bxe_softc *)arg1;;
15676         uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
15677         int rc = 0;
15678         int error;
15679         int result;
15680 
15681 
15682         error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
15683 
15684         if (error || !req->newptr) {
15685                 return (error);
15686         }
15687         if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
15688                 BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
15689                 sc->bxe_pause_param = 8;
15690         }
15691 
15692         result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
15693 
15694 
15695         if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
15696                         BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
15697                         return -EINVAL;
15698         }
15699 
15700         if(IS_MF(sc))
15701                 return 0;
15702        sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
15703         if(result & ELINK_FLOW_CTRL_RX)
15704                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
15705 
15706         if(result & ELINK_FLOW_CTRL_TX)
15707                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
15708         if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
15709                 sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
15710 
15711         if(result & 0x400) {
15712                 if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
15713                         sc->link_params.req_flow_ctrl[cfg_idx] =
15714                                 ELINK_FLOW_CTRL_AUTO;
15715                 }
15716                 sc->link_params.req_fc_auto_adv = 0;
15717                 if (result & ELINK_FLOW_CTRL_RX)
15718                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
15719 
15720                 if (result & ELINK_FLOW_CTRL_TX)
15721                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
15722                 if (!sc->link_params.req_fc_auto_adv)
15723                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
15724         }
15725          if (IS_PF(sc)) {
15726                         if (sc->link_vars.link_up) {
15727                                 bxe_stats_handle(sc, STATS_EVENT_STOP);
15728                         }
15729 			if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
15730                         bxe_force_link_reset(sc);
15731                         bxe_acquire_phy_lock(sc);
15732 
15733                         rc = elink_phy_init(&sc->link_params, &sc->link_vars);
15734 
15735                         bxe_release_phy_lock(sc);
15736 
15737                         bxe_calc_fc_adv(sc);
15738                         }
15739         }
15740         return rc;
15741 }
15742 
15743 
15744 static void
15745 bxe_add_sysctls(struct bxe_softc *sc)
15746 {
15747     struct sysctl_ctx_list *ctx;
15748     struct sysctl_oid_list *children;
15749     struct sysctl_oid *queue_top, *queue;
15750     struct sysctl_oid_list *queue_top_children, *queue_children;
15751     char queue_num_buf[32];
15752     uint32_t q_stat;
15753     int i, j;
15754 
15755     ctx = device_get_sysctl_ctx(sc->dev);
15756     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15757 
15758     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15759                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15760                       "version");
15761 
15762     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15763              BCM_5710_FW_MAJOR_VERSION,
15764              BCM_5710_FW_MINOR_VERSION,
15765              BCM_5710_FW_REVISION_VERSION,
15766              BCM_5710_FW_ENGINEERING_VERSION);
15767 
15768     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15769         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15770          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15771          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15772          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15773                                                                 "Unknown"));
15774     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15775                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15776                     "multifunction vnics per port");
15777 
15778     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15779         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15780          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15781          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15782                                               "???GT/s"),
15783         sc->devinfo.pcie_link_width);
15784 
15785     sc->debug = bxe_debug;
15786 
15787 #if __FreeBSD_version >= 900000
15788     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15789                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15790                       "bootcode version");
15791     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15792                       CTLFLAG_RD, sc->fw_ver_str, 0,
15793                       "firmware version");
15794     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15795                       CTLFLAG_RD, sc->mf_mode_str, 0,
15796                       "multifunction mode");
15797     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15798                       CTLFLAG_RD, sc->mac_addr_str, 0,
15799                       "mac address");
15800     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15801                       CTLFLAG_RD, sc->pci_link_str, 0,
15802                       "pci link status");
15803     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15804                     CTLFLAG_RW, &sc->debug,
15805                     "debug logging mode");
15806 #else
15807     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15808                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15809                       "bootcode version");
15810     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15811                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15812                       "firmware version");
15813     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15814                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15815                       "multifunction mode");
15816     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15817                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15818                       "mac address");
15819     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15820                       CTLFLAG_RD, &sc->pci_link_str, 0,
15821                       "pci link status");
15822     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15823                     CTLFLAG_RW, &sc->debug, 0,
15824                     "debug logging mode");
15825 #endif /* #if __FreeBSD_version >= 900000 */
15826 
15827     sc->trigger_grcdump = 0;
15828     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15829                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15830                    "trigger grcdump should be invoked"
15831                    "  before collecting grcdump");
15832 
15833     sc->grcdump_started = 0;
15834     sc->grcdump_done = 0;
15835     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15836                    CTLFLAG_RD, &sc->grcdump_done, 0,
15837                    "set by driver when grcdump is done");
15838 
15839     sc->rx_budget = bxe_rx_budget;
15840     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15841                     CTLFLAG_RW, &sc->rx_budget, 0,
15842                     "rx processing budget");
15843 
15844    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
15845                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15846                     bxe_sysctl_pauseparam, "IU",
15847                     "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
15848 
15849 
15850     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15851                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15852                     bxe_sysctl_state, "IU", "dump driver state");
15853 
15854     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15855         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15856                         bxe_eth_stats_arr[i].string,
15857                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15858                         bxe_sysctl_eth_stat, "LU",
15859                         bxe_eth_stats_arr[i].string);
15860     }
15861 
15862     /* add a new parent node for all queues "dev.bxe.#.queue" */
15863     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15864                                 CTLFLAG_RD, NULL, "queue");
15865     queue_top_children = SYSCTL_CHILDREN(queue_top);
15866 
15867     for (i = 0; i < sc->num_queues; i++) {
15868         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15869         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15870         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15871                                 queue_num_buf, CTLFLAG_RD, NULL,
15872                                 "single queue");
15873         queue_children = SYSCTL_CHILDREN(queue);
15874 
15875         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15876             q_stat = ((i << 16) | j);
15877             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15878                             bxe_eth_q_stats_arr[j].string,
15879                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15880                             bxe_sysctl_eth_q_stat, "LU",
15881                             bxe_eth_q_stats_arr[j].string);
15882         }
15883     }
15884 }
15885 
15886 static int
15887 bxe_alloc_buf_rings(struct bxe_softc *sc)
15888 {
15889 #if __FreeBSD_version >= 901504
15890 
15891     int i;
15892     struct bxe_fastpath *fp;
15893 
15894     for (i = 0; i < sc->num_queues; i++) {
15895 
15896         fp = &sc->fp[i];
15897 
15898         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15899                                    M_NOWAIT, &fp->tx_mtx);
15900         if (fp->tx_br == NULL)
15901             return (-1);
15902     }
15903 #endif
15904     return (0);
15905 }
15906 
15907 static void
15908 bxe_free_buf_rings(struct bxe_softc *sc)
15909 {
15910 #if __FreeBSD_version >= 901504
15911 
15912     int i;
15913     struct bxe_fastpath *fp;
15914 
15915     for (i = 0; i < sc->num_queues; i++) {
15916 
15917         fp = &sc->fp[i];
15918 
15919         if (fp->tx_br) {
15920             buf_ring_free(fp->tx_br, M_DEVBUF);
15921             fp->tx_br = NULL;
15922         }
15923     }
15924 
15925 #endif
15926 }
15927 
15928 static void
15929 bxe_init_fp_mutexs(struct bxe_softc *sc)
15930 {
15931     int i;
15932     struct bxe_fastpath *fp;
15933 
15934     for (i = 0; i < sc->num_queues; i++) {
15935 
15936         fp = &sc->fp[i];
15937 
15938         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15939             "bxe%d_fp%d_tx_lock", sc->unit, i);
15940         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15941 
15942         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15943             "bxe%d_fp%d_rx_lock", sc->unit, i);
15944         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15945     }
15946 }
15947 
15948 static void
15949 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15950 {
15951     int i;
15952     struct bxe_fastpath *fp;
15953 
15954     for (i = 0; i < sc->num_queues; i++) {
15955 
15956         fp = &sc->fp[i];
15957 
15958         if (mtx_initialized(&fp->tx_mtx)) {
15959             mtx_destroy(&fp->tx_mtx);
15960         }
15961 
15962         if (mtx_initialized(&fp->rx_mtx)) {
15963             mtx_destroy(&fp->rx_mtx);
15964         }
15965     }
15966 }
15967 
15968 
15969 /*
15970  * Device attach function.
15971  *
15972  * Allocates device resources, performs secondary chip identification, and
15973  * initializes driver instance variables. This function is called from driver
15974  * load after a successful probe.
15975  *
15976  * Returns:
15977  *   0 = Success, >0 = Failure
15978  */
15979 static int
15980 bxe_attach(device_t dev)
15981 {
15982     struct bxe_softc *sc;
15983 
15984     sc = device_get_softc(dev);
15985 
15986     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15987 
15988     sc->state = BXE_STATE_CLOSED;
15989 
15990     sc->dev  = dev;
15991     sc->unit = device_get_unit(dev);
15992 
15993     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15994 
15995     sc->pcie_bus    = pci_get_bus(dev);
15996     sc->pcie_device = pci_get_slot(dev);
15997     sc->pcie_func   = pci_get_function(dev);
15998 
15999     /* enable bus master capability */
16000     pci_enable_busmaster(dev);
16001 
16002     /* get the BARs */
16003     if (bxe_allocate_bars(sc) != 0) {
16004         return (ENXIO);
16005     }
16006 
16007     /* initialize the mutexes */
16008     bxe_init_mutexes(sc);
16009 
16010     /* prepare the periodic callout */
16011     callout_init(&sc->periodic_callout, 0);
16012 
16013     /* prepare the chip taskqueue */
16014     sc->chip_tq_flags = CHIP_TQ_NONE;
16015     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16016              "bxe%d_chip_tq", sc->unit);
16017     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16018     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16019                                    taskqueue_thread_enqueue,
16020                                    &sc->chip_tq);
16021     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16022                             "%s", sc->chip_tq_name);
16023 
16024     /* get device info and set params */
16025     if (bxe_get_device_info(sc) != 0) {
16026         BLOGE(sc, "getting device info\n");
16027         bxe_deallocate_bars(sc);
16028         pci_disable_busmaster(dev);
16029         return (ENXIO);
16030     }
16031 
16032     /* get final misc params */
16033     bxe_get_params(sc);
16034 
16035     /* set the default MTU (changed via ifconfig) */
16036     sc->mtu = ETHERMTU;
16037 
16038     bxe_set_modes_bitmap(sc);
16039 
16040     /* XXX
16041      * If in AFEX mode and the function is configured for FCoE
16042      * then bail... no L2 allowed.
16043      */
16044 
16045     /* get phy settings from shmem and 'and' against admin settings */
16046     bxe_get_phy_info(sc);
16047 
16048     /* initialize the FreeBSD ifnet interface */
16049     if (bxe_init_ifnet(sc) != 0) {
16050         bxe_release_mutexes(sc);
16051         bxe_deallocate_bars(sc);
16052         pci_disable_busmaster(dev);
16053         return (ENXIO);
16054     }
16055 
16056     if (bxe_add_cdev(sc) != 0) {
16057         if (sc->ifp != NULL) {
16058             ether_ifdetach(sc->ifp);
16059         }
16060         ifmedia_removeall(&sc->ifmedia);
16061         bxe_release_mutexes(sc);
16062         bxe_deallocate_bars(sc);
16063         pci_disable_busmaster(dev);
16064         return (ENXIO);
16065     }
16066 
16067     /* allocate device interrupts */
16068     if (bxe_interrupt_alloc(sc) != 0) {
16069         bxe_del_cdev(sc);
16070         if (sc->ifp != NULL) {
16071             ether_ifdetach(sc->ifp);
16072         }
16073         ifmedia_removeall(&sc->ifmedia);
16074         bxe_release_mutexes(sc);
16075         bxe_deallocate_bars(sc);
16076         pci_disable_busmaster(dev);
16077         return (ENXIO);
16078     }
16079 
16080     bxe_init_fp_mutexs(sc);
16081 
16082     if (bxe_alloc_buf_rings(sc) != 0) {
16083 	bxe_free_buf_rings(sc);
16084         bxe_interrupt_free(sc);
16085         bxe_del_cdev(sc);
16086         if (sc->ifp != NULL) {
16087             ether_ifdetach(sc->ifp);
16088         }
16089         ifmedia_removeall(&sc->ifmedia);
16090         bxe_release_mutexes(sc);
16091         bxe_deallocate_bars(sc);
16092         pci_disable_busmaster(dev);
16093         return (ENXIO);
16094     }
16095 
16096     /* allocate ilt */
16097     if (bxe_alloc_ilt_mem(sc) != 0) {
16098 	bxe_free_buf_rings(sc);
16099         bxe_interrupt_free(sc);
16100         bxe_del_cdev(sc);
16101         if (sc->ifp != NULL) {
16102             ether_ifdetach(sc->ifp);
16103         }
16104         ifmedia_removeall(&sc->ifmedia);
16105         bxe_release_mutexes(sc);
16106         bxe_deallocate_bars(sc);
16107         pci_disable_busmaster(dev);
16108         return (ENXIO);
16109     }
16110 
16111     /* allocate the host hardware/software hsi structures */
16112     if (bxe_alloc_hsi_mem(sc) != 0) {
16113         bxe_free_ilt_mem(sc);
16114 	bxe_free_buf_rings(sc);
16115         bxe_interrupt_free(sc);
16116         bxe_del_cdev(sc);
16117         if (sc->ifp != NULL) {
16118             ether_ifdetach(sc->ifp);
16119         }
16120         ifmedia_removeall(&sc->ifmedia);
16121         bxe_release_mutexes(sc);
16122         bxe_deallocate_bars(sc);
16123         pci_disable_busmaster(dev);
16124         return (ENXIO);
16125     }
16126 
16127     /* need to reset chip if UNDI was active */
16128     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16129         /* init fw_seq */
16130         sc->fw_seq =
16131             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16132              DRV_MSG_SEQ_NUMBER_MASK);
16133         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16134         bxe_prev_unload(sc);
16135     }
16136 
16137 #if 1
16138     /* XXX */
16139     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16140 #else
16141     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16142         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16143         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16144         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16145         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16146         bxe_dcbx_init_params(sc);
16147     } else {
16148         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16149     }
16150 #endif
16151 
16152     /* calculate qm_cid_count */
16153     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16154     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16155 
16156     sc->max_cos = 1;
16157     bxe_init_multi_cos(sc);
16158 
16159     bxe_add_sysctls(sc);
16160 
16161     return (0);
16162 }
16163 
16164 /*
16165  * Device detach function.
16166  *
16167  * Stops the controller, resets the controller, and releases resources.
16168  *
16169  * Returns:
16170  *   0 = Success, >0 = Failure
16171  */
16172 static int
16173 bxe_detach(device_t dev)
16174 {
16175     struct bxe_softc *sc;
16176     if_t ifp;
16177 
16178     sc = device_get_softc(dev);
16179 
16180     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16181 
16182     ifp = sc->ifp;
16183     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16184         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16185         return(EBUSY);
16186     }
16187 
16188     bxe_del_cdev(sc);
16189 
16190     /* stop the periodic callout */
16191     bxe_periodic_stop(sc);
16192 
16193     /* stop the chip taskqueue */
16194     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16195     if (sc->chip_tq) {
16196         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16197         taskqueue_free(sc->chip_tq);
16198         sc->chip_tq = NULL;
16199     }
16200 
16201     /* stop and reset the controller if it was open */
16202     if (sc->state != BXE_STATE_CLOSED) {
16203         BXE_CORE_LOCK(sc);
16204         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16205         sc->state = BXE_STATE_DISABLED;
16206         BXE_CORE_UNLOCK(sc);
16207     }
16208 
16209     /* release the network interface */
16210     if (ifp != NULL) {
16211         ether_ifdetach(ifp);
16212     }
16213     ifmedia_removeall(&sc->ifmedia);
16214 
16215     /* XXX do the following based on driver state... */
16216 
16217     /* free the host hardware/software hsi structures */
16218     bxe_free_hsi_mem(sc);
16219 
16220     /* free ilt */
16221     bxe_free_ilt_mem(sc);
16222 
16223     bxe_free_buf_rings(sc);
16224 
16225     /* release the interrupts */
16226     bxe_interrupt_free(sc);
16227 
16228     /* Release the mutexes*/
16229     bxe_destroy_fp_mutexs(sc);
16230     bxe_release_mutexes(sc);
16231 
16232 
16233     /* Release the PCIe BAR mapped memory */
16234     bxe_deallocate_bars(sc);
16235 
16236     /* Release the FreeBSD interface. */
16237     if (sc->ifp != NULL) {
16238         if_free(sc->ifp);
16239     }
16240 
16241     pci_disable_busmaster(dev);
16242 
16243     return (0);
16244 }
16245 
16246 /*
16247  * Device shutdown function.
16248  *
16249  * Stops and resets the controller.
16250  *
16251  * Returns:
16252  *   Nothing
16253  */
16254 static int
16255 bxe_shutdown(device_t dev)
16256 {
16257     struct bxe_softc *sc;
16258 
16259     sc = device_get_softc(dev);
16260 
16261     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16262 
16263     /* stop the periodic callout */
16264     bxe_periodic_stop(sc);
16265 
16266     BXE_CORE_LOCK(sc);
16267     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16268     BXE_CORE_UNLOCK(sc);
16269 
16270     return (0);
16271 }
16272 
16273 void
16274 bxe_igu_ack_sb(struct bxe_softc *sc,
16275                uint8_t          igu_sb_id,
16276                uint8_t          segment,
16277                uint16_t         index,
16278                uint8_t          op,
16279                uint8_t          update)
16280 {
16281     uint32_t igu_addr = sc->igu_base_addr;
16282     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16283     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16284 }
16285 
16286 static void
16287 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16288                      uint8_t          func,
16289                      uint8_t          idu_sb_id,
16290                      uint8_t          is_pf)
16291 {
16292     uint32_t data, ctl, cnt = 100;
16293     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16294     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16295     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16296     uint32_t sb_bit =  1 << (idu_sb_id%32);
16297     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16298     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16299 
16300     /* Not supported in BC mode */
16301     if (CHIP_INT_MODE_IS_BC(sc)) {
16302         return;
16303     }
16304 
16305     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16306              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16307             IGU_REGULAR_CLEANUP_SET |
16308             IGU_REGULAR_BCLEANUP);
16309 
16310     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16311            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16312            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16313 
16314     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16315             data, igu_addr_data);
16316     REG_WR(sc, igu_addr_data, data);
16317 
16318     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16319                       BUS_SPACE_BARRIER_WRITE);
16320     mb();
16321 
16322     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16323             ctl, igu_addr_ctl);
16324     REG_WR(sc, igu_addr_ctl, ctl);
16325 
16326     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16327                       BUS_SPACE_BARRIER_WRITE);
16328     mb();
16329 
16330     /* wait for clean up to finish */
16331     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16332         DELAY(20000);
16333     }
16334 
16335     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16336         BLOGD(sc, DBG_LOAD,
16337               "Unable to finish IGU cleanup: "
16338               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16339               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16340     }
16341 }
16342 
16343 static void
16344 bxe_igu_clear_sb(struct bxe_softc *sc,
16345                  uint8_t          idu_sb_id)
16346 {
16347     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16348 }
16349 
16350 
16351 
16352 
16353 
16354 
16355 
16356 /*******************/
16357 /* ECORE CALLBACKS */
16358 /*******************/
16359 
16360 static void
16361 bxe_reset_common(struct bxe_softc *sc)
16362 {
16363     uint32_t val = 0x1400;
16364 
16365     /* reset_common */
16366     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16367 
16368     if (CHIP_IS_E3(sc)) {
16369         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16370         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16371     }
16372 
16373     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16374 }
16375 
16376 static void
16377 bxe_common_init_phy(struct bxe_softc *sc)
16378 {
16379     uint32_t shmem_base[2];
16380     uint32_t shmem2_base[2];
16381 
16382     /* Avoid common init in case MFW supports LFA */
16383     if (SHMEM2_RD(sc, size) >
16384         (uint32_t)offsetof(struct shmem2_region,
16385                            lfa_host_addr[SC_PORT(sc)])) {
16386         return;
16387     }
16388 
16389     shmem_base[0]  = sc->devinfo.shmem_base;
16390     shmem2_base[0] = sc->devinfo.shmem2_base;
16391 
16392     if (!CHIP_IS_E1x(sc)) {
16393         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16394         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16395     }
16396 
16397     bxe_acquire_phy_lock(sc);
16398     elink_common_init_phy(sc, shmem_base, shmem2_base,
16399                           sc->devinfo.chip_id, 0);
16400     bxe_release_phy_lock(sc);
16401 }
16402 
16403 static void
16404 bxe_pf_disable(struct bxe_softc *sc)
16405 {
16406     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16407 
16408     val &= ~IGU_PF_CONF_FUNC_EN;
16409 
16410     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16411     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16412     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16413 }
16414 
16415 static void
16416 bxe_init_pxp(struct bxe_softc *sc)
16417 {
16418     uint16_t devctl;
16419     int r_order, w_order;
16420 
16421     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16422 
16423     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16424 
16425     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16426 
16427     if (sc->mrrs == -1) {
16428         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16429     } else {
16430         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16431         r_order = sc->mrrs;
16432     }
16433 
16434     ecore_init_pxp_arb(sc, r_order, w_order);
16435 }
16436 
16437 static uint32_t
16438 bxe_get_pretend_reg(struct bxe_softc *sc)
16439 {
16440     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16441     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16442     return (base + (SC_ABS_FUNC(sc)) * stride);
16443 }
16444 
16445 /*
16446  * Called only on E1H or E2.
16447  * When pretending to be PF, the pretend value is the function number 0..7.
16448  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16449  * combination.
16450  */
16451 static int
16452 bxe_pretend_func(struct bxe_softc *sc,
16453                  uint16_t         pretend_func_val)
16454 {
16455     uint32_t pretend_reg;
16456 
16457     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16458         return (-1);
16459     }
16460 
16461     /* get my own pretend register */
16462     pretend_reg = bxe_get_pretend_reg(sc);
16463     REG_WR(sc, pretend_reg, pretend_func_val);
16464     REG_RD(sc, pretend_reg);
16465     return (0);
16466 }
16467 
16468 static void
16469 bxe_iov_init_dmae(struct bxe_softc *sc)
16470 {
16471     return;
16472 }
16473 
16474 static void
16475 bxe_iov_init_dq(struct bxe_softc *sc)
16476 {
16477     return;
16478 }
16479 
16480 /* send a NIG loopback debug packet */
16481 static void
16482 bxe_lb_pckt(struct bxe_softc *sc)
16483 {
16484     uint32_t wb_write[3];
16485 
16486     /* Ethernet source and destination addresses */
16487     wb_write[0] = 0x55555555;
16488     wb_write[1] = 0x55555555;
16489     wb_write[2] = 0x20;     /* SOP */
16490     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16491 
16492     /* NON-IP protocol */
16493     wb_write[0] = 0x09000000;
16494     wb_write[1] = 0x55555555;
16495     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16496     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16497 }
16498 
16499 /*
16500  * Some of the internal memories are not directly readable from the driver.
16501  * To test them we send debug packets.
16502  */
16503 static int
16504 bxe_int_mem_test(struct bxe_softc *sc)
16505 {
16506     int factor;
16507     int count, i;
16508     uint32_t val = 0;
16509 
16510     if (CHIP_REV_IS_FPGA(sc)) {
16511         factor = 120;
16512     } else if (CHIP_REV_IS_EMUL(sc)) {
16513         factor = 200;
16514     } else {
16515         factor = 1;
16516     }
16517 
16518     /* disable inputs of parser neighbor blocks */
16519     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16520     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16521     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16522     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16523 
16524     /*  write 0 to parser credits for CFC search request */
16525     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16526 
16527     /* send Ethernet packet */
16528     bxe_lb_pckt(sc);
16529 
16530     /* TODO do i reset NIG statistic? */
16531     /* Wait until NIG register shows 1 packet of size 0x10 */
16532     count = 1000 * factor;
16533     while (count) {
16534         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16535         val = *BXE_SP(sc, wb_data[0]);
16536         if (val == 0x10) {
16537             break;
16538         }
16539 
16540         DELAY(10000);
16541         count--;
16542     }
16543 
16544     if (val != 0x10) {
16545         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16546         return (-1);
16547     }
16548 
16549     /* wait until PRS register shows 1 packet */
16550     count = (1000 * factor);
16551     while (count) {
16552         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16553         if (val == 1) {
16554             break;
16555         }
16556 
16557         DELAY(10000);
16558         count--;
16559     }
16560 
16561     if (val != 0x1) {
16562         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16563         return (-2);
16564     }
16565 
16566     /* Reset and init BRB, PRS */
16567     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16568     DELAY(50000);
16569     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16570     DELAY(50000);
16571     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16572     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16573 
16574     /* Disable inputs of parser neighbor blocks */
16575     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16576     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16577     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16578     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16579 
16580     /* Write 0 to parser credits for CFC search request */
16581     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16582 
16583     /* send 10 Ethernet packets */
16584     for (i = 0; i < 10; i++) {
16585         bxe_lb_pckt(sc);
16586     }
16587 
16588     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16589     count = (1000 * factor);
16590     while (count) {
16591         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16592         val = *BXE_SP(sc, wb_data[0]);
16593         if (val == 0xb0) {
16594             break;
16595         }
16596 
16597         DELAY(10000);
16598         count--;
16599     }
16600 
16601     if (val != 0xb0) {
16602         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16603         return (-3);
16604     }
16605 
16606     /* Wait until PRS register shows 2 packets */
16607     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16608     if (val != 2) {
16609         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16610     }
16611 
16612     /* Write 1 to parser credits for CFC search request */
16613     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16614 
16615     /* Wait until PRS register shows 3 packets */
16616     DELAY(10000 * factor);
16617 
16618     /* Wait until NIG register shows 1 packet of size 0x10 */
16619     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16620     if (val != 3) {
16621         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16622     }
16623 
16624     /* clear NIG EOP FIFO */
16625     for (i = 0; i < 11; i++) {
16626         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16627     }
16628 
16629     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16630     if (val != 1) {
16631         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16632         return (-4);
16633     }
16634 
16635     /* Reset and init BRB, PRS, NIG */
16636     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16637     DELAY(50000);
16638     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16639     DELAY(50000);
16640     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16641     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16642     if (!CNIC_SUPPORT(sc)) {
16643         /* set NIC mode */
16644         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16645     }
16646 
16647     /* Enable inputs of parser neighbor blocks */
16648     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16649     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16650     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16651     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16652 
16653     return (0);
16654 }
16655 
16656 static void
16657 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16658 {
16659     int is_required;
16660     uint32_t val;
16661     int port;
16662 
16663     is_required = 0;
16664     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16665            SHARED_HW_CFG_FAN_FAILURE_MASK);
16666 
16667     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16668         is_required = 1;
16669     }
16670     /*
16671      * The fan failure mechanism is usually related to the PHY type since
16672      * the power consumption of the board is affected by the PHY. Currently,
16673      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16674      */
16675     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16676         for (port = PORT_0; port < PORT_MAX; port++) {
16677             is_required |= elink_fan_failure_det_req(sc,
16678                                                      sc->devinfo.shmem_base,
16679                                                      sc->devinfo.shmem2_base,
16680                                                      port);
16681         }
16682     }
16683 
16684     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16685 
16686     if (is_required == 0) {
16687         return;
16688     }
16689 
16690     /* Fan failure is indicated by SPIO 5 */
16691     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16692 
16693     /* set to active low mode */
16694     val = REG_RD(sc, MISC_REG_SPIO_INT);
16695     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16696     REG_WR(sc, MISC_REG_SPIO_INT, val);
16697 
16698     /* enable interrupt to signal the IGU */
16699     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16700     val |= MISC_SPIO_SPIO5;
16701     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16702 }
16703 
16704 static void
16705 bxe_enable_blocks_attention(struct bxe_softc *sc)
16706 {
16707     uint32_t val;
16708 
16709     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16710     if (!CHIP_IS_E1x(sc)) {
16711         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16712     } else {
16713         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16714     }
16715     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16716     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16717     /*
16718      * mask read length error interrupts in brb for parser
16719      * (parsing unit and 'checksum and crc' unit)
16720      * these errors are legal (PU reads fixed length and CAC can cause
16721      * read length error on truncated packets)
16722      */
16723     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16724     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16725     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16726     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16727     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16728     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16729 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16730 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16731     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16732     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16733     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16734 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16735 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16736     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16737     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16738     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16739     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16740 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16741 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16742 
16743     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16744            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16745            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16746     if (!CHIP_IS_E1x(sc)) {
16747         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16748                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16749     }
16750     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16751 
16752     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16753     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16754     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16755 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16756 
16757     if (!CHIP_IS_E1x(sc)) {
16758         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16759         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16760     }
16761 
16762     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16763     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16764 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16765     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16766 }
16767 
16768 /**
16769  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16770  *
16771  * @sc:     driver handle
16772  */
16773 static int
16774 bxe_init_hw_common(struct bxe_softc *sc)
16775 {
16776     uint8_t abs_func_id;
16777     uint32_t val;
16778 
16779     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16780           SC_ABS_FUNC(sc));
16781 
16782     /*
16783      * take the RESET lock to protect undi_unload flow from accessing
16784      * registers while we are resetting the chip
16785      */
16786     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16787 
16788     bxe_reset_common(sc);
16789 
16790     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16791 
16792     val = 0xfffc;
16793     if (CHIP_IS_E3(sc)) {
16794         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16795         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16796     }
16797 
16798     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16799 
16800     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16801 
16802     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16803     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16804 
16805     if (!CHIP_IS_E1x(sc)) {
16806         /*
16807          * 4-port mode or 2-port mode we need to turn off master-enable for
16808          * everyone. After that we turn it back on for self. So, we disregard
16809          * multi-function, and always disable all functions on the given path,
16810          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16811          */
16812         for (abs_func_id = SC_PATH(sc);
16813              abs_func_id < (E2_FUNC_MAX * 2);
16814              abs_func_id += 2) {
16815             if (abs_func_id == SC_ABS_FUNC(sc)) {
16816                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16817                 continue;
16818             }
16819 
16820             bxe_pretend_func(sc, abs_func_id);
16821 
16822             /* clear pf enable */
16823             bxe_pf_disable(sc);
16824 
16825             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16826         }
16827     }
16828 
16829     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16830 
16831     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16832 
16833     if (CHIP_IS_E1(sc)) {
16834         /*
16835          * enable HW interrupt from PXP on USDM overflow
16836          * bit 16 on INT_MASK_0
16837          */
16838         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16839     }
16840 
16841     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16842     bxe_init_pxp(sc);
16843 
16844 #ifdef __BIG_ENDIAN
16845     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16846     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16847     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16848     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16849     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16850     /* make sure this value is 0 */
16851     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16852 
16853     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16854     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16855     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16856     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16857     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16858 #endif
16859 
16860     ecore_ilt_init_page_size(sc, INITOP_SET);
16861 
16862     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16863         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16864     }
16865 
16866     /* let the HW do it's magic... */
16867     DELAY(100000);
16868 
16869     /* finish PXP init */
16870     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16871     if (val != 1) {
16872         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16873             val);
16874         return (-1);
16875     }
16876     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16877     if (val != 1) {
16878         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16879         return (-1);
16880     }
16881 
16882     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16883 
16884     /*
16885      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16886      * entries with value "0" and valid bit on. This needs to be done by the
16887      * first PF that is loaded in a path (i.e. common phase)
16888      */
16889     if (!CHIP_IS_E1x(sc)) {
16890 /*
16891  * In E2 there is a bug in the timers block that can cause function 6 / 7
16892  * (i.e. vnic3) to start even if it is marked as "scan-off".
16893  * This occurs when a different function (func2,3) is being marked
16894  * as "scan-off". Real-life scenario for example: if a driver is being
16895  * load-unloaded while func6,7 are down. This will cause the timer to access
16896  * the ilt, translate to a logical address and send a request to read/write.
16897  * Since the ilt for the function that is down is not valid, this will cause
16898  * a translation error which is unrecoverable.
16899  * The Workaround is intended to make sure that when this happens nothing
16900  * fatal will occur. The workaround:
16901  *  1.  First PF driver which loads on a path will:
16902  *      a.  After taking the chip out of reset, by using pretend,
16903  *          it will write "0" to the following registers of
16904  *          the other vnics.
16905  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16906  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16907  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16908  *          And for itself it will write '1' to
16909  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16910  *          dmae-operations (writing to pram for example.)
16911  *          note: can be done for only function 6,7 but cleaner this
16912  *            way.
16913  *      b.  Write zero+valid to the entire ILT.
16914  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16915  *          VNIC3 (of that port). The range allocated will be the
16916  *          entire ILT. This is needed to prevent  ILT range error.
16917  *  2.  Any PF driver load flow:
16918  *      a.  ILT update with the physical addresses of the allocated
16919  *          logical pages.
16920  *      b.  Wait 20msec. - note that this timeout is needed to make
16921  *          sure there are no requests in one of the PXP internal
16922  *          queues with "old" ILT addresses.
16923  *      c.  PF enable in the PGLC.
16924  *      d.  Clear the was_error of the PF in the PGLC. (could have
16925  *          occurred while driver was down)
16926  *      e.  PF enable in the CFC (WEAK + STRONG)
16927  *      f.  Timers scan enable
16928  *  3.  PF driver unload flow:
16929  *      a.  Clear the Timers scan_en.
16930  *      b.  Polling for scan_on=0 for that PF.
16931  *      c.  Clear the PF enable bit in the PXP.
16932  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16933  *      e.  Write zero+valid to all ILT entries (The valid bit must
16934  *          stay set)
16935  *      f.  If this is VNIC 3 of a port then also init
16936  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16937  *          to the last enrty in the ILT.
16938  *
16939  *      Notes:
16940  *      Currently the PF error in the PGLC is non recoverable.
16941  *      In the future the there will be a recovery routine for this error.
16942  *      Currently attention is masked.
16943  *      Having an MCP lock on the load/unload process does not guarantee that
16944  *      there is no Timer disable during Func6/7 enable. This is because the
16945  *      Timers scan is currently being cleared by the MCP on FLR.
16946  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16947  *      there is error before clearing it. But the flow above is simpler and
16948  *      more general.
16949  *      All ILT entries are written by zero+valid and not just PF6/7
16950  *      ILT entries since in the future the ILT entries allocation for
16951  *      PF-s might be dynamic.
16952  */
16953         struct ilt_client_info ilt_cli;
16954         struct ecore_ilt ilt;
16955 
16956         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16957         memset(&ilt, 0, sizeof(struct ecore_ilt));
16958 
16959         /* initialize dummy TM client */
16960         ilt_cli.start      = 0;
16961         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16962         ilt_cli.client_num = ILT_CLIENT_TM;
16963 
16964         /*
16965          * Step 1: set zeroes to all ilt page entries with valid bit on
16966          * Step 2: set the timers first/last ilt entry to point
16967          * to the entire range to prevent ILT range error for 3rd/4th
16968          * vnic (this code assumes existence of the vnic)
16969          *
16970          * both steps performed by call to ecore_ilt_client_init_op()
16971          * with dummy TM client
16972          *
16973          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16974          * and his brother are split registers
16975          */
16976 
16977         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16978         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16979         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16980 
16981         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16982         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16983         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16984     }
16985 
16986     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16987     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16988 
16989     if (!CHIP_IS_E1x(sc)) {
16990         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16991                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16992 
16993         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16994         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16995 
16996         /* let the HW do it's magic... */
16997         do {
16998             DELAY(200000);
16999             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17000         } while (factor-- && (val != 1));
17001 
17002         if (val != 1) {
17003             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17004             return (-1);
17005         }
17006     }
17007 
17008     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17009 
17010     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17011 
17012     bxe_iov_init_dmae(sc);
17013 
17014     /* clean the DMAE memory */
17015     sc->dmae_ready = 1;
17016     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17017 
17018     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17019 
17020     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17021 
17022     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17023 
17024     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17025 
17026     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17027     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17028     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17029     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17030 
17031     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17032 
17033     /* QM queues pointers table */
17034     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17035 
17036     /* soft reset pulse */
17037     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17038     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17039 
17040     if (CNIC_SUPPORT(sc))
17041         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17042 
17043     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17044     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17045     if (!CHIP_REV_IS_SLOW(sc)) {
17046         /* enable hw interrupt from doorbell Q */
17047         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17048     }
17049 
17050     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17051 
17052     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17053     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17054 
17055     if (!CHIP_IS_E1(sc)) {
17056         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17057     }
17058 
17059     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17060         if (IS_MF_AFEX(sc)) {
17061             /*
17062              * configure that AFEX and VLAN headers must be
17063              * received in AFEX mode
17064              */
17065             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17066             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17067             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17068             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17069             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17070         } else {
17071             /*
17072              * Bit-map indicating which L2 hdrs may appear
17073              * after the basic Ethernet header
17074              */
17075             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17076                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17077         }
17078     }
17079 
17080     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17081     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17082     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17083     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17084 
17085     if (!CHIP_IS_E1x(sc)) {
17086         /* reset VFC memories */
17087         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17088                VFC_MEMORIES_RST_REG_CAM_RST |
17089                VFC_MEMORIES_RST_REG_RAM_RST);
17090         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17091                VFC_MEMORIES_RST_REG_CAM_RST |
17092                VFC_MEMORIES_RST_REG_RAM_RST);
17093 
17094         DELAY(20000);
17095     }
17096 
17097     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17098     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17099     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17100     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17101 
17102     /* sync semi rtc */
17103     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17104            0x80000000);
17105     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17106            0x80000000);
17107 
17108     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17109     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17110     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17111 
17112     if (!CHIP_IS_E1x(sc)) {
17113         if (IS_MF_AFEX(sc)) {
17114             /*
17115              * configure that AFEX and VLAN headers must be
17116              * sent in AFEX mode
17117              */
17118             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17119             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17120             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17121             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17122             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17123         } else {
17124             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17125                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17126         }
17127     }
17128 
17129     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17130 
17131     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17132 
17133     if (CNIC_SUPPORT(sc)) {
17134         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17135         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17136         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17137         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17138         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17139         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17140         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17141         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17142         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17143         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17144     }
17145     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17146 
17147     if (sizeof(union cdu_context) != 1024) {
17148         /* we currently assume that a context is 1024 bytes */
17149         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17150               (long)sizeof(union cdu_context));
17151     }
17152 
17153     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17154     val = (4 << 24) + (0 << 12) + 1024;
17155     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17156 
17157     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17158 
17159     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17160     /* enable context validation interrupt from CFC */
17161     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17162 
17163     /* set the thresholds to prevent CFC/CDU race */
17164     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17165     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17166 
17167     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17168         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17169     }
17170 
17171     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17172     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17173 
17174     /* Reset PCIE errors for debug */
17175     REG_WR(sc, 0x2814, 0xffffffff);
17176     REG_WR(sc, 0x3820, 0xffffffff);
17177 
17178     if (!CHIP_IS_E1x(sc)) {
17179         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17180                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17181                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17182         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17183                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17184                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17185                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17186         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17187                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17188                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17189                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17190     }
17191 
17192     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17193 
17194     if (!CHIP_IS_E1(sc)) {
17195         /* in E3 this done in per-port section */
17196         if (!CHIP_IS_E3(sc))
17197             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17198     }
17199 
17200     if (CHIP_IS_E1H(sc)) {
17201         /* not applicable for E2 (and above ...) */
17202         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17203     }
17204 
17205     if (CHIP_REV_IS_SLOW(sc)) {
17206         DELAY(200000);
17207     }
17208 
17209     /* finish CFC init */
17210     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17211     if (val != 1) {
17212         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17213         return (-1);
17214     }
17215     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17216     if (val != 1) {
17217         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17218         return (-1);
17219     }
17220     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17221     if (val != 1) {
17222         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17223         return (-1);
17224     }
17225     REG_WR(sc, CFC_REG_DEBUG0, 0);
17226 
17227     if (CHIP_IS_E1(sc)) {
17228         /* read NIG statistic to see if this is our first up since powerup */
17229         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17230         val = *BXE_SP(sc, wb_data[0]);
17231 
17232         /* do internal memory self test */
17233         if ((val == 0) && bxe_int_mem_test(sc)) {
17234             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17235             return (-1);
17236         }
17237     }
17238 
17239     bxe_setup_fan_failure_detection(sc);
17240 
17241     /* clear PXP2 attentions */
17242     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17243 
17244     bxe_enable_blocks_attention(sc);
17245 
17246     if (!CHIP_REV_IS_SLOW(sc)) {
17247         ecore_enable_blocks_parity(sc);
17248     }
17249 
17250     if (!BXE_NOMCP(sc)) {
17251         if (CHIP_IS_E1x(sc)) {
17252             bxe_common_init_phy(sc);
17253         }
17254     }
17255 
17256     return (0);
17257 }
17258 
17259 /**
17260  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17261  *
17262  * @sc:     driver handle
17263  */
17264 static int
17265 bxe_init_hw_common_chip(struct bxe_softc *sc)
17266 {
17267     int rc = bxe_init_hw_common(sc);
17268 
17269     if (rc) {
17270         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17271         return (rc);
17272     }
17273 
17274     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17275     if (!BXE_NOMCP(sc)) {
17276         bxe_common_init_phy(sc);
17277     }
17278 
17279     return (0);
17280 }
17281 
17282 static int
17283 bxe_init_hw_port(struct bxe_softc *sc)
17284 {
17285     int port = SC_PORT(sc);
17286     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17287     uint32_t low, high;
17288     uint32_t val;
17289 
17290     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17291 
17292     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17293 
17294     ecore_init_block(sc, BLOCK_MISC, init_phase);
17295     ecore_init_block(sc, BLOCK_PXP, init_phase);
17296     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17297 
17298     /*
17299      * Timers bug workaround: disables the pf_master bit in pglue at
17300      * common phase, we need to enable it here before any dmae access are
17301      * attempted. Therefore we manually added the enable-master to the
17302      * port phase (it also happens in the function phase)
17303      */
17304     if (!CHIP_IS_E1x(sc)) {
17305         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17306     }
17307 
17308     ecore_init_block(sc, BLOCK_ATC, init_phase);
17309     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17310     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17311     ecore_init_block(sc, BLOCK_QM, init_phase);
17312 
17313     ecore_init_block(sc, BLOCK_TCM, init_phase);
17314     ecore_init_block(sc, BLOCK_UCM, init_phase);
17315     ecore_init_block(sc, BLOCK_CCM, init_phase);
17316     ecore_init_block(sc, BLOCK_XCM, init_phase);
17317 
17318     /* QM cid (connection) count */
17319     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17320 
17321     if (CNIC_SUPPORT(sc)) {
17322         ecore_init_block(sc, BLOCK_TM, init_phase);
17323         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17324         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17325     }
17326 
17327     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17328 
17329     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17330 
17331     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17332         if (IS_MF(sc)) {
17333             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17334         } else if (sc->mtu > 4096) {
17335             if (BXE_ONE_PORT(sc)) {
17336                 low = 160;
17337             } else {
17338                 val = sc->mtu;
17339                 /* (24*1024 + val*4)/256 */
17340                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17341             }
17342         } else {
17343             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17344         }
17345         high = (low + 56); /* 14*1024/256 */
17346         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17347         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17348     }
17349 
17350     if (CHIP_IS_MODE_4_PORT(sc)) {
17351         REG_WR(sc, SC_PORT(sc) ?
17352                BRB1_REG_MAC_GUARANTIED_1 :
17353                BRB1_REG_MAC_GUARANTIED_0, 40);
17354     }
17355 
17356     ecore_init_block(sc, BLOCK_PRS, init_phase);
17357     if (CHIP_IS_E3B0(sc)) {
17358         if (IS_MF_AFEX(sc)) {
17359             /* configure headers for AFEX mode */
17360             REG_WR(sc, SC_PORT(sc) ?
17361                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17362                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17363             REG_WR(sc, SC_PORT(sc) ?
17364                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17365                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17366             REG_WR(sc, SC_PORT(sc) ?
17367                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17368                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17369         } else {
17370             /* Ovlan exists only if we are in multi-function +
17371              * switch-dependent mode, in switch-independent there
17372              * is no ovlan headers
17373              */
17374             REG_WR(sc, SC_PORT(sc) ?
17375                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17376                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17377                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17378         }
17379     }
17380 
17381     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17382     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17383     ecore_init_block(sc, BLOCK_USDM, init_phase);
17384     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17385 
17386     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17387     ecore_init_block(sc, BLOCK_USEM, init_phase);
17388     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17389     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17390 
17391     ecore_init_block(sc, BLOCK_UPB, init_phase);
17392     ecore_init_block(sc, BLOCK_XPB, init_phase);
17393 
17394     ecore_init_block(sc, BLOCK_PBF, init_phase);
17395 
17396     if (CHIP_IS_E1x(sc)) {
17397         /* configure PBF to work without PAUSE mtu 9000 */
17398         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17399 
17400         /* update threshold */
17401         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17402         /* update init credit */
17403         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17404 
17405         /* probe changes */
17406         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17407         DELAY(50);
17408         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17409     }
17410 
17411     if (CNIC_SUPPORT(sc)) {
17412         ecore_init_block(sc, BLOCK_SRC, init_phase);
17413     }
17414 
17415     ecore_init_block(sc, BLOCK_CDU, init_phase);
17416     ecore_init_block(sc, BLOCK_CFC, init_phase);
17417 
17418     if (CHIP_IS_E1(sc)) {
17419         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17420         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17421     }
17422     ecore_init_block(sc, BLOCK_HC, init_phase);
17423 
17424     ecore_init_block(sc, BLOCK_IGU, init_phase);
17425 
17426     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17427     /* init aeu_mask_attn_func_0/1:
17428      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17429      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17430      *             bits 4-7 are used for "per vn group attention" */
17431     val = IS_MF(sc) ? 0xF7 : 0x7;
17432     /* Enable DCBX attention for all but E1 */
17433     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17434     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17435 
17436     ecore_init_block(sc, BLOCK_NIG, init_phase);
17437 
17438     if (!CHIP_IS_E1x(sc)) {
17439         /* Bit-map indicating which L2 hdrs may appear after the
17440          * basic Ethernet header
17441          */
17442         if (IS_MF_AFEX(sc)) {
17443             REG_WR(sc, SC_PORT(sc) ?
17444                    NIG_REG_P1_HDRS_AFTER_BASIC :
17445                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17446         } else {
17447             REG_WR(sc, SC_PORT(sc) ?
17448                    NIG_REG_P1_HDRS_AFTER_BASIC :
17449                    NIG_REG_P0_HDRS_AFTER_BASIC,
17450                    IS_MF_SD(sc) ? 7 : 6);
17451         }
17452 
17453         if (CHIP_IS_E3(sc)) {
17454             REG_WR(sc, SC_PORT(sc) ?
17455                    NIG_REG_LLH1_MF_MODE :
17456                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17457         }
17458     }
17459     if (!CHIP_IS_E3(sc)) {
17460         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17461     }
17462 
17463     if (!CHIP_IS_E1(sc)) {
17464         /* 0x2 disable mf_ov, 0x1 enable */
17465         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17466                (IS_MF_SD(sc) ? 0x1 : 0x2));
17467 
17468         if (!CHIP_IS_E1x(sc)) {
17469             val = 0;
17470             switch (sc->devinfo.mf_info.mf_mode) {
17471             case MULTI_FUNCTION_SD:
17472                 val = 1;
17473                 break;
17474             case MULTI_FUNCTION_SI:
17475             case MULTI_FUNCTION_AFEX:
17476                 val = 2;
17477                 break;
17478             }
17479 
17480             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17481                         NIG_REG_LLH0_CLS_TYPE), val);
17482         }
17483         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17484         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17485         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17486     }
17487 
17488     /* If SPIO5 is set to generate interrupts, enable it for this port */
17489     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17490     if (val & MISC_SPIO_SPIO5) {
17491         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17492                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17493         val = REG_RD(sc, reg_addr);
17494         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17495         REG_WR(sc, reg_addr, val);
17496     }
17497 
17498     return (0);
17499 }
17500 
17501 static uint32_t
17502 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17503                        uint32_t         reg,
17504                        uint32_t         expected,
17505                        uint32_t         poll_count)
17506 {
17507     uint32_t cur_cnt = poll_count;
17508     uint32_t val;
17509 
17510     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17511         DELAY(FLR_WAIT_INTERVAL);
17512     }
17513 
17514     return (val);
17515 }
17516 
17517 static int
17518 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17519                               uint32_t         reg,
17520                               char             *msg,
17521                               uint32_t         poll_cnt)
17522 {
17523     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17524 
17525     if (val != 0) {
17526         BLOGE(sc, "%s usage count=%d\n", msg, val);
17527         return (1);
17528     }
17529 
17530     return (0);
17531 }
17532 
17533 /* Common routines with VF FLR cleanup */
17534 static uint32_t
17535 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17536 {
17537     /* adjust polling timeout */
17538     if (CHIP_REV_IS_EMUL(sc)) {
17539         return (FLR_POLL_CNT * 2000);
17540     }
17541 
17542     if (CHIP_REV_IS_FPGA(sc)) {
17543         return (FLR_POLL_CNT * 120);
17544     }
17545 
17546     return (FLR_POLL_CNT);
17547 }
17548 
17549 static int
17550 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17551                            uint32_t         poll_cnt)
17552 {
17553     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17554     if (bxe_flr_clnup_poll_hw_counter(sc,
17555                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17556                                       "CFC PF usage counter timed out",
17557                                       poll_cnt)) {
17558         return (1);
17559     }
17560 
17561     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17562     if (bxe_flr_clnup_poll_hw_counter(sc,
17563                                       DORQ_REG_PF_USAGE_CNT,
17564                                       "DQ PF usage counter timed out",
17565                                       poll_cnt)) {
17566         return (1);
17567     }
17568 
17569     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17570     if (bxe_flr_clnup_poll_hw_counter(sc,
17571                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17572                                       "QM PF usage counter timed out",
17573                                       poll_cnt)) {
17574         return (1);
17575     }
17576 
17577     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17578     if (bxe_flr_clnup_poll_hw_counter(sc,
17579                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17580                                       "Timers VNIC usage counter timed out",
17581                                       poll_cnt)) {
17582         return (1);
17583     }
17584 
17585     if (bxe_flr_clnup_poll_hw_counter(sc,
17586                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17587                                       "Timers NUM_SCANS usage counter timed out",
17588                                       poll_cnt)) {
17589         return (1);
17590     }
17591 
17592     /* Wait DMAE PF usage counter to zero */
17593     if (bxe_flr_clnup_poll_hw_counter(sc,
17594                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17595                                       "DMAE dommand register timed out",
17596                                       poll_cnt)) {
17597         return (1);
17598     }
17599 
17600     return (0);
17601 }
17602 
17603 #define OP_GEN_PARAM(param)                                            \
17604     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17605 #define OP_GEN_TYPE(type)                                           \
17606     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17607 #define OP_GEN_AGG_VECT(index)                                             \
17608     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17609 
17610 static int
17611 bxe_send_final_clnup(struct bxe_softc *sc,
17612                      uint8_t          clnup_func,
17613                      uint32_t         poll_cnt)
17614 {
17615     uint32_t op_gen_command = 0;
17616     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17617                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17618     int ret = 0;
17619 
17620     if (REG_RD(sc, comp_addr)) {
17621         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17622         return (1);
17623     }
17624 
17625     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17626     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17627     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17628     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17629 
17630     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17631     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17632 
17633     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17634         BLOGE(sc, "FW final cleanup did not succeed\n");
17635         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17636               (REG_RD(sc, comp_addr)));
17637         bxe_panic(sc, ("FLR cleanup failed\n"));
17638         return (1);
17639     }
17640 
17641     /* Zero completion for nxt FLR */
17642     REG_WR(sc, comp_addr, 0);
17643 
17644     return (ret);
17645 }
17646 
17647 static void
17648 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17649                        struct pbf_pN_buf_regs *regs,
17650                        uint32_t               poll_count)
17651 {
17652     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17653     uint32_t cur_cnt = poll_count;
17654 
17655     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17656     crd = crd_start = REG_RD(sc, regs->crd);
17657     init_crd = REG_RD(sc, regs->init_crd);
17658 
17659     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17660     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17661     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17662 
17663     while ((crd != init_crd) &&
17664            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17665             (init_crd - crd_start))) {
17666         if (cur_cnt--) {
17667             DELAY(FLR_WAIT_INTERVAL);
17668             crd = REG_RD(sc, regs->crd);
17669             crd_freed = REG_RD(sc, regs->crd_freed);
17670         } else {
17671             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17672             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17673             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17674             break;
17675         }
17676     }
17677 
17678     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17679           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17680 }
17681 
17682 static void
17683 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17684                        struct pbf_pN_cmd_regs *regs,
17685                        uint32_t               poll_count)
17686 {
17687     uint32_t occup, to_free, freed, freed_start;
17688     uint32_t cur_cnt = poll_count;
17689 
17690     occup = to_free = REG_RD(sc, regs->lines_occup);
17691     freed = freed_start = REG_RD(sc, regs->lines_freed);
17692 
17693     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17694     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17695 
17696     while (occup &&
17697            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17698         if (cur_cnt--) {
17699             DELAY(FLR_WAIT_INTERVAL);
17700             occup = REG_RD(sc, regs->lines_occup);
17701             freed = REG_RD(sc, regs->lines_freed);
17702         } else {
17703             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17704             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17705             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17706             break;
17707         }
17708     }
17709 
17710     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17711           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17712 }
17713 
17714 static void
17715 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17716 {
17717     struct pbf_pN_cmd_regs cmd_regs[] = {
17718         {0, (CHIP_IS_E3B0(sc)) ?
17719             PBF_REG_TQ_OCCUPANCY_Q0 :
17720             PBF_REG_P0_TQ_OCCUPANCY,
17721             (CHIP_IS_E3B0(sc)) ?
17722             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17723             PBF_REG_P0_TQ_LINES_FREED_CNT},
17724         {1, (CHIP_IS_E3B0(sc)) ?
17725             PBF_REG_TQ_OCCUPANCY_Q1 :
17726             PBF_REG_P1_TQ_OCCUPANCY,
17727             (CHIP_IS_E3B0(sc)) ?
17728             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17729             PBF_REG_P1_TQ_LINES_FREED_CNT},
17730         {4, (CHIP_IS_E3B0(sc)) ?
17731             PBF_REG_TQ_OCCUPANCY_LB_Q :
17732             PBF_REG_P4_TQ_OCCUPANCY,
17733             (CHIP_IS_E3B0(sc)) ?
17734             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17735             PBF_REG_P4_TQ_LINES_FREED_CNT}
17736     };
17737 
17738     struct pbf_pN_buf_regs buf_regs[] = {
17739         {0, (CHIP_IS_E3B0(sc)) ?
17740             PBF_REG_INIT_CRD_Q0 :
17741             PBF_REG_P0_INIT_CRD ,
17742             (CHIP_IS_E3B0(sc)) ?
17743             PBF_REG_CREDIT_Q0 :
17744             PBF_REG_P0_CREDIT,
17745             (CHIP_IS_E3B0(sc)) ?
17746             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17747             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17748         {1, (CHIP_IS_E3B0(sc)) ?
17749             PBF_REG_INIT_CRD_Q1 :
17750             PBF_REG_P1_INIT_CRD,
17751             (CHIP_IS_E3B0(sc)) ?
17752             PBF_REG_CREDIT_Q1 :
17753             PBF_REG_P1_CREDIT,
17754             (CHIP_IS_E3B0(sc)) ?
17755             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17756             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17757         {4, (CHIP_IS_E3B0(sc)) ?
17758             PBF_REG_INIT_CRD_LB_Q :
17759             PBF_REG_P4_INIT_CRD,
17760             (CHIP_IS_E3B0(sc)) ?
17761             PBF_REG_CREDIT_LB_Q :
17762             PBF_REG_P4_CREDIT,
17763             (CHIP_IS_E3B0(sc)) ?
17764             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17765             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17766     };
17767 
17768     int i;
17769 
17770     /* Verify the command queues are flushed P0, P1, P4 */
17771     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17772         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17773     }
17774 
17775     /* Verify the transmission buffers are flushed P0, P1, P4 */
17776     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17777         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17778     }
17779 }
17780 
17781 static void
17782 bxe_hw_enable_status(struct bxe_softc *sc)
17783 {
17784     uint32_t val;
17785 
17786     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17787     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17788 
17789     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17790     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17791 
17792     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17793     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17794 
17795     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17796     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17797 
17798     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17799     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17800 
17801     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17802     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17803 
17804     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17805     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17806 
17807     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17808     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17809 }
17810 
17811 static int
17812 bxe_pf_flr_clnup(struct bxe_softc *sc)
17813 {
17814     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17815 
17816     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17817 
17818     /* Re-enable PF target read access */
17819     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17820 
17821     /* Poll HW usage counters */
17822     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17823     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17824         return (-1);
17825     }
17826 
17827     /* Zero the igu 'trailing edge' and 'leading edge' */
17828 
17829     /* Send the FW cleanup command */
17830     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17831         return (-1);
17832     }
17833 
17834     /* ATC cleanup */
17835 
17836     /* Verify TX hw is flushed */
17837     bxe_tx_hw_flushed(sc, poll_cnt);
17838 
17839     /* Wait 100ms (not adjusted according to platform) */
17840     DELAY(100000);
17841 
17842     /* Verify no pending pci transactions */
17843     if (bxe_is_pcie_pending(sc)) {
17844         BLOGE(sc, "PCIE Transactions still pending\n");
17845     }
17846 
17847     /* Debug */
17848     bxe_hw_enable_status(sc);
17849 
17850     /*
17851      * Master enable - Due to WB DMAE writes performed before this
17852      * register is re-initialized as part of the regular function init
17853      */
17854     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17855 
17856     return (0);
17857 }
17858 
17859 static int
17860 bxe_init_hw_func(struct bxe_softc *sc)
17861 {
17862     int port = SC_PORT(sc);
17863     int func = SC_FUNC(sc);
17864     int init_phase = PHASE_PF0 + func;
17865     struct ecore_ilt *ilt = sc->ilt;
17866     uint16_t cdu_ilt_start;
17867     uint32_t addr, val;
17868     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17869     int i, main_mem_width, rc;
17870 
17871     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17872 
17873     /* FLR cleanup */
17874     if (!CHIP_IS_E1x(sc)) {
17875         rc = bxe_pf_flr_clnup(sc);
17876         if (rc) {
17877             BLOGE(sc, "FLR cleanup failed!\n");
17878             // XXX bxe_fw_dump(sc);
17879             // XXX bxe_idle_chk(sc);
17880             return (rc);
17881         }
17882     }
17883 
17884     /* set MSI reconfigure capability */
17885     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17886         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17887         val = REG_RD(sc, addr);
17888         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17889         REG_WR(sc, addr, val);
17890     }
17891 
17892     ecore_init_block(sc, BLOCK_PXP, init_phase);
17893     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17894 
17895     ilt = sc->ilt;
17896     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17897 
17898     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17899         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17900         ilt->lines[cdu_ilt_start + i].page_mapping =
17901             sc->context[i].vcxt_dma.paddr;
17902         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17903     }
17904     ecore_ilt_init_op(sc, INITOP_SET);
17905 
17906     /* Set NIC mode */
17907     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17908     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17909 
17910     if (!CHIP_IS_E1x(sc)) {
17911         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17912 
17913         /* Turn on a single ISR mode in IGU if driver is going to use
17914          * INT#x or MSI
17915          */
17916         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17917             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17918         }
17919 
17920         /*
17921          * Timers workaround bug: function init part.
17922          * Need to wait 20msec after initializing ILT,
17923          * needed to make sure there are no requests in
17924          * one of the PXP internal queues with "old" ILT addresses
17925          */
17926         DELAY(20000);
17927 
17928         /*
17929          * Master enable - Due to WB DMAE writes performed before this
17930          * register is re-initialized as part of the regular function
17931          * init
17932          */
17933         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17934         /* Enable the function in IGU */
17935         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17936     }
17937 
17938     sc->dmae_ready = 1;
17939 
17940     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17941 
17942     if (!CHIP_IS_E1x(sc))
17943         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17944 
17945     ecore_init_block(sc, BLOCK_ATC, init_phase);
17946     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17947     ecore_init_block(sc, BLOCK_NIG, init_phase);
17948     ecore_init_block(sc, BLOCK_SRC, init_phase);
17949     ecore_init_block(sc, BLOCK_MISC, init_phase);
17950     ecore_init_block(sc, BLOCK_TCM, init_phase);
17951     ecore_init_block(sc, BLOCK_UCM, init_phase);
17952     ecore_init_block(sc, BLOCK_CCM, init_phase);
17953     ecore_init_block(sc, BLOCK_XCM, init_phase);
17954     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17955     ecore_init_block(sc, BLOCK_USEM, init_phase);
17956     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17957     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17958 
17959     if (!CHIP_IS_E1x(sc))
17960         REG_WR(sc, QM_REG_PF_EN, 1);
17961 
17962     if (!CHIP_IS_E1x(sc)) {
17963         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17964         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17965         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17966         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17967     }
17968     ecore_init_block(sc, BLOCK_QM, init_phase);
17969 
17970     ecore_init_block(sc, BLOCK_TM, init_phase);
17971     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17972 
17973     bxe_iov_init_dq(sc);
17974 
17975     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17976     ecore_init_block(sc, BLOCK_PRS, init_phase);
17977     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17978     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17979     ecore_init_block(sc, BLOCK_USDM, init_phase);
17980     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17981     ecore_init_block(sc, BLOCK_UPB, init_phase);
17982     ecore_init_block(sc, BLOCK_XPB, init_phase);
17983     ecore_init_block(sc, BLOCK_PBF, init_phase);
17984     if (!CHIP_IS_E1x(sc))
17985         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17986 
17987     ecore_init_block(sc, BLOCK_CDU, init_phase);
17988 
17989     ecore_init_block(sc, BLOCK_CFC, init_phase);
17990 
17991     if (!CHIP_IS_E1x(sc))
17992         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17993 
17994     if (IS_MF(sc)) {
17995         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17996         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17997     }
17998 
17999     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18000 
18001     /* HC init per function */
18002     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18003         if (CHIP_IS_E1H(sc)) {
18004             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18005 
18006             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18007             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18008         }
18009         ecore_init_block(sc, BLOCK_HC, init_phase);
18010 
18011     } else {
18012         int num_segs, sb_idx, prod_offset;
18013 
18014         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18015 
18016         if (!CHIP_IS_E1x(sc)) {
18017             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18018             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18019         }
18020 
18021         ecore_init_block(sc, BLOCK_IGU, init_phase);
18022 
18023         if (!CHIP_IS_E1x(sc)) {
18024             int dsb_idx = 0;
18025             /**
18026              * Producer memory:
18027              * E2 mode: address 0-135 match to the mapping memory;
18028              * 136 - PF0 default prod; 137 - PF1 default prod;
18029              * 138 - PF2 default prod; 139 - PF3 default prod;
18030              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18031              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18032              * 144-147 reserved.
18033              *
18034              * E1.5 mode - In backward compatible mode;
18035              * for non default SB; each even line in the memory
18036              * holds the U producer and each odd line hold
18037              * the C producer. The first 128 producers are for
18038              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18039              * producers are for the DSB for each PF.
18040              * Each PF has five segments: (the order inside each
18041              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18042              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18043              * 144-147 attn prods;
18044              */
18045             /* non-default-status-blocks */
18046             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18047                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18048             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18049                 prod_offset = (sc->igu_base_sb + sb_idx) *
18050                     num_segs;
18051 
18052                 for (i = 0; i < num_segs; i++) {
18053                     addr = IGU_REG_PROD_CONS_MEMORY +
18054                             (prod_offset + i) * 4;
18055                     REG_WR(sc, addr, 0);
18056                 }
18057                 /* send consumer update with value 0 */
18058                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18059                            USTORM_ID, 0, IGU_INT_NOP, 1);
18060                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18061             }
18062 
18063             /* default-status-blocks */
18064             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18065                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18066 
18067             if (CHIP_IS_MODE_4_PORT(sc))
18068                 dsb_idx = SC_FUNC(sc);
18069             else
18070                 dsb_idx = SC_VN(sc);
18071 
18072             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18073                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18074                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18075 
18076             /*
18077              * igu prods come in chunks of E1HVN_MAX (4) -
18078              * does not matters what is the current chip mode
18079              */
18080             for (i = 0; i < (num_segs * E1HVN_MAX);
18081                  i += E1HVN_MAX) {
18082                 addr = IGU_REG_PROD_CONS_MEMORY +
18083                             (prod_offset + i)*4;
18084                 REG_WR(sc, addr, 0);
18085             }
18086             /* send consumer update with 0 */
18087             if (CHIP_INT_MODE_IS_BC(sc)) {
18088                 bxe_ack_sb(sc, sc->igu_dsb_id,
18089                            USTORM_ID, 0, IGU_INT_NOP, 1);
18090                 bxe_ack_sb(sc, sc->igu_dsb_id,
18091                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18092                 bxe_ack_sb(sc, sc->igu_dsb_id,
18093                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18094                 bxe_ack_sb(sc, sc->igu_dsb_id,
18095                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18096                 bxe_ack_sb(sc, sc->igu_dsb_id,
18097                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18098             } else {
18099                 bxe_ack_sb(sc, sc->igu_dsb_id,
18100                            USTORM_ID, 0, IGU_INT_NOP, 1);
18101                 bxe_ack_sb(sc, sc->igu_dsb_id,
18102                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18103             }
18104             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18105 
18106             /* !!! these should become driver const once
18107                rf-tool supports split-68 const */
18108             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18109             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18110             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18111             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18112             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18113             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18114         }
18115     }
18116 
18117     /* Reset PCIE errors for debug */
18118     REG_WR(sc, 0x2114, 0xffffffff);
18119     REG_WR(sc, 0x2120, 0xffffffff);
18120 
18121     if (CHIP_IS_E1x(sc)) {
18122         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18123         main_mem_base = HC_REG_MAIN_MEMORY +
18124                 SC_PORT(sc) * (main_mem_size * 4);
18125         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18126         main_mem_width = 8;
18127 
18128         val = REG_RD(sc, main_mem_prty_clr);
18129         if (val) {
18130             BLOGD(sc, DBG_LOAD,
18131                   "Parity errors in HC block during function init (0x%x)!\n",
18132                   val);
18133         }
18134 
18135         /* Clear "false" parity errors in MSI-X table */
18136         for (i = main_mem_base;
18137              i < main_mem_base + main_mem_size * 4;
18138              i += main_mem_width) {
18139             bxe_read_dmae(sc, i, main_mem_width / 4);
18140             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18141                            i, main_mem_width / 4);
18142         }
18143         /* Clear HC parity attention */
18144         REG_RD(sc, main_mem_prty_clr);
18145     }
18146 
18147 #if 1
18148     /* Enable STORMs SP logging */
18149     REG_WR8(sc, BAR_USTRORM_INTMEM +
18150            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18151     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18152            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18153     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18154            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18155     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18156            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18157 #endif
18158 
18159     elink_phy_probe(&sc->link_params);
18160 
18161     return (0);
18162 }
18163 
18164 static void
18165 bxe_link_reset(struct bxe_softc *sc)
18166 {
18167     if (!BXE_NOMCP(sc)) {
18168 	bxe_acquire_phy_lock(sc);
18169         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18170 	bxe_release_phy_lock(sc);
18171     } else {
18172         if (!CHIP_REV_IS_SLOW(sc)) {
18173             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18174         }
18175     }
18176 }
18177 
18178 static void
18179 bxe_reset_port(struct bxe_softc *sc)
18180 {
18181     int port = SC_PORT(sc);
18182     uint32_t val;
18183 
18184 	ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18185     /* reset physical Link */
18186     bxe_link_reset(sc);
18187 
18188     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18189 
18190     /* Do not rcv packets to BRB */
18191     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18192     /* Do not direct rcv packets that are not for MCP to the BRB */
18193     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18194                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18195 
18196     /* Configure AEU */
18197     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18198 
18199     DELAY(100000);
18200 
18201     /* Check for BRB port occupancy */
18202     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18203     if (val) {
18204         BLOGD(sc, DBG_LOAD,
18205               "BRB1 is not empty, %d blocks are occupied\n", val);
18206     }
18207 
18208     /* TODO: Close Doorbell port? */
18209 }
18210 
18211 static void
18212 bxe_ilt_wr(struct bxe_softc *sc,
18213            uint32_t         index,
18214            bus_addr_t       addr)
18215 {
18216     int reg;
18217     uint32_t wb_write[2];
18218 
18219     if (CHIP_IS_E1(sc)) {
18220         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18221     } else {
18222         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18223     }
18224 
18225     wb_write[0] = ONCHIP_ADDR1(addr);
18226     wb_write[1] = ONCHIP_ADDR2(addr);
18227     REG_WR_DMAE(sc, reg, wb_write, 2);
18228 }
18229 
18230 static void
18231 bxe_clear_func_ilt(struct bxe_softc *sc,
18232                    uint32_t         func)
18233 {
18234     uint32_t i, base = FUNC_ILT_BASE(func);
18235     for (i = base; i < base + ILT_PER_FUNC; i++) {
18236         bxe_ilt_wr(sc, i, 0);
18237     }
18238 }
18239 
18240 static void
18241 bxe_reset_func(struct bxe_softc *sc)
18242 {
18243     struct bxe_fastpath *fp;
18244     int port = SC_PORT(sc);
18245     int func = SC_FUNC(sc);
18246     int i;
18247 
18248     /* Disable the function in the FW */
18249     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18250     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18251     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18252     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18253 
18254     /* FP SBs */
18255     FOR_EACH_ETH_QUEUE(sc, i) {
18256         fp = &sc->fp[i];
18257         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18258                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18259                 SB_DISABLED);
18260     }
18261 
18262     /* SP SB */
18263     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18264             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18265             SB_DISABLED);
18266 
18267     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18268         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18269     }
18270 
18271     /* Configure IGU */
18272     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18273         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18274         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18275     } else {
18276         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18277         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18278     }
18279 
18280     if (CNIC_LOADED(sc)) {
18281         /* Disable Timer scan */
18282         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18283         /*
18284          * Wait for at least 10ms and up to 2 second for the timers
18285          * scan to complete
18286          */
18287         for (i = 0; i < 200; i++) {
18288             DELAY(10000);
18289             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18290                 break;
18291         }
18292     }
18293 
18294     /* Clear ILT */
18295     bxe_clear_func_ilt(sc, func);
18296 
18297     /*
18298      * Timers workaround bug for E2: if this is vnic-3,
18299      * we need to set the entire ilt range for this timers.
18300      */
18301     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18302         struct ilt_client_info ilt_cli;
18303         /* use dummy TM client */
18304         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18305         ilt_cli.start = 0;
18306         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18307         ilt_cli.client_num = ILT_CLIENT_TM;
18308 
18309         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18310     }
18311 
18312     /* this assumes that reset_port() called before reset_func()*/
18313     if (!CHIP_IS_E1x(sc)) {
18314         bxe_pf_disable(sc);
18315     }
18316 
18317     sc->dmae_ready = 0;
18318 }
18319 
18320 static int
18321 bxe_gunzip_init(struct bxe_softc *sc)
18322 {
18323     return (0);
18324 }
18325 
18326 static void
18327 bxe_gunzip_end(struct bxe_softc *sc)
18328 {
18329     return;
18330 }
18331 
18332 static int
18333 bxe_init_firmware(struct bxe_softc *sc)
18334 {
18335     if (CHIP_IS_E1(sc)) {
18336         ecore_init_e1_firmware(sc);
18337         sc->iro_array = e1_iro_arr;
18338     } else if (CHIP_IS_E1H(sc)) {
18339         ecore_init_e1h_firmware(sc);
18340         sc->iro_array = e1h_iro_arr;
18341     } else if (!CHIP_IS_E1x(sc)) {
18342         ecore_init_e2_firmware(sc);
18343         sc->iro_array = e2_iro_arr;
18344     } else {
18345         BLOGE(sc, "Unsupported chip revision\n");
18346         return (-1);
18347     }
18348 
18349     return (0);
18350 }
18351 
18352 static void
18353 bxe_release_firmware(struct bxe_softc *sc)
18354 {
18355     /* Do nothing */
18356     return;
18357 }
18358 
18359 static int
18360 ecore_gunzip(struct bxe_softc *sc,
18361              const uint8_t    *zbuf,
18362              int              len)
18363 {
18364     /* XXX : Implement... */
18365     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18366     return (FALSE);
18367 }
18368 
18369 static void
18370 ecore_reg_wr_ind(struct bxe_softc *sc,
18371                  uint32_t         addr,
18372                  uint32_t         val)
18373 {
18374     bxe_reg_wr_ind(sc, addr, val);
18375 }
18376 
18377 static void
18378 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18379                           bus_addr_t       phys_addr,
18380                           uint32_t         addr,
18381                           uint32_t         len)
18382 {
18383     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18384 }
18385 
18386 void
18387 ecore_storm_memset_struct(struct bxe_softc *sc,
18388                           uint32_t         addr,
18389                           size_t           size,
18390                           uint32_t         *data)
18391 {
18392     uint8_t i;
18393     for (i = 0; i < size/4; i++) {
18394         REG_WR(sc, addr + (i * 4), data[i]);
18395     }
18396 }
18397 
18398 
18399 /*
18400  * character device - ioctl interface definitions
18401  */
18402 
18403 
18404 #include "bxe_dump.h"
18405 #include "bxe_ioctl.h"
18406 #include <sys/conf.h>
18407 
18408 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18409                 struct thread *td);
18410 
18411 static struct cdevsw bxe_cdevsw = {
18412     .d_version = D_VERSION,
18413     .d_ioctl = bxe_eioctl,
18414     .d_name = "bxecnic",
18415 };
18416 
18417 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18418 
18419 
18420 #define DUMP_ALL_PRESETS        0x1FFF
18421 #define DUMP_MAX_PRESETS        13
18422 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18423 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18424 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18425 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18426 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18427 
18428 #define IS_REG_IN_PRESET(presets, idx)  \
18429                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18430 
18431 
18432 static int
18433 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18434 {
18435     if (CHIP_IS_E1(sc))
18436         return dump_num_registers[0][preset-1];
18437     else if (CHIP_IS_E1H(sc))
18438         return dump_num_registers[1][preset-1];
18439     else if (CHIP_IS_E2(sc))
18440         return dump_num_registers[2][preset-1];
18441     else if (CHIP_IS_E3A0(sc))
18442         return dump_num_registers[3][preset-1];
18443     else if (CHIP_IS_E3B0(sc))
18444         return dump_num_registers[4][preset-1];
18445     else
18446         return 0;
18447 }
18448 
18449 static int
18450 bxe_get_total_regs_len32(struct bxe_softc *sc)
18451 {
18452     uint32_t preset_idx;
18453     int regdump_len32 = 0;
18454 
18455 
18456     /* Calculate the total preset regs length */
18457     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18458         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18459     }
18460 
18461     return regdump_len32;
18462 }
18463 
18464 static const uint32_t *
18465 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18466 {
18467     if (CHIP_IS_E2(sc))
18468         return page_vals_e2;
18469     else if (CHIP_IS_E3(sc))
18470         return page_vals_e3;
18471     else
18472         return NULL;
18473 }
18474 
18475 static uint32_t
18476 __bxe_get_page_reg_num(struct bxe_softc *sc)
18477 {
18478     if (CHIP_IS_E2(sc))
18479         return PAGE_MODE_VALUES_E2;
18480     else if (CHIP_IS_E3(sc))
18481         return PAGE_MODE_VALUES_E3;
18482     else
18483         return 0;
18484 }
18485 
18486 static const uint32_t *
18487 __bxe_get_page_write_ar(struct bxe_softc *sc)
18488 {
18489     if (CHIP_IS_E2(sc))
18490         return page_write_regs_e2;
18491     else if (CHIP_IS_E3(sc))
18492         return page_write_regs_e3;
18493     else
18494         return NULL;
18495 }
18496 
18497 static uint32_t
18498 __bxe_get_page_write_num(struct bxe_softc *sc)
18499 {
18500     if (CHIP_IS_E2(sc))
18501         return PAGE_WRITE_REGS_E2;
18502     else if (CHIP_IS_E3(sc))
18503         return PAGE_WRITE_REGS_E3;
18504     else
18505         return 0;
18506 }
18507 
18508 static const struct reg_addr *
18509 __bxe_get_page_read_ar(struct bxe_softc *sc)
18510 {
18511     if (CHIP_IS_E2(sc))
18512         return page_read_regs_e2;
18513     else if (CHIP_IS_E3(sc))
18514         return page_read_regs_e3;
18515     else
18516         return NULL;
18517 }
18518 
18519 static uint32_t
18520 __bxe_get_page_read_num(struct bxe_softc *sc)
18521 {
18522     if (CHIP_IS_E2(sc))
18523         return PAGE_READ_REGS_E2;
18524     else if (CHIP_IS_E3(sc))
18525         return PAGE_READ_REGS_E3;
18526     else
18527         return 0;
18528 }
18529 
18530 static bool
18531 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18532 {
18533     if (CHIP_IS_E1(sc))
18534         return IS_E1_REG(reg_info->chips);
18535     else if (CHIP_IS_E1H(sc))
18536         return IS_E1H_REG(reg_info->chips);
18537     else if (CHIP_IS_E2(sc))
18538         return IS_E2_REG(reg_info->chips);
18539     else if (CHIP_IS_E3A0(sc))
18540         return IS_E3A0_REG(reg_info->chips);
18541     else if (CHIP_IS_E3B0(sc))
18542         return IS_E3B0_REG(reg_info->chips);
18543     else
18544         return 0;
18545 }
18546 
18547 static bool
18548 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18549 {
18550     if (CHIP_IS_E1(sc))
18551         return IS_E1_REG(wreg_info->chips);
18552     else if (CHIP_IS_E1H(sc))
18553         return IS_E1H_REG(wreg_info->chips);
18554     else if (CHIP_IS_E2(sc))
18555         return IS_E2_REG(wreg_info->chips);
18556     else if (CHIP_IS_E3A0(sc))
18557         return IS_E3A0_REG(wreg_info->chips);
18558     else if (CHIP_IS_E3B0(sc))
18559         return IS_E3B0_REG(wreg_info->chips);
18560     else
18561         return 0;
18562 }
18563 
18564 /**
18565  * bxe_read_pages_regs - read "paged" registers
18566  *
18567  * @bp          device handle
18568  * @p           output buffer
18569  *
18570  * Reads "paged" memories: memories that may only be read by first writing to a
18571  * specific address ("write address") and then reading from a specific address
18572  * ("read address"). There may be more than one write address per "page" and
18573  * more than one read address per write address.
18574  */
18575 static void
18576 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18577 {
18578     uint32_t i, j, k, n;
18579 
18580     /* addresses of the paged registers */
18581     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18582     /* number of paged registers */
18583     int num_pages = __bxe_get_page_reg_num(sc);
18584     /* write addresses */
18585     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18586     /* number of write addresses */
18587     int write_num = __bxe_get_page_write_num(sc);
18588     /* read addresses info */
18589     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18590     /* number of read addresses */
18591     int read_num = __bxe_get_page_read_num(sc);
18592     uint32_t addr, size;
18593 
18594     for (i = 0; i < num_pages; i++) {
18595         for (j = 0; j < write_num; j++) {
18596             REG_WR(sc, write_addr[j], page_addr[i]);
18597 
18598             for (k = 0; k < read_num; k++) {
18599                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18600                     size = read_addr[k].size;
18601                     for (n = 0; n < size; n++) {
18602                         addr = read_addr[k].addr + n*4;
18603                         *p++ = REG_RD(sc, addr);
18604                     }
18605                 }
18606             }
18607         }
18608     }
18609     return;
18610 }
18611 
18612 
18613 static int
18614 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18615 {
18616     uint32_t i, j, addr;
18617     const struct wreg_addr *wreg_addr_p = NULL;
18618 
18619     if (CHIP_IS_E1(sc))
18620         wreg_addr_p = &wreg_addr_e1;
18621     else if (CHIP_IS_E1H(sc))
18622         wreg_addr_p = &wreg_addr_e1h;
18623     else if (CHIP_IS_E2(sc))
18624         wreg_addr_p = &wreg_addr_e2;
18625     else if (CHIP_IS_E3A0(sc))
18626         wreg_addr_p = &wreg_addr_e3;
18627     else if (CHIP_IS_E3B0(sc))
18628         wreg_addr_p = &wreg_addr_e3b0;
18629     else
18630         return (-1);
18631 
18632     /* Read the idle_chk registers */
18633     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18634         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18635             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18636             for (j = 0; j < idle_reg_addrs[i].size; j++)
18637                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18638         }
18639     }
18640 
18641     /* Read the regular registers */
18642     for (i = 0; i < REGS_COUNT; i++) {
18643         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18644             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18645             for (j = 0; j < reg_addrs[i].size; j++)
18646                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18647         }
18648     }
18649 
18650     /* Read the CAM registers */
18651     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18652         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18653         for (i = 0; i < wreg_addr_p->size; i++) {
18654             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18655 
18656             /* In case of wreg_addr register, read additional
18657                registers from read_regs array
18658              */
18659             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18660                 addr = *(wreg_addr_p->read_regs);
18661                 *p++ = REG_RD(sc, addr + j*4);
18662             }
18663         }
18664     }
18665 
18666     /* Paged registers are supported in E2 & E3 only */
18667     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18668         /* Read "paged" registers */
18669         bxe_read_pages_regs(sc, p, preset);
18670     }
18671 
18672     return 0;
18673 }
18674 
18675 int
18676 bxe_grc_dump(struct bxe_softc *sc)
18677 {
18678     int rval = 0;
18679     uint32_t preset_idx;
18680     uint8_t *buf;
18681     uint32_t size;
18682     struct  dump_header *d_hdr;
18683     uint32_t i;
18684     uint32_t reg_val;
18685     uint32_t reg_addr;
18686     uint32_t cmd_offset;
18687     struct ecore_ilt *ilt = SC_ILT(sc);
18688     struct bxe_fastpath *fp;
18689     struct ilt_client_info *ilt_cli;
18690     int grc_dump_size;
18691 
18692 
18693     if (sc->grcdump_done || sc->grcdump_started)
18694 	return (rval);
18695 
18696     sc->grcdump_started = 1;
18697     BLOGI(sc, "Started collecting grcdump\n");
18698 
18699     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18700                 sizeof(struct  dump_header);
18701 
18702     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18703 
18704     if (sc->grc_dump == NULL) {
18705         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18706         return(ENOMEM);
18707     }
18708 
18709 
18710 
18711     /* Disable parity attentions as long as following dump may
18712      * cause false alarms by reading never written registers. We
18713      * will re-enable parity attentions right after the dump.
18714      */
18715 
18716     /* Disable parity on path 0 */
18717     bxe_pretend_func(sc, 0);
18718 
18719     ecore_disable_blocks_parity(sc);
18720 
18721     /* Disable parity on path 1 */
18722     bxe_pretend_func(sc, 1);
18723     ecore_disable_blocks_parity(sc);
18724 
18725     /* Return to current function */
18726     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18727 
18728     buf = sc->grc_dump;
18729     d_hdr = sc->grc_dump;
18730 
18731     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18732     d_hdr->version = BNX2X_DUMP_VERSION;
18733     d_hdr->preset = DUMP_ALL_PRESETS;
18734 
18735     if (CHIP_IS_E1(sc)) {
18736         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18737     } else if (CHIP_IS_E1H(sc)) {
18738         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18739     } else if (CHIP_IS_E2(sc)) {
18740         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18741                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18742     } else if (CHIP_IS_E3A0(sc)) {
18743         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18744                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18745     } else if (CHIP_IS_E3B0(sc)) {
18746         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18747                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18748     }
18749 
18750     buf += sizeof(struct  dump_header);
18751 
18752     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18753 
18754         /* Skip presets with IOR */
18755         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18756             (preset_idx == 11))
18757             continue;
18758 
18759         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18760 
18761 	if (rval)
18762             break;
18763 
18764         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18765 
18766         buf += size;
18767     }
18768 
18769     bxe_pretend_func(sc, 0);
18770     ecore_clear_blocks_parity(sc);
18771     ecore_enable_blocks_parity(sc);
18772 
18773     bxe_pretend_func(sc, 1);
18774     ecore_clear_blocks_parity(sc);
18775     ecore_enable_blocks_parity(sc);
18776 
18777     /* Return to current function */
18778     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18779 
18780 
18781 
18782     if(sc->state == BXE_STATE_OPEN) {
18783         if(sc->fw_stats_req  != NULL) {
18784     		BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18785         			(uintmax_t)sc->fw_stats_req_mapping,
18786         			(uintmax_t)sc->fw_stats_data_mapping,
18787         			sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18788 		}
18789 		if(sc->def_sb != NULL) {
18790 			BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18791         			(void *)sc->def_sb_dma.paddr, sc->def_sb,
18792         			sizeof(struct host_sp_status_block));
18793 		}
18794 		if(sc->eq_dma.vaddr != NULL) {
18795     		BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18796         			(uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18797 		}
18798 		if(sc->sp_dma.vaddr != NULL) {
18799     		BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18800         			(uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18801         			sizeof(struct bxe_slowpath));
18802 		}
18803 		if(sc->spq_dma.vaddr != NULL) {
18804     		BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18805         			(uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18806 		}
18807 		if(sc->gz_buf_dma.vaddr != NULL) {
18808     		BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18809         			(uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18810         			FW_BUF_SIZE);
18811 		}
18812     	for (i = 0; i < sc->num_queues; i++) {
18813         	fp = &sc->fp[i];
18814 			if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
18815                         fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
18816                         fp->rx_sge_dma.vaddr != NULL) {
18817 
18818 				BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18819             			(uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18820             			sizeof(union bxe_host_hc_status_block));
18821 				BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18822             			(uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18823             			(BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18824         		BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18825             			(uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18826             			(BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18827         		BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18828             			(uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18829             			(BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18830         		BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18831             			(uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18832             			(BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18833     		}
18834 		}
18835 		if(ilt != NULL ) {
18836     		ilt_cli = &ilt->clients[1];
18837 			if(ilt->lines != NULL) {
18838     		for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18839         		BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18840             			(uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18841             			((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18842     		}
18843 			}
18844 		}
18845 
18846 
18847     	cmd_offset = DMAE_REG_CMD_MEM;
18848     	for (i = 0; i < 224; i++) {
18849         	reg_addr = (cmd_offset +(i * 4));
18850         	reg_val = REG_RD(sc, reg_addr);
18851         	BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18852             			reg_addr, reg_val);
18853     	}
18854 	}
18855 
18856     BLOGI(sc, "Collection of grcdump done\n");
18857     sc->grcdump_done = 1;
18858     return(rval);
18859 }
18860 
18861 static int
18862 bxe_add_cdev(struct bxe_softc *sc)
18863 {
18864     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18865 
18866     if (sc->eeprom == NULL) {
18867         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18868         return (-1);
18869     }
18870 
18871     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18872                             sc->ifp->if_dunit,
18873                             UID_ROOT,
18874                             GID_WHEEL,
18875                             0600,
18876                             "%s",
18877                             if_name(sc->ifp));
18878 
18879     if (sc->ioctl_dev == NULL) {
18880         free(sc->eeprom, M_DEVBUF);
18881         sc->eeprom = NULL;
18882         return (-1);
18883     }
18884 
18885     sc->ioctl_dev->si_drv1 = sc;
18886 
18887     return (0);
18888 }
18889 
18890 static void
18891 bxe_del_cdev(struct bxe_softc *sc)
18892 {
18893     if (sc->ioctl_dev != NULL)
18894         destroy_dev(sc->ioctl_dev);
18895 
18896     if (sc->eeprom != NULL) {
18897         free(sc->eeprom, M_DEVBUF);
18898         sc->eeprom = NULL;
18899     }
18900     sc->ioctl_dev = NULL;
18901 
18902     return;
18903 }
18904 
18905 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18906 {
18907 
18908     if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
18909         return FALSE;
18910 
18911     return TRUE;
18912 }
18913 
18914 
18915 static int
18916 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18917 {
18918     int rval = 0;
18919 
18920     if(!bxe_is_nvram_accessible(sc)) {
18921         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18922         return (-EAGAIN);
18923     }
18924     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18925 
18926 
18927    return (rval);
18928 }
18929 
18930 static int
18931 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18932 {
18933     int rval = 0;
18934 
18935     if(!bxe_is_nvram_accessible(sc)) {
18936         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18937         return (-EAGAIN);
18938     }
18939     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18940 
18941    return (rval);
18942 }
18943 
18944 static int
18945 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18946 {
18947     int rval = 0;
18948 
18949     switch (eeprom->eeprom_cmd) {
18950 
18951     case BXE_EEPROM_CMD_SET_EEPROM:
18952 
18953         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18954                        eeprom->eeprom_data_len);
18955 
18956         if (rval)
18957             break;
18958 
18959         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18960                        eeprom->eeprom_data_len);
18961         break;
18962 
18963     case BXE_EEPROM_CMD_GET_EEPROM:
18964 
18965         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18966                        eeprom->eeprom_data_len);
18967 
18968         if (rval) {
18969             break;
18970         }
18971 
18972         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18973                        eeprom->eeprom_data_len);
18974         break;
18975 
18976     default:
18977             rval = EINVAL;
18978             break;
18979     }
18980 
18981     if (rval) {
18982         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18983     }
18984 
18985     return (rval);
18986 }
18987 
18988 static int
18989 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18990 {
18991     uint32_t ext_phy_config;
18992     int port = SC_PORT(sc);
18993     int cfg_idx = bxe_get_link_cfg_idx(sc);
18994 
18995     dev_p->supported = sc->port.supported[cfg_idx] |
18996             (sc->port.supported[cfg_idx ^ 1] &
18997             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18998     dev_p->advertising = sc->port.advertising[cfg_idx];
18999     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
19000         ELINK_ETH_PHY_SFP_1G_FIBER) {
19001         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
19002         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
19003     }
19004     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
19005         !(sc->flags & BXE_MF_FUNC_DIS)) {
19006         dev_p->duplex = sc->link_vars.duplex;
19007         if (IS_MF(sc) && !BXE_NOMCP(sc))
19008             dev_p->speed = bxe_get_mf_speed(sc);
19009         else
19010             dev_p->speed = sc->link_vars.line_speed;
19011     } else {
19012         dev_p->duplex = DUPLEX_UNKNOWN;
19013         dev_p->speed = SPEED_UNKNOWN;
19014     }
19015 
19016     dev_p->port = bxe_media_detect(sc);
19017 
19018     ext_phy_config = SHMEM_RD(sc,
19019                          dev_info.port_hw_config[port].external_phy_config);
19020     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19021         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19022         dev_p->phy_address =  sc->port.phy_addr;
19023     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19024             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19025         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19026             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19027         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19028     else
19029         dev_p->phy_address = 0;
19030 
19031     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19032         dev_p->autoneg = AUTONEG_ENABLE;
19033     else
19034        dev_p->autoneg = AUTONEG_DISABLE;
19035 
19036 
19037     return 0;
19038 }
19039 
19040 static int
19041 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19042         struct thread *td)
19043 {
19044     struct bxe_softc    *sc;
19045     int                 rval = 0;
19046     device_t            pci_dev;
19047     bxe_grcdump_t       *dump = NULL;
19048     int grc_dump_size;
19049     bxe_drvinfo_t   *drv_infop = NULL;
19050     bxe_dev_setting_t  *dev_p;
19051     bxe_dev_setting_t  dev_set;
19052     bxe_get_regs_t  *reg_p;
19053     bxe_reg_rdw_t *reg_rdw_p;
19054     bxe_pcicfg_rdw_t *cfg_rdw_p;
19055     bxe_perm_mac_addr_t *mac_addr_p;
19056 
19057 
19058     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19059         return ENXIO;
19060 
19061     pci_dev= sc->dev;
19062 
19063     dump = (bxe_grcdump_t *)data;
19064 
19065     switch(cmd) {
19066 
19067         case BXE_GRC_DUMP_SIZE:
19068             dump->pci_func = sc->pcie_func;
19069             dump->grcdump_size =
19070                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19071                      sizeof(struct  dump_header);
19072             break;
19073 
19074         case BXE_GRC_DUMP:
19075 
19076             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19077                                 sizeof(struct  dump_header);
19078             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19079                 (dump->grcdump_size < grc_dump_size)) {
19080                 rval = EINVAL;
19081                 break;
19082             }
19083 
19084             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19085                 (!sc->grcdump_started)) {
19086                 rval =  bxe_grc_dump(sc);
19087             }
19088 
19089             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19090                 (sc->grc_dump != NULL))  {
19091                 dump->grcdump_dwords = grc_dump_size >> 2;
19092                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19093                 free(sc->grc_dump, M_DEVBUF);
19094                 sc->grc_dump = NULL;
19095                 sc->grcdump_started = 0;
19096                 sc->grcdump_done = 0;
19097             }
19098 
19099             break;
19100 
19101         case BXE_DRV_INFO:
19102             drv_infop = (bxe_drvinfo_t *)data;
19103             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19104             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19105                 BXE_DRIVER_VERSION);
19106             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19107                 sc->devinfo.bc_ver_str);
19108             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19109                 "%s", sc->fw_ver_str);
19110             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19111             drv_infop->reg_dump_len =
19112                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19113                     + sizeof(struct  dump_header);
19114             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19115                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19116             break;
19117 
19118         case BXE_DEV_SETTING:
19119             dev_p = (bxe_dev_setting_t *)data;
19120             bxe_get_settings(sc, &dev_set);
19121             dev_p->supported = dev_set.supported;
19122             dev_p->advertising = dev_set.advertising;
19123             dev_p->speed = dev_set.speed;
19124             dev_p->duplex = dev_set.duplex;
19125             dev_p->port = dev_set.port;
19126             dev_p->phy_address = dev_set.phy_address;
19127             dev_p->autoneg = dev_set.autoneg;
19128 
19129             break;
19130 
19131         case BXE_GET_REGS:
19132 
19133             reg_p = (bxe_get_regs_t *)data;
19134             grc_dump_size = reg_p->reg_buf_len;
19135 
19136             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19137                 bxe_grc_dump(sc);
19138             }
19139             if((sc->grcdump_done) && (sc->grcdump_started) &&
19140                 (sc->grc_dump != NULL))  {
19141                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19142                 free(sc->grc_dump, M_DEVBUF);
19143                 sc->grc_dump = NULL;
19144                 sc->grcdump_started = 0;
19145                 sc->grcdump_done = 0;
19146             }
19147 
19148             break;
19149 
19150         case BXE_RDW_REG:
19151             reg_rdw_p = (bxe_reg_rdw_t *)data;
19152             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19153                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19154                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19155 
19156             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19157                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19158                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19159 
19160             break;
19161 
19162         case BXE_RDW_PCICFG:
19163             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19164             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19165 
19166                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19167                                          cfg_rdw_p->cfg_width);
19168 
19169             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19170                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19171                             cfg_rdw_p->cfg_width);
19172             } else {
19173                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19174             }
19175             break;
19176 
19177         case BXE_MAC_ADDR:
19178             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19179             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19180                 sc->mac_addr_str);
19181             break;
19182 
19183         case BXE_EEPROM:
19184             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19185             break;
19186 
19187 
19188         default:
19189             break;
19190     }
19191 
19192     return (rval);
19193 }
19194 
19195 #ifdef NETDUMP
19196 static void
19197 bxe_netdump_init(struct ifnet *ifp, int *nrxr, int *ncl, int *clsize)
19198 {
19199 	struct bxe_softc *sc;
19200 
19201 	sc = if_getsoftc(ifp);
19202 	BXE_CORE_LOCK(sc);
19203 	*nrxr = sc->num_queues;
19204 	*ncl = NETDUMP_MAX_IN_FLIGHT;
19205 	*clsize = sc->fp[0].mbuf_alloc_size;
19206 	BXE_CORE_UNLOCK(sc);
19207 }
19208 
19209 static void
19210 bxe_netdump_event(struct ifnet *ifp __unused, enum netdump_ev event __unused)
19211 {
19212 }
19213 
19214 static int
19215 bxe_netdump_transmit(struct ifnet *ifp, struct mbuf *m)
19216 {
19217 	struct bxe_softc *sc;
19218 	int error;
19219 
19220 	sc = if_getsoftc(ifp);
19221 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
19222 	    IFF_DRV_RUNNING || !sc->link_vars.link_up)
19223 		return (ENOENT);
19224 
19225 	error = bxe_tx_encap(&sc->fp[0], &m);
19226 	if (error != 0 && m != NULL)
19227 		m_freem(m);
19228 	return (error);
19229 }
19230 
19231 static int
19232 bxe_netdump_poll(struct ifnet *ifp, int count)
19233 {
19234 	struct bxe_softc *sc;
19235 	int i;
19236 
19237 	sc = if_getsoftc(ifp);
19238 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 ||
19239 	    !sc->link_vars.link_up)
19240 		return (ENOENT);
19241 
19242 	for (i = 0; i < sc->num_queues; i++)
19243 		(void)bxe_rxeof(sc, &sc->fp[i]);
19244 	(void)bxe_txeof(sc, &sc->fp[0]);
19245 	return (0);
19246 }
19247 #endif /* NETDUMP */
19248