xref: /freebsd/sys/dev/bxe/bxe.c (revision f0cfa1b168014f56c02b83e5f28412cc5f78d117)
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.90"
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 /* resources needed for unloading a previously loaded device */
240 
241 #define BXE_PREV_WAIT_NEEDED 1
242 struct mtx bxe_prev_mtx;
243 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
244 struct bxe_prev_list_node {
245     LIST_ENTRY(bxe_prev_list_node) node;
246     uint8_t bus;
247     uint8_t slot;
248     uint8_t path;
249     uint8_t aer; /* XXX automatic error recovery */
250     uint8_t undi;
251 };
252 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
253 
254 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
255 
256 /* Tunable device values... */
257 
258 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
259 
260 /* Debug */
261 unsigned long bxe_debug = 0;
262 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
263              &bxe_debug, 0, "Debug logging mode");
264 
265 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
266 static int bxe_interrupt_mode = INTR_MODE_MSIX;
267 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
268            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
269 
270 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
271 static int bxe_queue_count = 4;
272 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
273            &bxe_queue_count, 0, "Multi-Queue queue count");
274 
275 /* max number of buffers per queue (default RX_BD_USABLE) */
276 static int bxe_max_rx_bufs = 0;
277 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
278            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
279 
280 /* Host interrupt coalescing RX tick timer (usecs) */
281 static int bxe_hc_rx_ticks = 25;
282 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
283            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
284 
285 /* Host interrupt coalescing TX tick timer (usecs) */
286 static int bxe_hc_tx_ticks = 50;
287 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
288            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
289 
290 /* Maximum number of Rx packets to process at a time */
291 static int bxe_rx_budget = 0xffffffff;
292 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
293            &bxe_rx_budget, 0, "Rx processing budget");
294 
295 /* Maximum LRO aggregation size */
296 static int bxe_max_aggregation_size = 0;
297 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
298            &bxe_max_aggregation_size, 0, "max aggregation size");
299 
300 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
301 static int bxe_mrrs = -1;
302 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
303            &bxe_mrrs, 0, "PCIe maximum read request size");
304 
305 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
306 static int bxe_autogreeen = 0;
307 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
308            &bxe_autogreeen, 0, "AutoGrEEEn support");
309 
310 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
311 static int bxe_udp_rss = 0;
312 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
313            &bxe_udp_rss, 0, "UDP RSS support");
314 
315 
316 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
317 
318 #define STATS_OFFSET32(stat_name)                   \
319     (offsetof(struct bxe_eth_stats, stat_name) / 4)
320 
321 #define Q_STATS_OFFSET32(stat_name)                   \
322     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
323 
324 static const struct {
325     uint32_t offset;
326     uint32_t size;
327     uint32_t flags;
328 #define STATS_FLAGS_PORT  1
329 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
330 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
331     char string[STAT_NAME_LEN];
332 } bxe_eth_stats_arr[] = {
333     { STATS_OFFSET32(total_bytes_received_hi),
334                 8, STATS_FLAGS_BOTH, "rx_bytes" },
335     { STATS_OFFSET32(error_bytes_received_hi),
336                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
337     { STATS_OFFSET32(total_unicast_packets_received_hi),
338                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
339     { STATS_OFFSET32(total_multicast_packets_received_hi),
340                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
341     { STATS_OFFSET32(total_broadcast_packets_received_hi),
342                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
343     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
344                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
345     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
346                 8, STATS_FLAGS_PORT, "rx_align_errors" },
347     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
348                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
349     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
350                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
351     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
352                 8, STATS_FLAGS_PORT, "rx_fragments" },
353     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
354                 8, STATS_FLAGS_PORT, "rx_jabbers" },
355     { STATS_OFFSET32(no_buff_discard_hi),
356                 8, STATS_FLAGS_BOTH, "rx_discards" },
357     { STATS_OFFSET32(mac_filter_discard),
358                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
359     { STATS_OFFSET32(mf_tag_discard),
360                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
361     { STATS_OFFSET32(pfc_frames_received_hi),
362                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
363     { STATS_OFFSET32(pfc_frames_sent_hi),
364                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
365     { STATS_OFFSET32(brb_drop_hi),
366                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
367     { STATS_OFFSET32(brb_truncate_hi),
368                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
369     { STATS_OFFSET32(pause_frames_received_hi),
370                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
371     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
372                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
373     { STATS_OFFSET32(nig_timer_max),
374                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
375     { STATS_OFFSET32(total_bytes_transmitted_hi),
376                 8, STATS_FLAGS_BOTH, "tx_bytes" },
377     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
378                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
379     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
380                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
381     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
382                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
383     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
384                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
385     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
386                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
387     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
388                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
389     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
390                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
391     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
392                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
393     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
394                 8, STATS_FLAGS_PORT, "tx_deferred" },
395     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
396                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
397     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
398                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
399     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
400                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
401     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
402                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
403     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
404                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
405     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
406                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
407     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
408                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
409     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
410                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
411     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
412                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
413     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
414                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
415     { STATS_OFFSET32(pause_frames_sent_hi),
416                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
417     { STATS_OFFSET32(total_tpa_aggregations_hi),
418                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
419     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
420                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
421     { STATS_OFFSET32(total_tpa_bytes_hi),
422                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
423     { STATS_OFFSET32(eee_tx_lpi),
424                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
425     { STATS_OFFSET32(rx_calls),
426                 4, STATS_FLAGS_FUNC, "rx_calls"},
427     { STATS_OFFSET32(rx_pkts),
428                 4, STATS_FLAGS_FUNC, "rx_pkts"},
429     { STATS_OFFSET32(rx_tpa_pkts),
430                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
431     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
432                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
433     { STATS_OFFSET32(rx_bxe_service_rxsgl),
434                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
435     { STATS_OFFSET32(rx_jumbo_sge_pkts),
436                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
437     { STATS_OFFSET32(rx_soft_errors),
438                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
439     { STATS_OFFSET32(rx_hw_csum_errors),
440                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
441     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
442                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
443     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
444                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
445     { STATS_OFFSET32(rx_budget_reached),
446                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
447     { STATS_OFFSET32(tx_pkts),
448                 4, STATS_FLAGS_FUNC, "tx_pkts"},
449     { STATS_OFFSET32(tx_soft_errors),
450                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
451     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
452                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
453     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
454                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
455     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
456                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
457     { STATS_OFFSET32(tx_ofld_frames_lso),
458                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
459     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
460                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
461     { STATS_OFFSET32(tx_encap_failures),
462                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
463     { STATS_OFFSET32(tx_hw_queue_full),
464                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
465     { STATS_OFFSET32(tx_hw_max_queue_depth),
466                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
467     { STATS_OFFSET32(tx_dma_mapping_failure),
468                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
469     { STATS_OFFSET32(tx_max_drbr_queue_depth),
470                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
471     { STATS_OFFSET32(tx_window_violation_std),
472                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
473     { STATS_OFFSET32(tx_window_violation_tso),
474                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
475     { STATS_OFFSET32(tx_chain_lost_mbuf),
476                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
477     { STATS_OFFSET32(tx_frames_deferred),
478                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
479     { STATS_OFFSET32(tx_queue_xoff),
480                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
481     { STATS_OFFSET32(mbuf_defrag_attempts),
482                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
483     { STATS_OFFSET32(mbuf_defrag_failures),
484                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
485     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
486                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
487     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
488                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
489     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
490                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
491     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
492                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
493     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
494                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
495     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
496                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
497     { STATS_OFFSET32(mbuf_alloc_tx),
498                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
499     { STATS_OFFSET32(mbuf_alloc_rx),
500                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
501     { STATS_OFFSET32(mbuf_alloc_sge),
502                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
503     { STATS_OFFSET32(mbuf_alloc_tpa),
504                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
505     { STATS_OFFSET32(tx_queue_full_return),
506                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
507     { STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
508                 4, STATS_FLAGS_FUNC, "bxe_tx_mq_sc_state_failures"},
509     { STATS_OFFSET32(tx_request_link_down_failures),
510                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
511     { STATS_OFFSET32(bd_avail_too_less_failures),
512                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
513     { STATS_OFFSET32(tx_mq_not_empty),
514                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"},
515     { STATS_OFFSET32(nsegs_path1_errors),
516                 4, STATS_FLAGS_FUNC, "nsegs_path1_errors"},
517     { STATS_OFFSET32(nsegs_path2_errors),
518                 4, STATS_FLAGS_FUNC, "nsegs_path2_errors"}
519 
520 
521 };
522 
523 static const struct {
524     uint32_t offset;
525     uint32_t size;
526     char string[STAT_NAME_LEN];
527 } bxe_eth_q_stats_arr[] = {
528     { Q_STATS_OFFSET32(total_bytes_received_hi),
529                 8, "rx_bytes" },
530     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
531                 8, "rx_ucast_packets" },
532     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
533                 8, "rx_mcast_packets" },
534     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
535                 8, "rx_bcast_packets" },
536     { Q_STATS_OFFSET32(no_buff_discard_hi),
537                 8, "rx_discards" },
538     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
539                 8, "tx_bytes" },
540     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
541                 8, "tx_ucast_packets" },
542     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
543                 8, "tx_mcast_packets" },
544     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
545                 8, "tx_bcast_packets" },
546     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
547                 8, "tpa_aggregations" },
548     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
549                 8, "tpa_aggregated_frames"},
550     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
551                 8, "tpa_bytes"},
552     { Q_STATS_OFFSET32(rx_calls),
553                 4, "rx_calls"},
554     { Q_STATS_OFFSET32(rx_pkts),
555                 4, "rx_pkts"},
556     { Q_STATS_OFFSET32(rx_tpa_pkts),
557                 4, "rx_tpa_pkts"},
558     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
559                 4, "rx_erroneous_jumbo_sge_pkts"},
560     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
561                 4, "rx_bxe_service_rxsgl"},
562     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
563                 4, "rx_jumbo_sge_pkts"},
564     { Q_STATS_OFFSET32(rx_soft_errors),
565                 4, "rx_soft_errors"},
566     { Q_STATS_OFFSET32(rx_hw_csum_errors),
567                 4, "rx_hw_csum_errors"},
568     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
569                 4, "rx_ofld_frames_csum_ip"},
570     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
571                 4, "rx_ofld_frames_csum_tcp_udp"},
572     { Q_STATS_OFFSET32(rx_budget_reached),
573                 4, "rx_budget_reached"},
574     { Q_STATS_OFFSET32(tx_pkts),
575                 4, "tx_pkts"},
576     { Q_STATS_OFFSET32(tx_soft_errors),
577                 4, "tx_soft_errors"},
578     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
579                 4, "tx_ofld_frames_csum_ip"},
580     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
581                 4, "tx_ofld_frames_csum_tcp"},
582     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
583                 4, "tx_ofld_frames_csum_udp"},
584     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
585                 4, "tx_ofld_frames_lso"},
586     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
587                 4, "tx_ofld_frames_lso_hdr_splits"},
588     { Q_STATS_OFFSET32(tx_encap_failures),
589                 4, "tx_encap_failures"},
590     { Q_STATS_OFFSET32(tx_hw_queue_full),
591                 4, "tx_hw_queue_full"},
592     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
593                 4, "tx_hw_max_queue_depth"},
594     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
595                 4, "tx_dma_mapping_failure"},
596     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
597                 4, "tx_max_drbr_queue_depth"},
598     { Q_STATS_OFFSET32(tx_window_violation_std),
599                 4, "tx_window_violation_std"},
600     { Q_STATS_OFFSET32(tx_window_violation_tso),
601                 4, "tx_window_violation_tso"},
602     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
603                 4, "tx_chain_lost_mbuf"},
604     { Q_STATS_OFFSET32(tx_frames_deferred),
605                 4, "tx_frames_deferred"},
606     { Q_STATS_OFFSET32(tx_queue_xoff),
607                 4, "tx_queue_xoff"},
608     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
609                 4, "mbuf_defrag_attempts"},
610     { Q_STATS_OFFSET32(mbuf_defrag_failures),
611                 4, "mbuf_defrag_failures"},
612     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
613                 4, "mbuf_rx_bd_alloc_failed"},
614     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
615                 4, "mbuf_rx_bd_mapping_failed"},
616     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
617                 4, "mbuf_rx_tpa_alloc_failed"},
618     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
619                 4, "mbuf_rx_tpa_mapping_failed"},
620     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
621                 4, "mbuf_rx_sge_alloc_failed"},
622     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
623                 4, "mbuf_rx_sge_mapping_failed"},
624     { Q_STATS_OFFSET32(mbuf_alloc_tx),
625                 4, "mbuf_alloc_tx"},
626     { Q_STATS_OFFSET32(mbuf_alloc_rx),
627                 4, "mbuf_alloc_rx"},
628     { Q_STATS_OFFSET32(mbuf_alloc_sge),
629                 4, "mbuf_alloc_sge"},
630     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
631                 4, "mbuf_alloc_tpa"},
632     { Q_STATS_OFFSET32(tx_queue_full_return),
633                 4, "tx_queue_full_return"},
634     { Q_STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
635                 4, "bxe_tx_mq_sc_state_failures"},
636     { Q_STATS_OFFSET32(tx_request_link_down_failures),
637                 4, "tx_request_link_down_failures"},
638     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
639                 4, "bd_avail_too_less_failures"},
640     { Q_STATS_OFFSET32(tx_mq_not_empty),
641                 4, "tx_mq_not_empty"},
642     { Q_STATS_OFFSET32(nsegs_path1_errors),
643                 4, "nsegs_path1_errors"},
644     { Q_STATS_OFFSET32(nsegs_path2_errors),
645                 4, "nsegs_path2_errors"}
646 
647 
648 };
649 
650 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
651 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
652 
653 
654 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
655                                  uint8_t          read_cfg,
656                                  uint8_t          cmng_type);
657 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
658 static void    storm_memset_cmng(struct bxe_softc *sc,
659                                  struct cmng_init *cmng,
660                                  uint8_t          port);
661 static void    bxe_set_reset_global(struct bxe_softc *sc);
662 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
663 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
664                                  int              engine);
665 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
666 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
667                                    uint8_t          *global,
668                                    uint8_t          print);
669 static void    bxe_int_disable(struct bxe_softc *sc);
670 static int     bxe_release_leader_lock(struct bxe_softc *sc);
671 static void    bxe_pf_disable(struct bxe_softc *sc);
672 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
673 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
674                                       struct bxe_fastpath *fp,
675                                       uint16_t            rx_bd_prod,
676                                       uint16_t            rx_cq_prod,
677                                       uint16_t            rx_sge_prod);
678 static void    bxe_link_report_locked(struct bxe_softc *sc);
679 static void    bxe_link_report(struct bxe_softc *sc);
680 static void    bxe_link_status_update(struct bxe_softc *sc);
681 static void    bxe_periodic_callout_func(void *xsc);
682 static void    bxe_periodic_start(struct bxe_softc *sc);
683 static void    bxe_periodic_stop(struct bxe_softc *sc);
684 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
685                                     uint16_t prev_index,
686                                     uint16_t index);
687 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
688                                      int                 queue);
689 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
690                                      uint16_t            index);
691 static uint8_t bxe_txeof(struct bxe_softc *sc,
692                          struct bxe_fastpath *fp);
693 static void    bxe_task_fp(struct bxe_fastpath *fp);
694 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
695                                      struct mbuf      *m,
696                                      uint8_t          contents);
697 static int     bxe_alloc_mem(struct bxe_softc *sc);
698 static void    bxe_free_mem(struct bxe_softc *sc);
699 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
700 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
701 static int     bxe_interrupt_attach(struct bxe_softc *sc);
702 static void    bxe_interrupt_detach(struct bxe_softc *sc);
703 static void    bxe_set_rx_mode(struct bxe_softc *sc);
704 static int     bxe_init_locked(struct bxe_softc *sc);
705 static int     bxe_stop_locked(struct bxe_softc *sc);
706 static __noinline int bxe_nic_load(struct bxe_softc *sc,
707                                    int              load_mode);
708 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
709                                      uint32_t         unload_mode,
710                                      uint8_t          keep_link);
711 
712 static void bxe_handle_sp_tq(void *context, int pending);
713 static void bxe_handle_fp_tq(void *context, int pending);
714 
715 static int bxe_add_cdev(struct bxe_softc *sc);
716 static void bxe_del_cdev(struct bxe_softc *sc);
717 int bxe_grc_dump(struct bxe_softc *sc);
718 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
719 static void bxe_free_buf_rings(struct bxe_softc *sc);
720 
721 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
722 uint32_t
723 calc_crc32(uint8_t  *crc32_packet,
724            uint32_t crc32_length,
725            uint32_t crc32_seed,
726            uint8_t  complement)
727 {
728    uint32_t byte         = 0;
729    uint32_t bit          = 0;
730    uint8_t  msb          = 0;
731    uint32_t temp         = 0;
732    uint32_t shft         = 0;
733    uint8_t  current_byte = 0;
734    uint32_t crc32_result = crc32_seed;
735    const uint32_t CRC32_POLY = 0x1edc6f41;
736 
737    if ((crc32_packet == NULL) ||
738        (crc32_length == 0) ||
739        ((crc32_length % 8) != 0))
740     {
741         return (crc32_result);
742     }
743 
744     for (byte = 0; byte < crc32_length; byte = byte + 1)
745     {
746         current_byte = crc32_packet[byte];
747         for (bit = 0; bit < 8; bit = bit + 1)
748         {
749             /* msb = crc32_result[31]; */
750             msb = (uint8_t)(crc32_result >> 31);
751 
752             crc32_result = crc32_result << 1;
753 
754             /* it (msb != current_byte[bit]) */
755             if (msb != (0x1 & (current_byte >> bit)))
756             {
757                 crc32_result = crc32_result ^ CRC32_POLY;
758                 /* crc32_result[0] = 1 */
759                 crc32_result |= 1;
760             }
761         }
762     }
763 
764     /* Last step is to:
765      * 1. "mirror" every bit
766      * 2. swap the 4 bytes
767      * 3. complement each bit
768      */
769 
770     /* Mirror */
771     temp = crc32_result;
772     shft = sizeof(crc32_result) * 8 - 1;
773 
774     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
775     {
776         temp <<= 1;
777         temp |= crc32_result & 1;
778         shft-- ;
779     }
780 
781     /* temp[31-bit] = crc32_result[bit] */
782     temp <<= shft;
783 
784     /* Swap */
785     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
786     {
787         uint32_t t0, t1, t2, t3;
788         t0 = (0x000000ff & (temp >> 24));
789         t1 = (0x0000ff00 & (temp >> 8));
790         t2 = (0x00ff0000 & (temp << 8));
791         t3 = (0xff000000 & (temp << 24));
792         crc32_result = t0 | t1 | t2 | t3;
793     }
794 
795     /* Complement */
796     if (complement)
797     {
798         crc32_result = ~crc32_result;
799     }
800 
801     return (crc32_result);
802 }
803 
804 int
805 bxe_test_bit(int                    nr,
806              volatile unsigned long *addr)
807 {
808     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
809 }
810 
811 void
812 bxe_set_bit(unsigned int           nr,
813             volatile unsigned long *addr)
814 {
815     atomic_set_acq_long(addr, (1 << nr));
816 }
817 
818 void
819 bxe_clear_bit(int                    nr,
820               volatile unsigned long *addr)
821 {
822     atomic_clear_acq_long(addr, (1 << nr));
823 }
824 
825 int
826 bxe_test_and_set_bit(int                    nr,
827                        volatile unsigned long *addr)
828 {
829     unsigned long x;
830     nr = (1 << nr);
831     do {
832         x = *addr;
833     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
834     // if (x & nr) bit_was_set; else bit_was_not_set;
835     return (x & nr);
836 }
837 
838 int
839 bxe_test_and_clear_bit(int                    nr,
840                        volatile unsigned long *addr)
841 {
842     unsigned long x;
843     nr = (1 << nr);
844     do {
845         x = *addr;
846     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
847     // if (x & nr) bit_was_set; else bit_was_not_set;
848     return (x & nr);
849 }
850 
851 int
852 bxe_cmpxchg(volatile int *addr,
853             int          old,
854             int          new)
855 {
856     int x;
857     do {
858         x = *addr;
859     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
860     return (x);
861 }
862 
863 /*
864  * Get DMA memory from the OS.
865  *
866  * Validates that the OS has provided DMA buffers in response to a
867  * bus_dmamap_load call and saves the physical address of those buffers.
868  * When the callback is used the OS will return 0 for the mapping function
869  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
870  * failures back to the caller.
871  *
872  * Returns:
873  *   Nothing.
874  */
875 static void
876 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
877 {
878     struct bxe_dma *dma = arg;
879 
880     if (error) {
881         dma->paddr = 0;
882         dma->nseg  = 0;
883         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
884     } else {
885         dma->paddr = segs->ds_addr;
886         dma->nseg  = nseg;
887     }
888 }
889 
890 /*
891  * Allocate a block of memory and map it for DMA. No partial completions
892  * allowed and release any resources acquired if we can't acquire all
893  * resources.
894  *
895  * Returns:
896  *   0 = Success, !0 = Failure
897  */
898 int
899 bxe_dma_alloc(struct bxe_softc *sc,
900               bus_size_t       size,
901               struct bxe_dma   *dma,
902               const char       *msg)
903 {
904     int rc;
905 
906     if (dma->size > 0) {
907         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
908               (unsigned long)dma->size);
909         return (1);
910     }
911 
912     memset(dma, 0, sizeof(*dma)); /* sanity */
913     dma->sc   = sc;
914     dma->size = size;
915     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
916 
917     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
918                             BCM_PAGE_SIZE,      /* alignment */
919                             0,                  /* boundary limit */
920                             BUS_SPACE_MAXADDR,  /* restricted low */
921                             BUS_SPACE_MAXADDR,  /* restricted hi */
922                             NULL,               /* addr filter() */
923                             NULL,               /* addr filter() arg */
924                             size,               /* max map size */
925                             1,                  /* num discontinuous */
926                             size,               /* max seg size */
927                             BUS_DMA_ALLOCNOW,   /* flags */
928                             NULL,               /* lock() */
929                             NULL,               /* lock() arg */
930                             &dma->tag);         /* returned dma tag */
931     if (rc != 0) {
932         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
933         memset(dma, 0, sizeof(*dma));
934         return (1);
935     }
936 
937     rc = bus_dmamem_alloc(dma->tag,
938                           (void **)&dma->vaddr,
939                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
940                           &dma->map);
941     if (rc != 0) {
942         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
943         bus_dma_tag_destroy(dma->tag);
944         memset(dma, 0, sizeof(*dma));
945         return (1);
946     }
947 
948     rc = bus_dmamap_load(dma->tag,
949                          dma->map,
950                          dma->vaddr,
951                          size,
952                          bxe_dma_map_addr, /* BLOGD in here */
953                          dma,
954                          BUS_DMA_NOWAIT);
955     if (rc != 0) {
956         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
957         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
958         bus_dma_tag_destroy(dma->tag);
959         memset(dma, 0, sizeof(*dma));
960         return (1);
961     }
962 
963     return (0);
964 }
965 
966 void
967 bxe_dma_free(struct bxe_softc *sc,
968              struct bxe_dma   *dma)
969 {
970     if (dma->size > 0) {
971         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
972 
973         bus_dmamap_sync(dma->tag, dma->map,
974                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
975         bus_dmamap_unload(dma->tag, dma->map);
976         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
977         bus_dma_tag_destroy(dma->tag);
978     }
979 
980     memset(dma, 0, sizeof(*dma));
981 }
982 
983 /*
984  * These indirect read and write routines are only during init.
985  * The locking is handled by the MCP.
986  */
987 
988 void
989 bxe_reg_wr_ind(struct bxe_softc *sc,
990                uint32_t         addr,
991                uint32_t         val)
992 {
993     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
994     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
995     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
996 }
997 
998 uint32_t
999 bxe_reg_rd_ind(struct bxe_softc *sc,
1000                uint32_t         addr)
1001 {
1002     uint32_t val;
1003 
1004     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1005     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1006     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1007 
1008     return (val);
1009 }
1010 
1011 static int
1012 bxe_acquire_hw_lock(struct bxe_softc *sc,
1013                     uint32_t         resource)
1014 {
1015     uint32_t lock_status;
1016     uint32_t resource_bit = (1 << resource);
1017     int func = SC_FUNC(sc);
1018     uint32_t hw_lock_control_reg;
1019     int cnt;
1020 
1021     /* validate the resource is within range */
1022     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1023         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1024             " resource_bit 0x%x\n", resource, resource_bit);
1025         return (-1);
1026     }
1027 
1028     if (func <= 5) {
1029         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1030     } else {
1031         hw_lock_control_reg =
1032                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1033     }
1034 
1035     /* validate the resource is not already taken */
1036     lock_status = REG_RD(sc, hw_lock_control_reg);
1037     if (lock_status & resource_bit) {
1038         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1039               resource, lock_status, resource_bit);
1040         return (-1);
1041     }
1042 
1043     /* try every 5ms for 5 seconds */
1044     for (cnt = 0; cnt < 1000; cnt++) {
1045         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1046         lock_status = REG_RD(sc, hw_lock_control_reg);
1047         if (lock_status & resource_bit) {
1048             return (0);
1049         }
1050         DELAY(5000);
1051     }
1052 
1053     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1054         resource, resource_bit);
1055     return (-1);
1056 }
1057 
1058 static int
1059 bxe_release_hw_lock(struct bxe_softc *sc,
1060                     uint32_t         resource)
1061 {
1062     uint32_t lock_status;
1063     uint32_t resource_bit = (1 << resource);
1064     int func = SC_FUNC(sc);
1065     uint32_t hw_lock_control_reg;
1066 
1067     /* validate the resource is within range */
1068     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1069         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1070             " resource_bit 0x%x\n", resource, resource_bit);
1071         return (-1);
1072     }
1073 
1074     if (func <= 5) {
1075         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1076     } else {
1077         hw_lock_control_reg =
1078                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1079     }
1080 
1081     /* validate the resource is currently taken */
1082     lock_status = REG_RD(sc, hw_lock_control_reg);
1083     if (!(lock_status & resource_bit)) {
1084         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1085               resource, lock_status, resource_bit);
1086         return (-1);
1087     }
1088 
1089     REG_WR(sc, hw_lock_control_reg, resource_bit);
1090     return (0);
1091 }
1092 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1093 {
1094 	BXE_PHY_LOCK(sc);
1095 	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1096 }
1097 
1098 static void bxe_release_phy_lock(struct bxe_softc *sc)
1099 {
1100 	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1101 	BXE_PHY_UNLOCK(sc);
1102 }
1103 /*
1104  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1105  * had we done things the other way around, if two pfs from the same port
1106  * would attempt to access nvram at the same time, we could run into a
1107  * scenario such as:
1108  * pf A takes the port lock.
1109  * pf B succeeds in taking the same lock since they are from the same port.
1110  * pf A takes the per pf misc lock. Performs eeprom access.
1111  * pf A finishes. Unlocks the per pf misc lock.
1112  * Pf B takes the lock and proceeds to perform it's own access.
1113  * pf A unlocks the per port lock, while pf B is still working (!).
1114  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1115  * access corrupted by pf B).*
1116  */
1117 static int
1118 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1119 {
1120     int port = SC_PORT(sc);
1121     int count, i;
1122     uint32_t val = 0;
1123 
1124     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1125     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1126 
1127     /* adjust timeout for emulation/FPGA */
1128     count = NVRAM_TIMEOUT_COUNT;
1129     if (CHIP_REV_IS_SLOW(sc)) {
1130         count *= 100;
1131     }
1132 
1133     /* request access to nvram interface */
1134     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1135            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1136 
1137     for (i = 0; i < count*10; i++) {
1138         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1139         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1140             break;
1141         }
1142 
1143         DELAY(5);
1144     }
1145 
1146     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1147         BLOGE(sc, "Cannot get access to nvram interface "
1148             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1149             port, val);
1150         return (-1);
1151     }
1152 
1153     return (0);
1154 }
1155 
1156 static int
1157 bxe_release_nvram_lock(struct bxe_softc *sc)
1158 {
1159     int port = SC_PORT(sc);
1160     int count, i;
1161     uint32_t val = 0;
1162 
1163     /* adjust timeout for emulation/FPGA */
1164     count = NVRAM_TIMEOUT_COUNT;
1165     if (CHIP_REV_IS_SLOW(sc)) {
1166         count *= 100;
1167     }
1168 
1169     /* relinquish nvram interface */
1170     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1171            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1172 
1173     for (i = 0; i < count*10; i++) {
1174         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1175         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1176             break;
1177         }
1178 
1179         DELAY(5);
1180     }
1181 
1182     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1183         BLOGE(sc, "Cannot free access to nvram interface "
1184             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1185             port, val);
1186         return (-1);
1187     }
1188 
1189     /* release HW lock: protect against other PFs in PF Direct Assignment */
1190     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1191 
1192     return (0);
1193 }
1194 
1195 static void
1196 bxe_enable_nvram_access(struct bxe_softc *sc)
1197 {
1198     uint32_t val;
1199 
1200     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1201 
1202     /* enable both bits, even on read */
1203     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1204            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1205 }
1206 
1207 static void
1208 bxe_disable_nvram_access(struct bxe_softc *sc)
1209 {
1210     uint32_t val;
1211 
1212     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1213 
1214     /* disable both bits, even after read */
1215     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1216            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1217                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1218 }
1219 
1220 static int
1221 bxe_nvram_read_dword(struct bxe_softc *sc,
1222                      uint32_t         offset,
1223                      uint32_t         *ret_val,
1224                      uint32_t         cmd_flags)
1225 {
1226     int count, i, rc;
1227     uint32_t val;
1228 
1229     /* build the command word */
1230     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1231 
1232     /* need to clear DONE bit separately */
1233     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1234 
1235     /* address of the NVRAM to read from */
1236     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1237            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1238 
1239     /* issue a read command */
1240     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1241 
1242     /* adjust timeout for emulation/FPGA */
1243     count = NVRAM_TIMEOUT_COUNT;
1244     if (CHIP_REV_IS_SLOW(sc)) {
1245         count *= 100;
1246     }
1247 
1248     /* wait for completion */
1249     *ret_val = 0;
1250     rc = -1;
1251     for (i = 0; i < count; i++) {
1252         DELAY(5);
1253         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1254 
1255         if (val & MCPR_NVM_COMMAND_DONE) {
1256             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1257             /* we read nvram data in cpu order
1258              * but ethtool sees it as an array of bytes
1259              * converting to big-endian will do the work
1260              */
1261             *ret_val = htobe32(val);
1262             rc = 0;
1263             break;
1264         }
1265     }
1266 
1267     if (rc == -1) {
1268         BLOGE(sc, "nvram read timeout expired "
1269             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1270             offset, cmd_flags, val);
1271     }
1272 
1273     return (rc);
1274 }
1275 
1276 static int
1277 bxe_nvram_read(struct bxe_softc *sc,
1278                uint32_t         offset,
1279                uint8_t          *ret_buf,
1280                int              buf_size)
1281 {
1282     uint32_t cmd_flags;
1283     uint32_t val;
1284     int rc;
1285 
1286     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1287         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1288               offset, buf_size);
1289         return (-1);
1290     }
1291 
1292     if ((offset + buf_size) > sc->devinfo.flash_size) {
1293         BLOGE(sc, "Invalid parameter, "
1294                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1295               offset, buf_size, sc->devinfo.flash_size);
1296         return (-1);
1297     }
1298 
1299     /* request access to nvram interface */
1300     rc = bxe_acquire_nvram_lock(sc);
1301     if (rc) {
1302         return (rc);
1303     }
1304 
1305     /* enable access to nvram interface */
1306     bxe_enable_nvram_access(sc);
1307 
1308     /* read the first word(s) */
1309     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1310     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1311         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1312         memcpy(ret_buf, &val, 4);
1313 
1314         /* advance to the next dword */
1315         offset += sizeof(uint32_t);
1316         ret_buf += sizeof(uint32_t);
1317         buf_size -= sizeof(uint32_t);
1318         cmd_flags = 0;
1319     }
1320 
1321     if (rc == 0) {
1322         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1323         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1324         memcpy(ret_buf, &val, 4);
1325     }
1326 
1327     /* disable access to nvram interface */
1328     bxe_disable_nvram_access(sc);
1329     bxe_release_nvram_lock(sc);
1330 
1331     return (rc);
1332 }
1333 
1334 static int
1335 bxe_nvram_write_dword(struct bxe_softc *sc,
1336                       uint32_t         offset,
1337                       uint32_t         val,
1338                       uint32_t         cmd_flags)
1339 {
1340     int count, i, rc;
1341 
1342     /* build the command word */
1343     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1344 
1345     /* need to clear DONE bit separately */
1346     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1347 
1348     /* write the data */
1349     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1350 
1351     /* address of the NVRAM to write to */
1352     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1353            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1354 
1355     /* issue the write command */
1356     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1357 
1358     /* adjust timeout for emulation/FPGA */
1359     count = NVRAM_TIMEOUT_COUNT;
1360     if (CHIP_REV_IS_SLOW(sc)) {
1361         count *= 100;
1362     }
1363 
1364     /* wait for completion */
1365     rc = -1;
1366     for (i = 0; i < count; i++) {
1367         DELAY(5);
1368         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1369         if (val & MCPR_NVM_COMMAND_DONE) {
1370             rc = 0;
1371             break;
1372         }
1373     }
1374 
1375     if (rc == -1) {
1376         BLOGE(sc, "nvram write timeout expired "
1377             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1378             offset, cmd_flags, val);
1379     }
1380 
1381     return (rc);
1382 }
1383 
1384 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1385 
1386 static int
1387 bxe_nvram_write1(struct bxe_softc *sc,
1388                  uint32_t         offset,
1389                  uint8_t          *data_buf,
1390                  int              buf_size)
1391 {
1392     uint32_t cmd_flags;
1393     uint32_t align_offset;
1394     uint32_t val;
1395     int rc;
1396 
1397     if ((offset + buf_size) > sc->devinfo.flash_size) {
1398         BLOGE(sc, "Invalid parameter, "
1399                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1400               offset, buf_size, sc->devinfo.flash_size);
1401         return (-1);
1402     }
1403 
1404     /* request access to nvram interface */
1405     rc = bxe_acquire_nvram_lock(sc);
1406     if (rc) {
1407         return (rc);
1408     }
1409 
1410     /* enable access to nvram interface */
1411     bxe_enable_nvram_access(sc);
1412 
1413     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1414     align_offset = (offset & ~0x03);
1415     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1416 
1417     if (rc == 0) {
1418         val &= ~(0xff << BYTE_OFFSET(offset));
1419         val |= (*data_buf << BYTE_OFFSET(offset));
1420 
1421         /* nvram data is returned as an array of bytes
1422          * convert it back to cpu order
1423          */
1424         val = be32toh(val);
1425 
1426         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1427     }
1428 
1429     /* disable access to nvram interface */
1430     bxe_disable_nvram_access(sc);
1431     bxe_release_nvram_lock(sc);
1432 
1433     return (rc);
1434 }
1435 
1436 static int
1437 bxe_nvram_write(struct bxe_softc *sc,
1438                 uint32_t         offset,
1439                 uint8_t          *data_buf,
1440                 int              buf_size)
1441 {
1442     uint32_t cmd_flags;
1443     uint32_t val;
1444     uint32_t written_so_far;
1445     int rc;
1446 
1447     if (buf_size == 1) {
1448         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1449     }
1450 
1451     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1452         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1453               offset, buf_size);
1454         return (-1);
1455     }
1456 
1457     if (buf_size == 0) {
1458         return (0); /* nothing to do */
1459     }
1460 
1461     if ((offset + buf_size) > sc->devinfo.flash_size) {
1462         BLOGE(sc, "Invalid parameter, "
1463                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1464               offset, buf_size, sc->devinfo.flash_size);
1465         return (-1);
1466     }
1467 
1468     /* request access to nvram interface */
1469     rc = bxe_acquire_nvram_lock(sc);
1470     if (rc) {
1471         return (rc);
1472     }
1473 
1474     /* enable access to nvram interface */
1475     bxe_enable_nvram_access(sc);
1476 
1477     written_so_far = 0;
1478     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1479     while ((written_so_far < buf_size) && (rc == 0)) {
1480         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1481             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1482         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1483             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1484         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1485             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1486         }
1487 
1488         memcpy(&val, data_buf, 4);
1489 
1490         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1491 
1492         /* advance to the next dword */
1493         offset += sizeof(uint32_t);
1494         data_buf += sizeof(uint32_t);
1495         written_so_far += sizeof(uint32_t);
1496         cmd_flags = 0;
1497     }
1498 
1499     /* disable access to nvram interface */
1500     bxe_disable_nvram_access(sc);
1501     bxe_release_nvram_lock(sc);
1502 
1503     return (rc);
1504 }
1505 
1506 /* copy command into DMAE command memory and set DMAE command Go */
1507 void
1508 bxe_post_dmae(struct bxe_softc    *sc,
1509               struct dmae_cmd *dmae,
1510               int                 idx)
1511 {
1512     uint32_t cmd_offset;
1513     int i;
1514 
1515     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1516     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1517         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1518     }
1519 
1520     REG_WR(sc, dmae_reg_go_c[idx], 1);
1521 }
1522 
1523 uint32_t
1524 bxe_dmae_opcode_add_comp(uint32_t opcode,
1525                          uint8_t  comp_type)
1526 {
1527     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1528                       DMAE_CMD_C_TYPE_ENABLE));
1529 }
1530 
1531 uint32_t
1532 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1533 {
1534     return (opcode & ~DMAE_CMD_SRC_RESET);
1535 }
1536 
1537 uint32_t
1538 bxe_dmae_opcode(struct bxe_softc *sc,
1539                 uint8_t          src_type,
1540                 uint8_t          dst_type,
1541                 uint8_t          with_comp,
1542                 uint8_t          comp_type)
1543 {
1544     uint32_t opcode = 0;
1545 
1546     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1547                (dst_type << DMAE_CMD_DST_SHIFT));
1548 
1549     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1550 
1551     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1552 
1553     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1554                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1555 
1556     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1557 
1558 #ifdef __BIG_ENDIAN
1559     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1560 #else
1561     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1562 #endif
1563 
1564     if (with_comp) {
1565         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1566     }
1567 
1568     return (opcode);
1569 }
1570 
1571 static void
1572 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1573                         struct dmae_cmd *dmae,
1574                         uint8_t             src_type,
1575                         uint8_t             dst_type)
1576 {
1577     memset(dmae, 0, sizeof(struct dmae_cmd));
1578 
1579     /* set the opcode */
1580     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1581                                    TRUE, DMAE_COMP_PCI);
1582 
1583     /* fill in the completion parameters */
1584     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1585     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1586     dmae->comp_val     = DMAE_COMP_VAL;
1587 }
1588 
1589 /* issue a DMAE command over the init channel and wait for completion */
1590 static int
1591 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1592                          struct dmae_cmd *dmae)
1593 {
1594     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1595     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1596 
1597     BXE_DMAE_LOCK(sc);
1598 
1599     /* reset completion */
1600     *wb_comp = 0;
1601 
1602     /* post the command on the channel used for initializations */
1603     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1604 
1605     /* wait for completion */
1606     DELAY(5);
1607 
1608     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1609         if (!timeout ||
1610             (sc->recovery_state != BXE_RECOVERY_DONE &&
1611              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1612             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1613                 *wb_comp, sc->recovery_state);
1614             BXE_DMAE_UNLOCK(sc);
1615             return (DMAE_TIMEOUT);
1616         }
1617 
1618         timeout--;
1619         DELAY(50);
1620     }
1621 
1622     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1623         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1624                 *wb_comp, sc->recovery_state);
1625         BXE_DMAE_UNLOCK(sc);
1626         return (DMAE_PCI_ERROR);
1627     }
1628 
1629     BXE_DMAE_UNLOCK(sc);
1630     return (0);
1631 }
1632 
1633 void
1634 bxe_read_dmae(struct bxe_softc *sc,
1635               uint32_t         src_addr,
1636               uint32_t         len32)
1637 {
1638     struct dmae_cmd dmae;
1639     uint32_t *data;
1640     int i, rc;
1641 
1642     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1643 
1644     if (!sc->dmae_ready) {
1645         data = BXE_SP(sc, wb_data[0]);
1646 
1647         for (i = 0; i < len32; i++) {
1648             data[i] = (CHIP_IS_E1(sc)) ?
1649                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1650                           REG_RD(sc, (src_addr + (i * 4)));
1651         }
1652 
1653         return;
1654     }
1655 
1656     /* set opcode and fixed command fields */
1657     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1658 
1659     /* fill in addresses and len */
1660     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1661     dmae.src_addr_hi = 0;
1662     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1663     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1664     dmae.len         = len32;
1665 
1666     /* issue the command and wait for completion */
1667     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1668         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1669     }
1670 }
1671 
1672 void
1673 bxe_write_dmae(struct bxe_softc *sc,
1674                bus_addr_t       dma_addr,
1675                uint32_t         dst_addr,
1676                uint32_t         len32)
1677 {
1678     struct dmae_cmd dmae;
1679     int rc;
1680 
1681     if (!sc->dmae_ready) {
1682         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1683 
1684         if (CHIP_IS_E1(sc)) {
1685             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1686         } else {
1687             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1688         }
1689 
1690         return;
1691     }
1692 
1693     /* set opcode and fixed command fields */
1694     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1695 
1696     /* fill in addresses and len */
1697     dmae.src_addr_lo = U64_LO(dma_addr);
1698     dmae.src_addr_hi = U64_HI(dma_addr);
1699     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1700     dmae.dst_addr_hi = 0;
1701     dmae.len         = len32;
1702 
1703     /* issue the command and wait for completion */
1704     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1705         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1706     }
1707 }
1708 
1709 void
1710 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1711                         bus_addr_t       phys_addr,
1712                         uint32_t         addr,
1713                         uint32_t         len)
1714 {
1715     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1716     int offset = 0;
1717 
1718     while (len > dmae_wr_max) {
1719         bxe_write_dmae(sc,
1720                        (phys_addr + offset), /* src DMA address */
1721                        (addr + offset),      /* dst GRC address */
1722                        dmae_wr_max);
1723         offset += (dmae_wr_max * 4);
1724         len -= dmae_wr_max;
1725     }
1726 
1727     bxe_write_dmae(sc,
1728                    (phys_addr + offset), /* src DMA address */
1729                    (addr + offset),      /* dst GRC address */
1730                    len);
1731 }
1732 
1733 void
1734 bxe_set_ctx_validation(struct bxe_softc   *sc,
1735                        struct eth_context *cxt,
1736                        uint32_t           cid)
1737 {
1738     /* ustorm cxt validation */
1739     cxt->ustorm_ag_context.cdu_usage =
1740         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1741             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1742     /* xcontext validation */
1743     cxt->xstorm_ag_context.cdu_reserved =
1744         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1745             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1746 }
1747 
1748 static void
1749 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1750                             uint8_t          port,
1751                             uint8_t          fw_sb_id,
1752                             uint8_t          sb_index,
1753                             uint8_t          ticks)
1754 {
1755     uint32_t addr =
1756         (BAR_CSTRORM_INTMEM +
1757          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1758 
1759     REG_WR8(sc, addr, ticks);
1760 
1761     BLOGD(sc, DBG_LOAD,
1762           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1763           port, fw_sb_id, sb_index, ticks);
1764 }
1765 
1766 static void
1767 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1768                             uint8_t          port,
1769                             uint16_t         fw_sb_id,
1770                             uint8_t          sb_index,
1771                             uint8_t          disable)
1772 {
1773     uint32_t enable_flag =
1774         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1775     uint32_t addr =
1776         (BAR_CSTRORM_INTMEM +
1777          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1778     uint8_t flags;
1779 
1780     /* clear and set */
1781     flags = REG_RD8(sc, addr);
1782     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1783     flags |= enable_flag;
1784     REG_WR8(sc, addr, flags);
1785 
1786     BLOGD(sc, DBG_LOAD,
1787           "port %d fw_sb_id %d sb_index %d disable %d\n",
1788           port, fw_sb_id, sb_index, disable);
1789 }
1790 
1791 void
1792 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1793                              uint8_t          fw_sb_id,
1794                              uint8_t          sb_index,
1795                              uint8_t          disable,
1796                              uint16_t         usec)
1797 {
1798     int port = SC_PORT(sc);
1799     uint8_t ticks = (usec / 4); /* XXX ??? */
1800 
1801     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1802 
1803     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1804     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1805 }
1806 
1807 void
1808 elink_cb_udelay(struct bxe_softc *sc,
1809                 uint32_t         usecs)
1810 {
1811     DELAY(usecs);
1812 }
1813 
1814 uint32_t
1815 elink_cb_reg_read(struct bxe_softc *sc,
1816                   uint32_t         reg_addr)
1817 {
1818     return (REG_RD(sc, reg_addr));
1819 }
1820 
1821 void
1822 elink_cb_reg_write(struct bxe_softc *sc,
1823                    uint32_t         reg_addr,
1824                    uint32_t         val)
1825 {
1826     REG_WR(sc, reg_addr, val);
1827 }
1828 
1829 void
1830 elink_cb_reg_wb_write(struct bxe_softc *sc,
1831                       uint32_t         offset,
1832                       uint32_t         *wb_write,
1833                       uint16_t         len)
1834 {
1835     REG_WR_DMAE(sc, offset, wb_write, len);
1836 }
1837 
1838 void
1839 elink_cb_reg_wb_read(struct bxe_softc *sc,
1840                      uint32_t         offset,
1841                      uint32_t         *wb_write,
1842                      uint16_t         len)
1843 {
1844     REG_RD_DMAE(sc, offset, wb_write, len);
1845 }
1846 
1847 uint8_t
1848 elink_cb_path_id(struct bxe_softc *sc)
1849 {
1850     return (SC_PATH(sc));
1851 }
1852 
1853 void
1854 elink_cb_event_log(struct bxe_softc     *sc,
1855                    const elink_log_id_t elink_log_id,
1856                    ...)
1857 {
1858     /* XXX */
1859     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1860 }
1861 
1862 static int
1863 bxe_set_spio(struct bxe_softc *sc,
1864              int              spio,
1865              uint32_t         mode)
1866 {
1867     uint32_t spio_reg;
1868 
1869     /* Only 2 SPIOs are configurable */
1870     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1871         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1872         return (-1);
1873     }
1874 
1875     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1876 
1877     /* read SPIO and mask except the float bits */
1878     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1879 
1880     switch (mode) {
1881     case MISC_SPIO_OUTPUT_LOW:
1882         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1883         /* clear FLOAT and set CLR */
1884         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1885         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1886         break;
1887 
1888     case MISC_SPIO_OUTPUT_HIGH:
1889         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1890         /* clear FLOAT and set SET */
1891         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1892         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1893         break;
1894 
1895     case MISC_SPIO_INPUT_HI_Z:
1896         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1897         /* set FLOAT */
1898         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1899         break;
1900 
1901     default:
1902         break;
1903     }
1904 
1905     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1906     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1907 
1908     return (0);
1909 }
1910 
1911 static int
1912 bxe_gpio_read(struct bxe_softc *sc,
1913               int              gpio_num,
1914               uint8_t          port)
1915 {
1916     /* The GPIO should be swapped if swap register is set and active */
1917     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1918                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1919     int gpio_shift = (gpio_num +
1920                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1921     uint32_t gpio_mask = (1 << gpio_shift);
1922     uint32_t gpio_reg;
1923 
1924     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1925         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1926             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1927             gpio_mask);
1928         return (-1);
1929     }
1930 
1931     /* read GPIO value */
1932     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1933 
1934     /* get the requested pin value */
1935     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1936 }
1937 
1938 static int
1939 bxe_gpio_write(struct bxe_softc *sc,
1940                int              gpio_num,
1941                uint32_t         mode,
1942                uint8_t          port)
1943 {
1944     /* The GPIO should be swapped if swap register is set and active */
1945     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1946                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1947     int gpio_shift = (gpio_num +
1948                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1949     uint32_t gpio_mask = (1 << gpio_shift);
1950     uint32_t gpio_reg;
1951 
1952     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1953         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1954             " gpio_shift %d gpio_mask 0x%x\n",
1955             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1956         return (-1);
1957     }
1958 
1959     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1960 
1961     /* read GPIO and mask except the float bits */
1962     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1963 
1964     switch (mode) {
1965     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1966         BLOGD(sc, DBG_PHY,
1967               "Set GPIO %d (shift %d) -> output low\n",
1968               gpio_num, gpio_shift);
1969         /* clear FLOAT and set CLR */
1970         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1971         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1972         break;
1973 
1974     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1975         BLOGD(sc, DBG_PHY,
1976               "Set GPIO %d (shift %d) -> output high\n",
1977               gpio_num, gpio_shift);
1978         /* clear FLOAT and set SET */
1979         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1980         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1981         break;
1982 
1983     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1984         BLOGD(sc, DBG_PHY,
1985               "Set GPIO %d (shift %d) -> input\n",
1986               gpio_num, gpio_shift);
1987         /* set FLOAT */
1988         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1989         break;
1990 
1991     default:
1992         break;
1993     }
1994 
1995     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1996     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1997 
1998     return (0);
1999 }
2000 
2001 static int
2002 bxe_gpio_mult_write(struct bxe_softc *sc,
2003                     uint8_t          pins,
2004                     uint32_t         mode)
2005 {
2006     uint32_t gpio_reg;
2007 
2008     /* any port swapping should be handled by caller */
2009 
2010     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2011 
2012     /* read GPIO and mask except the float bits */
2013     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2014     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2015     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2016     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2017 
2018     switch (mode) {
2019     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2020         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2021         /* set CLR */
2022         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2023         break;
2024 
2025     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2026         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2027         /* set SET */
2028         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2029         break;
2030 
2031     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2032         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2033         /* set FLOAT */
2034         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2035         break;
2036 
2037     default:
2038         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2039             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2040         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2041         return (-1);
2042     }
2043 
2044     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2045     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2046 
2047     return (0);
2048 }
2049 
2050 static int
2051 bxe_gpio_int_write(struct bxe_softc *sc,
2052                    int              gpio_num,
2053                    uint32_t         mode,
2054                    uint8_t          port)
2055 {
2056     /* The GPIO should be swapped if swap register is set and active */
2057     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2058                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2059     int gpio_shift = (gpio_num +
2060                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2061     uint32_t gpio_mask = (1 << gpio_shift);
2062     uint32_t gpio_reg;
2063 
2064     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2065         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2066             " gpio_shift %d gpio_mask 0x%x\n",
2067             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2068         return (-1);
2069     }
2070 
2071     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2072 
2073     /* read GPIO int */
2074     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2075 
2076     switch (mode) {
2077     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2078         BLOGD(sc, DBG_PHY,
2079               "Clear GPIO INT %d (shift %d) -> output low\n",
2080               gpio_num, gpio_shift);
2081         /* clear SET and set CLR */
2082         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2083         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2084         break;
2085 
2086     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2087         BLOGD(sc, DBG_PHY,
2088               "Set GPIO INT %d (shift %d) -> output high\n",
2089               gpio_num, gpio_shift);
2090         /* clear CLR and set SET */
2091         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2092         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2093         break;
2094 
2095     default:
2096         break;
2097     }
2098 
2099     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2100     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2101 
2102     return (0);
2103 }
2104 
2105 uint32_t
2106 elink_cb_gpio_read(struct bxe_softc *sc,
2107                    uint16_t         gpio_num,
2108                    uint8_t          port)
2109 {
2110     return (bxe_gpio_read(sc, gpio_num, port));
2111 }
2112 
2113 uint8_t
2114 elink_cb_gpio_write(struct bxe_softc *sc,
2115                     uint16_t         gpio_num,
2116                     uint8_t          mode, /* 0=low 1=high */
2117                     uint8_t          port)
2118 {
2119     return (bxe_gpio_write(sc, gpio_num, mode, port));
2120 }
2121 
2122 uint8_t
2123 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2124                          uint8_t          pins,
2125                          uint8_t          mode) /* 0=low 1=high */
2126 {
2127     return (bxe_gpio_mult_write(sc, pins, mode));
2128 }
2129 
2130 uint8_t
2131 elink_cb_gpio_int_write(struct bxe_softc *sc,
2132                         uint16_t         gpio_num,
2133                         uint8_t          mode, /* 0=low 1=high */
2134                         uint8_t          port)
2135 {
2136     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2137 }
2138 
2139 void
2140 elink_cb_notify_link_changed(struct bxe_softc *sc)
2141 {
2142     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2143                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2144 }
2145 
2146 /* send the MCP a request, block until there is a reply */
2147 uint32_t
2148 elink_cb_fw_command(struct bxe_softc *sc,
2149                     uint32_t         command,
2150                     uint32_t         param)
2151 {
2152     int mb_idx = SC_FW_MB_IDX(sc);
2153     uint32_t seq;
2154     uint32_t rc = 0;
2155     uint32_t cnt = 1;
2156     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2157 
2158     BXE_FWMB_LOCK(sc);
2159 
2160     seq = ++sc->fw_seq;
2161     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2162     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2163 
2164     BLOGD(sc, DBG_PHY,
2165           "wrote command 0x%08x to FW MB param 0x%08x\n",
2166           (command | seq), param);
2167 
2168     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2169     do {
2170         DELAY(delay * 1000);
2171         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2172     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2173 
2174     BLOGD(sc, DBG_PHY,
2175           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2176           cnt*delay, rc, seq);
2177 
2178     /* is this a reply to our command? */
2179     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2180         rc &= FW_MSG_CODE_MASK;
2181     } else {
2182         /* Ruh-roh! */
2183         BLOGE(sc, "FW failed to respond!\n");
2184         // XXX bxe_fw_dump(sc);
2185         rc = 0;
2186     }
2187 
2188     BXE_FWMB_UNLOCK(sc);
2189     return (rc);
2190 }
2191 
2192 static uint32_t
2193 bxe_fw_command(struct bxe_softc *sc,
2194                uint32_t         command,
2195                uint32_t         param)
2196 {
2197     return (elink_cb_fw_command(sc, command, param));
2198 }
2199 
2200 static void
2201 __storm_memset_dma_mapping(struct bxe_softc *sc,
2202                            uint32_t         addr,
2203                            bus_addr_t       mapping)
2204 {
2205     REG_WR(sc, addr, U64_LO(mapping));
2206     REG_WR(sc, (addr + 4), U64_HI(mapping));
2207 }
2208 
2209 static void
2210 storm_memset_spq_addr(struct bxe_softc *sc,
2211                       bus_addr_t       mapping,
2212                       uint16_t         abs_fid)
2213 {
2214     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2215                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2216     __storm_memset_dma_mapping(sc, addr, mapping);
2217 }
2218 
2219 static void
2220 storm_memset_vf_to_pf(struct bxe_softc *sc,
2221                       uint16_t         abs_fid,
2222                       uint16_t         pf_id)
2223 {
2224     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2225     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2226     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2227     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2228 }
2229 
2230 static void
2231 storm_memset_func_en(struct bxe_softc *sc,
2232                      uint16_t         abs_fid,
2233                      uint8_t          enable)
2234 {
2235     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2236     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2237     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2238     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2239 }
2240 
2241 static void
2242 storm_memset_eq_data(struct bxe_softc       *sc,
2243                      struct event_ring_data *eq_data,
2244                      uint16_t               pfid)
2245 {
2246     uint32_t addr;
2247     size_t size;
2248 
2249     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2250     size = sizeof(struct event_ring_data);
2251     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2252 }
2253 
2254 static void
2255 storm_memset_eq_prod(struct bxe_softc *sc,
2256                      uint16_t         eq_prod,
2257                      uint16_t         pfid)
2258 {
2259     uint32_t addr = (BAR_CSTRORM_INTMEM +
2260                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2261     REG_WR16(sc, addr, eq_prod);
2262 }
2263 
2264 /*
2265  * Post a slowpath command.
2266  *
2267  * A slowpath command is used to propagate a configuration change through
2268  * the controller in a controlled manner, allowing each STORM processor and
2269  * other H/W blocks to phase in the change.  The commands sent on the
2270  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2271  * completion of the ramrod will occur in different ways.  Here's a
2272  * breakdown of ramrods and how they complete:
2273  *
2274  * RAMROD_CMD_ID_ETH_PORT_SETUP
2275  *   Used to setup the leading connection on a port.  Completes on the
2276  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2277  *
2278  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2279  *   Used to setup an additional connection on a port.  Completes on the
2280  *   RCQ of the multi-queue/RSS connection being initialized.
2281  *
2282  * RAMROD_CMD_ID_ETH_STAT_QUERY
2283  *   Used to force the storm processors to update the statistics database
2284  *   in host memory.  This ramrod is send on the leading connection CID and
2285  *   completes as an index increment of the CSTORM on the default status
2286  *   block.
2287  *
2288  * RAMROD_CMD_ID_ETH_UPDATE
2289  *   Used to update the state of the leading connection, usually to udpate
2290  *   the RSS indirection table.  Completes on the RCQ of the leading
2291  *   connection. (Not currently used under FreeBSD until OS support becomes
2292  *   available.)
2293  *
2294  * RAMROD_CMD_ID_ETH_HALT
2295  *   Used when tearing down a connection prior to driver unload.  Completes
2296  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2297  *   use this on the leading connection.
2298  *
2299  * RAMROD_CMD_ID_ETH_SET_MAC
2300  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2301  *   the RCQ of the leading connection.
2302  *
2303  * RAMROD_CMD_ID_ETH_CFC_DEL
2304  *   Used when tearing down a conneciton prior to driver unload.  Completes
2305  *   on the RCQ of the leading connection (since the current connection
2306  *   has been completely removed from controller memory).
2307  *
2308  * RAMROD_CMD_ID_ETH_PORT_DEL
2309  *   Used to tear down the leading connection prior to driver unload,
2310  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2311  *   default status block.
2312  *
2313  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2314  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2315  *   RSS connection that is being offloaded.  (Not currently used under
2316  *   FreeBSD.)
2317  *
2318  * There can only be one command pending per function.
2319  *
2320  * Returns:
2321  *   0 = Success, !0 = Failure.
2322  */
2323 
2324 /* must be called under the spq lock */
2325 static inline
2326 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2327 {
2328     struct eth_spe *next_spe = sc->spq_prod_bd;
2329 
2330     if (sc->spq_prod_bd == sc->spq_last_bd) {
2331         /* wrap back to the first eth_spq */
2332         sc->spq_prod_bd = sc->spq;
2333         sc->spq_prod_idx = 0;
2334     } else {
2335         sc->spq_prod_bd++;
2336         sc->spq_prod_idx++;
2337     }
2338 
2339     return (next_spe);
2340 }
2341 
2342 /* must be called under the spq lock */
2343 static inline
2344 void bxe_sp_prod_update(struct bxe_softc *sc)
2345 {
2346     int func = SC_FUNC(sc);
2347 
2348     /*
2349      * Make sure that BD data is updated before writing the producer.
2350      * BD data is written to the memory, the producer is read from the
2351      * memory, thus we need a full memory barrier to ensure the ordering.
2352      */
2353     mb();
2354 
2355     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2356              sc->spq_prod_idx);
2357 
2358     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2359                       BUS_SPACE_BARRIER_WRITE);
2360 }
2361 
2362 /**
2363  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2364  *
2365  * @cmd:      command to check
2366  * @cmd_type: command type
2367  */
2368 static inline
2369 int bxe_is_contextless_ramrod(int cmd,
2370                               int cmd_type)
2371 {
2372     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2373         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2374         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2375         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2376         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2377         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2378         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2379         return (TRUE);
2380     } else {
2381         return (FALSE);
2382     }
2383 }
2384 
2385 /**
2386  * bxe_sp_post - place a single command on an SP ring
2387  *
2388  * @sc:         driver handle
2389  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2390  * @cid:        SW CID the command is related to
2391  * @data_hi:    command private data address (high 32 bits)
2392  * @data_lo:    command private data address (low 32 bits)
2393  * @cmd_type:   command type (e.g. NONE, ETH)
2394  *
2395  * SP data is handled as if it's always an address pair, thus data fields are
2396  * not swapped to little endian in upper functions. Instead this function swaps
2397  * data as if it's two uint32 fields.
2398  */
2399 int
2400 bxe_sp_post(struct bxe_softc *sc,
2401             int              command,
2402             int              cid,
2403             uint32_t         data_hi,
2404             uint32_t         data_lo,
2405             int              cmd_type)
2406 {
2407     struct eth_spe *spe;
2408     uint16_t type;
2409     int common;
2410 
2411     common = bxe_is_contextless_ramrod(command, cmd_type);
2412 
2413     BXE_SP_LOCK(sc);
2414 
2415     if (common) {
2416         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2417             BLOGE(sc, "EQ ring is full!\n");
2418             BXE_SP_UNLOCK(sc);
2419             return (-1);
2420         }
2421     } else {
2422         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2423             BLOGE(sc, "SPQ ring is full!\n");
2424             BXE_SP_UNLOCK(sc);
2425             return (-1);
2426         }
2427     }
2428 
2429     spe = bxe_sp_get_next(sc);
2430 
2431     /* CID needs port number to be encoded int it */
2432     spe->hdr.conn_and_cmd_data =
2433         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2434 
2435     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2436 
2437     /* TBD: Check if it works for VFs */
2438     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2439              SPE_HDR_T_FUNCTION_ID);
2440 
2441     spe->hdr.type = htole16(type);
2442 
2443     spe->data.update_data_addr.hi = htole32(data_hi);
2444     spe->data.update_data_addr.lo = htole32(data_lo);
2445 
2446     /*
2447      * It's ok if the actual decrement is issued towards the memory
2448      * somewhere between the lock and unlock. Thus no more explict
2449      * memory barrier is needed.
2450      */
2451     if (common) {
2452         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2453     } else {
2454         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2455     }
2456 
2457     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2458     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2459           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2460     BLOGD(sc, DBG_SP,
2461           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2462           sc->spq_prod_idx,
2463           (uint32_t)U64_HI(sc->spq_dma.paddr),
2464           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2465           command,
2466           common,
2467           HW_CID(sc, cid),
2468           data_hi,
2469           data_lo,
2470           type,
2471           atomic_load_acq_long(&sc->cq_spq_left),
2472           atomic_load_acq_long(&sc->eq_spq_left));
2473 
2474     bxe_sp_prod_update(sc);
2475 
2476     BXE_SP_UNLOCK(sc);
2477     return (0);
2478 }
2479 
2480 /**
2481  * bxe_debug_print_ind_table - prints the indirection table configuration.
2482  *
2483  * @sc: driver hanlde
2484  * @p:  pointer to rss configuration
2485  */
2486 
2487 /*
2488  * FreeBSD Device probe function.
2489  *
2490  * Compares the device found to the driver's list of supported devices and
2491  * reports back to the bsd loader whether this is the right driver for the device.
2492  * This is the driver entry function called from the "kldload" command.
2493  *
2494  * Returns:
2495  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2496  */
2497 static int
2498 bxe_probe(device_t dev)
2499 {
2500     struct bxe_device_type *t;
2501     char *descbuf;
2502     uint16_t did, sdid, svid, vid;
2503 
2504     /* Find our device structure */
2505     t = bxe_devs;
2506 
2507     /* Get the data for the device to be probed. */
2508     vid  = pci_get_vendor(dev);
2509     did  = pci_get_device(dev);
2510     svid = pci_get_subvendor(dev);
2511     sdid = pci_get_subdevice(dev);
2512 
2513     /* Look through the list of known devices for a match. */
2514     while (t->bxe_name != NULL) {
2515         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2516             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2517             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2518             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2519             if (descbuf == NULL)
2520                 return (ENOMEM);
2521 
2522             /* Print out the device identity. */
2523             snprintf(descbuf, BXE_DEVDESC_MAX,
2524                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2525                      (((pci_read_config(dev, PCIR_REVID, 4) &
2526                         0xf0) >> 4) + 'A'),
2527                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2528                      BXE_DRIVER_VERSION);
2529 
2530             device_set_desc_copy(dev, descbuf);
2531             free(descbuf, M_TEMP);
2532             return (BUS_PROBE_DEFAULT);
2533         }
2534         t++;
2535     }
2536 
2537     return (ENXIO);
2538 }
2539 
2540 static void
2541 bxe_init_mutexes(struct bxe_softc *sc)
2542 {
2543 #ifdef BXE_CORE_LOCK_SX
2544     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2545              "bxe%d_core_lock", sc->unit);
2546     sx_init(&sc->core_sx, sc->core_sx_name);
2547 #else
2548     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2549              "bxe%d_core_lock", sc->unit);
2550     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2551 #endif
2552 
2553     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2554              "bxe%d_sp_lock", sc->unit);
2555     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2556 
2557     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2558              "bxe%d_dmae_lock", sc->unit);
2559     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2560 
2561     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2562              "bxe%d_phy_lock", sc->unit);
2563     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2564 
2565     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2566              "bxe%d_fwmb_lock", sc->unit);
2567     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2568 
2569     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2570              "bxe%d_print_lock", sc->unit);
2571     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2572 
2573     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2574              "bxe%d_stats_lock", sc->unit);
2575     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2576 
2577     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2578              "bxe%d_mcast_lock", sc->unit);
2579     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2580 }
2581 
2582 static void
2583 bxe_release_mutexes(struct bxe_softc *sc)
2584 {
2585 #ifdef BXE_CORE_LOCK_SX
2586     sx_destroy(&sc->core_sx);
2587 #else
2588     if (mtx_initialized(&sc->core_mtx)) {
2589         mtx_destroy(&sc->core_mtx);
2590     }
2591 #endif
2592 
2593     if (mtx_initialized(&sc->sp_mtx)) {
2594         mtx_destroy(&sc->sp_mtx);
2595     }
2596 
2597     if (mtx_initialized(&sc->dmae_mtx)) {
2598         mtx_destroy(&sc->dmae_mtx);
2599     }
2600 
2601     if (mtx_initialized(&sc->port.phy_mtx)) {
2602         mtx_destroy(&sc->port.phy_mtx);
2603     }
2604 
2605     if (mtx_initialized(&sc->fwmb_mtx)) {
2606         mtx_destroy(&sc->fwmb_mtx);
2607     }
2608 
2609     if (mtx_initialized(&sc->print_mtx)) {
2610         mtx_destroy(&sc->print_mtx);
2611     }
2612 
2613     if (mtx_initialized(&sc->stats_mtx)) {
2614         mtx_destroy(&sc->stats_mtx);
2615     }
2616 
2617     if (mtx_initialized(&sc->mcast_mtx)) {
2618         mtx_destroy(&sc->mcast_mtx);
2619     }
2620 }
2621 
2622 static void
2623 bxe_tx_disable(struct bxe_softc* sc)
2624 {
2625     if_t ifp = sc->ifp;
2626 
2627     /* tell the stack the driver is stopped and TX queue is full */
2628     if (ifp !=  NULL) {
2629         if_setdrvflags(ifp, 0);
2630     }
2631 }
2632 
2633 static void
2634 bxe_drv_pulse(struct bxe_softc *sc)
2635 {
2636     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2637              sc->fw_drv_pulse_wr_seq);
2638 }
2639 
2640 static inline uint16_t
2641 bxe_tx_avail(struct bxe_softc *sc,
2642              struct bxe_fastpath *fp)
2643 {
2644     int16_t  used;
2645     uint16_t prod;
2646     uint16_t cons;
2647 
2648     prod = fp->tx_bd_prod;
2649     cons = fp->tx_bd_cons;
2650 
2651     used = SUB_S16(prod, cons);
2652 
2653     return (int16_t)(sc->tx_ring_size) - used;
2654 }
2655 
2656 static inline int
2657 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2658 {
2659     uint16_t hw_cons;
2660 
2661     mb(); /* status block fields can change */
2662     hw_cons = le16toh(*fp->tx_cons_sb);
2663     return (hw_cons != fp->tx_pkt_cons);
2664 }
2665 
2666 static inline uint8_t
2667 bxe_has_tx_work(struct bxe_fastpath *fp)
2668 {
2669     /* expand this for multi-cos if ever supported */
2670     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2671 }
2672 
2673 static inline int
2674 bxe_has_rx_work(struct bxe_fastpath *fp)
2675 {
2676     uint16_t rx_cq_cons_sb;
2677 
2678     mb(); /* status block fields can change */
2679     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2680     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2681         rx_cq_cons_sb++;
2682     return (fp->rx_cq_cons != rx_cq_cons_sb);
2683 }
2684 
2685 static void
2686 bxe_sp_event(struct bxe_softc    *sc,
2687              struct bxe_fastpath *fp,
2688              union eth_rx_cqe    *rr_cqe)
2689 {
2690     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2691     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2692     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2693     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2694 
2695     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2696           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2697 
2698     switch (command) {
2699     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2700         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2701         drv_cmd = ECORE_Q_CMD_UPDATE;
2702         break;
2703 
2704     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2705         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2706         drv_cmd = ECORE_Q_CMD_SETUP;
2707         break;
2708 
2709     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2710         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2711         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2712         break;
2713 
2714     case (RAMROD_CMD_ID_ETH_HALT):
2715         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2716         drv_cmd = ECORE_Q_CMD_HALT;
2717         break;
2718 
2719     case (RAMROD_CMD_ID_ETH_TERMINATE):
2720         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2721         drv_cmd = ECORE_Q_CMD_TERMINATE;
2722         break;
2723 
2724     case (RAMROD_CMD_ID_ETH_EMPTY):
2725         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2726         drv_cmd = ECORE_Q_CMD_EMPTY;
2727         break;
2728 
2729     default:
2730         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2731               command, fp->index);
2732         return;
2733     }
2734 
2735     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2736         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2737         /*
2738          * q_obj->complete_cmd() failure means that this was
2739          * an unexpected completion.
2740          *
2741          * In this case we don't want to increase the sc->spq_left
2742          * because apparently we haven't sent this command the first
2743          * place.
2744          */
2745         // bxe_panic(sc, ("Unexpected SP completion\n"));
2746         return;
2747     }
2748 
2749     atomic_add_acq_long(&sc->cq_spq_left, 1);
2750 
2751     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2752           atomic_load_acq_long(&sc->cq_spq_left));
2753 }
2754 
2755 /*
2756  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2757  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2758  * the current aggregation queue as in-progress.
2759  */
2760 static void
2761 bxe_tpa_start(struct bxe_softc            *sc,
2762               struct bxe_fastpath         *fp,
2763               uint16_t                    queue,
2764               uint16_t                    cons,
2765               uint16_t                    prod,
2766               struct eth_fast_path_rx_cqe *cqe)
2767 {
2768     struct bxe_sw_rx_bd tmp_bd;
2769     struct bxe_sw_rx_bd *rx_buf;
2770     struct eth_rx_bd *rx_bd;
2771     int max_agg_queues;
2772     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2773     uint16_t index;
2774 
2775     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2776                        "cons=%d prod=%d\n",
2777           fp->index, queue, cons, prod);
2778 
2779     max_agg_queues = MAX_AGG_QS(sc);
2780 
2781     KASSERT((queue < max_agg_queues),
2782             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2783              fp->index, queue, max_agg_queues));
2784 
2785     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2786             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2787              fp->index, queue));
2788 
2789     /* copy the existing mbuf and mapping from the TPA pool */
2790     tmp_bd = tpa_info->bd;
2791 
2792     if (tmp_bd.m == NULL) {
2793         uint32_t *tmp;
2794 
2795         tmp = (uint32_t *)cqe;
2796 
2797         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2798               fp->index, queue, cons, prod);
2799         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2800             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2801 
2802         /* XXX Error handling? */
2803         return;
2804     }
2805 
2806     /* change the TPA queue to the start state */
2807     tpa_info->state            = BXE_TPA_STATE_START;
2808     tpa_info->placement_offset = cqe->placement_offset;
2809     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2810     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2811     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2812 
2813     fp->rx_tpa_queue_used |= (1 << queue);
2814 
2815     /*
2816      * If all the buffer descriptors are filled with mbufs then fill in
2817      * the current consumer index with a new BD. Else if a maximum Rx
2818      * buffer limit is imposed then fill in the next producer index.
2819      */
2820     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2821                 prod : cons;
2822 
2823     /* move the received mbuf and mapping to TPA pool */
2824     tpa_info->bd = fp->rx_mbuf_chain[cons];
2825 
2826     /* release any existing RX BD mbuf mappings */
2827     if (cons != index) {
2828         rx_buf = &fp->rx_mbuf_chain[cons];
2829 
2830         if (rx_buf->m_map != NULL) {
2831             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2832                             BUS_DMASYNC_POSTREAD);
2833             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2834         }
2835 
2836         /*
2837          * We get here when the maximum number of rx buffers is less than
2838          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2839          * it out here without concern of a memory leak.
2840          */
2841         fp->rx_mbuf_chain[cons].m = NULL;
2842     }
2843 
2844     /* update the Rx SW BD with the mbuf info from the TPA pool */
2845     fp->rx_mbuf_chain[index] = tmp_bd;
2846 
2847     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2848     rx_bd = &fp->rx_chain[index];
2849     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2850     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2851 }
2852 
2853 /*
2854  * When a TPA aggregation is completed, loop through the individual mbufs
2855  * of the aggregation, combining them into a single mbuf which will be sent
2856  * up the stack. Refill all freed SGEs with mbufs as we go along.
2857  */
2858 static int
2859 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2860                    struct bxe_fastpath       *fp,
2861                    struct bxe_sw_tpa_info    *tpa_info,
2862                    uint16_t                  queue,
2863                    uint16_t                  pages,
2864                    struct mbuf               *m,
2865 			       struct eth_end_agg_rx_cqe *cqe,
2866                    uint16_t                  cqe_idx)
2867 {
2868     struct mbuf *m_frag;
2869     uint32_t frag_len, frag_size, i;
2870     uint16_t sge_idx;
2871     int rc = 0;
2872     int j;
2873 
2874     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2875 
2876     BLOGD(sc, DBG_LRO,
2877           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2878           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2879 
2880     /* make sure the aggregated frame is not too big to handle */
2881     if (pages > 8 * PAGES_PER_SGE) {
2882 
2883         uint32_t *tmp = (uint32_t *)cqe;
2884 
2885         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2886                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2887               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2888               tpa_info->len_on_bd, frag_size);
2889 
2890         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2891             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2892 
2893         bxe_panic(sc, ("sge page count error\n"));
2894         return (EINVAL);
2895     }
2896 
2897     /*
2898      * Scan through the scatter gather list pulling individual mbufs into a
2899      * single mbuf for the host stack.
2900      */
2901     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2902         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2903 
2904         /*
2905          * Firmware gives the indices of the SGE as if the ring is an array
2906          * (meaning that the "next" element will consume 2 indices).
2907          */
2908         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2909 
2910         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2911                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2912               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2913 
2914         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2915 
2916         /* allocate a new mbuf for the SGE */
2917         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2918         if (rc) {
2919             /* Leave all remaining SGEs in the ring! */
2920             return (rc);
2921         }
2922 
2923         /* update the fragment length */
2924         m_frag->m_len = frag_len;
2925 
2926         /* concatenate the fragment to the head mbuf */
2927         m_cat(m, m_frag);
2928         fp->eth_q_stats.mbuf_alloc_sge--;
2929 
2930         /* update the TPA mbuf size and remaining fragment size */
2931         m->m_pkthdr.len += frag_len;
2932         frag_size -= frag_len;
2933     }
2934 
2935     BLOGD(sc, DBG_LRO,
2936           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2937           fp->index, queue, frag_size);
2938 
2939     return (rc);
2940 }
2941 
2942 static inline void
2943 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2944 {
2945     int i, j;
2946 
2947     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2948         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2949 
2950         for (j = 0; j < 2; j++) {
2951             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2952             idx--;
2953         }
2954     }
2955 }
2956 
2957 static inline void
2958 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2959 {
2960     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2961     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2962 
2963     /*
2964      * Clear the two last indices in the page to 1. These are the indices that
2965      * correspond to the "next" element, hence will never be indicated and
2966      * should be removed from the calculations.
2967      */
2968     bxe_clear_sge_mask_next_elems(fp);
2969 }
2970 
2971 static inline void
2972 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2973                         uint16_t            idx)
2974 {
2975     uint16_t last_max = fp->last_max_sge;
2976 
2977     if (SUB_S16(idx, last_max) > 0) {
2978         fp->last_max_sge = idx;
2979     }
2980 }
2981 
2982 static inline void
2983 bxe_update_sge_prod(struct bxe_softc          *sc,
2984                     struct bxe_fastpath       *fp,
2985                     uint16_t                  sge_len,
2986                     union eth_sgl_or_raw_data *cqe)
2987 {
2988     uint16_t last_max, last_elem, first_elem;
2989     uint16_t delta = 0;
2990     uint16_t i;
2991 
2992     if (!sge_len) {
2993         return;
2994     }
2995 
2996     /* first mark all used pages */
2997     for (i = 0; i < sge_len; i++) {
2998         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2999                             RX_SGE(le16toh(cqe->sgl[i])));
3000     }
3001 
3002     BLOGD(sc, DBG_LRO,
3003           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3004           fp->index, sge_len - 1,
3005           le16toh(cqe->sgl[sge_len - 1]));
3006 
3007     /* assume that the last SGE index is the biggest */
3008     bxe_update_last_max_sge(fp,
3009                             le16toh(cqe->sgl[sge_len - 1]));
3010 
3011     last_max = RX_SGE(fp->last_max_sge);
3012     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3013     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3014 
3015     /* if ring is not full */
3016     if (last_elem + 1 != first_elem) {
3017         last_elem++;
3018     }
3019 
3020     /* now update the prod */
3021     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3022         if (__predict_true(fp->sge_mask[i])) {
3023             break;
3024         }
3025 
3026         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3027         delta += BIT_VEC64_ELEM_SZ;
3028     }
3029 
3030     if (delta > 0) {
3031         fp->rx_sge_prod += delta;
3032         /* clear page-end entries */
3033         bxe_clear_sge_mask_next_elems(fp);
3034     }
3035 
3036     BLOGD(sc, DBG_LRO,
3037           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3038           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3039 }
3040 
3041 /*
3042  * The aggregation on the current TPA queue has completed. Pull the individual
3043  * mbuf fragments together into a single mbuf, perform all necessary checksum
3044  * calculations, and send the resuting mbuf to the stack.
3045  */
3046 static void
3047 bxe_tpa_stop(struct bxe_softc          *sc,
3048              struct bxe_fastpath       *fp,
3049              struct bxe_sw_tpa_info    *tpa_info,
3050              uint16_t                  queue,
3051              uint16_t                  pages,
3052 			 struct eth_end_agg_rx_cqe *cqe,
3053              uint16_t                  cqe_idx)
3054 {
3055     if_t ifp = sc->ifp;
3056     struct mbuf *m;
3057     int rc = 0;
3058 
3059     BLOGD(sc, DBG_LRO,
3060           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3061           fp->index, queue, tpa_info->placement_offset,
3062           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3063 
3064     m = tpa_info->bd.m;
3065 
3066     /* allocate a replacement before modifying existing mbuf */
3067     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3068     if (rc) {
3069         /* drop the frame and log an error */
3070         fp->eth_q_stats.rx_soft_errors++;
3071         goto bxe_tpa_stop_exit;
3072     }
3073 
3074     /* we have a replacement, fixup the current mbuf */
3075     m_adj(m, tpa_info->placement_offset);
3076     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3077 
3078     /* mark the checksums valid (taken care of by the firmware) */
3079     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3080     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3081     m->m_pkthdr.csum_data = 0xffff;
3082     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3083                                CSUM_IP_VALID   |
3084                                CSUM_DATA_VALID |
3085                                CSUM_PSEUDO_HDR);
3086 
3087     /* aggregate all of the SGEs into a single mbuf */
3088     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3089     if (rc) {
3090         /* drop the packet and log an error */
3091         fp->eth_q_stats.rx_soft_errors++;
3092         m_freem(m);
3093     } else {
3094         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3095             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3096             m->m_flags |= M_VLANTAG;
3097         }
3098 
3099         /* assign packet to this interface interface */
3100         if_setrcvif(m, ifp);
3101 
3102 #if __FreeBSD_version >= 800000
3103         /* specify what RSS queue was used for this flow */
3104         m->m_pkthdr.flowid = fp->index;
3105         BXE_SET_FLOWID(m);
3106 #endif
3107 
3108         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3109         fp->eth_q_stats.rx_tpa_pkts++;
3110 
3111         /* pass the frame to the stack */
3112         if_input(ifp, m);
3113     }
3114 
3115     /* we passed an mbuf up the stack or dropped the frame */
3116     fp->eth_q_stats.mbuf_alloc_tpa--;
3117 
3118 bxe_tpa_stop_exit:
3119 
3120     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3121     fp->rx_tpa_queue_used &= ~(1 << queue);
3122 }
3123 
3124 static uint8_t
3125 bxe_service_rxsgl(
3126                  struct bxe_fastpath *fp,
3127                  uint16_t len,
3128                  uint16_t lenonbd,
3129                  struct mbuf *m,
3130                  struct eth_fast_path_rx_cqe *cqe_fp)
3131 {
3132     struct mbuf *m_frag;
3133     uint16_t frags, frag_len;
3134     uint16_t sge_idx = 0;
3135     uint16_t j;
3136     uint8_t i, rc = 0;
3137     uint32_t frag_size;
3138 
3139     /* adjust the mbuf */
3140     m->m_len = lenonbd;
3141 
3142     frag_size =  len - lenonbd;
3143     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3144 
3145     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3146         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3147 
3148         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3149         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3150         m_frag->m_len = frag_len;
3151 
3152        /* allocate a new mbuf for the SGE */
3153         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3154         if (rc) {
3155             /* Leave all remaining SGEs in the ring! */
3156             return (rc);
3157         }
3158         fp->eth_q_stats.mbuf_alloc_sge--;
3159 
3160         /* concatenate the fragment to the head mbuf */
3161         m_cat(m, m_frag);
3162 
3163         frag_size -= frag_len;
3164     }
3165 
3166     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3167 
3168     return rc;
3169 }
3170 
3171 static uint8_t
3172 bxe_rxeof(struct bxe_softc    *sc,
3173           struct bxe_fastpath *fp)
3174 {
3175     if_t ifp = sc->ifp;
3176     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3177     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3178     int rx_pkts = 0;
3179     int rc = 0;
3180 
3181     BXE_FP_RX_LOCK(fp);
3182 
3183     /* CQ "next element" is of the size of the regular element */
3184     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3185     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3186         hw_cq_cons++;
3187     }
3188 
3189     bd_cons = fp->rx_bd_cons;
3190     bd_prod = fp->rx_bd_prod;
3191     bd_prod_fw = bd_prod;
3192     sw_cq_cons = fp->rx_cq_cons;
3193     sw_cq_prod = fp->rx_cq_prod;
3194 
3195     /*
3196      * Memory barrier necessary as speculative reads of the rx
3197      * buffer can be ahead of the index in the status block
3198      */
3199     rmb();
3200 
3201     BLOGD(sc, DBG_RX,
3202           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3203           fp->index, hw_cq_cons, sw_cq_cons);
3204 
3205     while (sw_cq_cons != hw_cq_cons) {
3206         struct bxe_sw_rx_bd *rx_buf = NULL;
3207         union eth_rx_cqe *cqe;
3208         struct eth_fast_path_rx_cqe *cqe_fp;
3209         uint8_t cqe_fp_flags;
3210         enum eth_rx_cqe_type cqe_fp_type;
3211         uint16_t len, lenonbd,  pad;
3212         struct mbuf *m = NULL;
3213 
3214         comp_ring_cons = RCQ(sw_cq_cons);
3215         bd_prod = RX_BD(bd_prod);
3216         bd_cons = RX_BD(bd_cons);
3217 
3218         cqe          = &fp->rcq_chain[comp_ring_cons];
3219         cqe_fp       = &cqe->fast_path_cqe;
3220         cqe_fp_flags = cqe_fp->type_error_flags;
3221         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3222 
3223         BLOGD(sc, DBG_RX,
3224               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3225               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3226               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3227               fp->index,
3228               hw_cq_cons,
3229               sw_cq_cons,
3230               bd_prod,
3231               bd_cons,
3232               CQE_TYPE(cqe_fp_flags),
3233               cqe_fp_flags,
3234               cqe_fp->status_flags,
3235               le32toh(cqe_fp->rss_hash_result),
3236               le16toh(cqe_fp->vlan_tag),
3237               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3238               le16toh(cqe_fp->len_on_bd));
3239 
3240         /* is this a slowpath msg? */
3241         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3242             bxe_sp_event(sc, fp, cqe);
3243             goto next_cqe;
3244         }
3245 
3246         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3247 
3248         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3249             struct bxe_sw_tpa_info *tpa_info;
3250             uint16_t frag_size, pages;
3251             uint8_t queue;
3252 
3253             if (CQE_TYPE_START(cqe_fp_type)) {
3254                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3255                               bd_cons, bd_prod, cqe_fp);
3256                 m = NULL; /* packet not ready yet */
3257                 goto next_rx;
3258             }
3259 
3260             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3261                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3262 
3263             queue = cqe->end_agg_cqe.queue_index;
3264             tpa_info = &fp->rx_tpa_info[queue];
3265 
3266             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3267                   fp->index, queue);
3268 
3269             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3270                          tpa_info->len_on_bd);
3271             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3272 
3273             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3274                          &cqe->end_agg_cqe, comp_ring_cons);
3275 
3276             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3277 
3278             goto next_cqe;
3279         }
3280 
3281         /* non TPA */
3282 
3283         /* is this an error packet? */
3284         if (__predict_false(cqe_fp_flags &
3285                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3286             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3287             fp->eth_q_stats.rx_soft_errors++;
3288             goto next_rx;
3289         }
3290 
3291         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3292         lenonbd = le16toh(cqe_fp->len_on_bd);
3293         pad = cqe_fp->placement_offset;
3294 
3295         m = rx_buf->m;
3296 
3297         if (__predict_false(m == NULL)) {
3298             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3299                   bd_cons, fp->index);
3300             goto next_rx;
3301         }
3302 
3303         /* XXX double copy if packet length under a threshold */
3304 
3305         /*
3306          * If all the buffer descriptors are filled with mbufs then fill in
3307          * the current consumer index with a new BD. Else if a maximum Rx
3308          * buffer limit is imposed then fill in the next producer index.
3309          */
3310         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3311                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3312                                       bd_prod : bd_cons);
3313         if (rc != 0) {
3314 
3315             /* we simply reuse the received mbuf and don't post it to the stack */
3316             m = NULL;
3317 
3318             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3319                   fp->index, rc);
3320             fp->eth_q_stats.rx_soft_errors++;
3321 
3322             if (sc->max_rx_bufs != RX_BD_USABLE) {
3323                 /* copy this consumer index to the producer index */
3324                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3325                        sizeof(struct bxe_sw_rx_bd));
3326                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3327             }
3328 
3329             goto next_rx;
3330         }
3331 
3332         /* current mbuf was detached from the bd */
3333         fp->eth_q_stats.mbuf_alloc_rx--;
3334 
3335         /* we allocated a replacement mbuf, fixup the current one */
3336         m_adj(m, pad);
3337         m->m_pkthdr.len = m->m_len = len;
3338 
3339         if ((len > 60) && (len > lenonbd)) {
3340             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3341             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3342             if (rc)
3343                 break;
3344             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3345         } else if (lenonbd < len) {
3346             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3347         }
3348 
3349         /* assign packet to this interface interface */
3350 	if_setrcvif(m, ifp);
3351 
3352         /* assume no hardware checksum has complated */
3353         m->m_pkthdr.csum_flags = 0;
3354 
3355         /* validate checksum if offload enabled */
3356         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3357             /* check for a valid IP frame */
3358             if (!(cqe->fast_path_cqe.status_flags &
3359                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3360                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3361                 if (__predict_false(cqe_fp_flags &
3362                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3363                     fp->eth_q_stats.rx_hw_csum_errors++;
3364                 } else {
3365                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3366                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3367                 }
3368             }
3369 
3370             /* check for a valid TCP/UDP frame */
3371             if (!(cqe->fast_path_cqe.status_flags &
3372                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3373                 if (__predict_false(cqe_fp_flags &
3374                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3375                     fp->eth_q_stats.rx_hw_csum_errors++;
3376                 } else {
3377                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3378                     m->m_pkthdr.csum_data = 0xFFFF;
3379                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3380                                                CSUM_PSEUDO_HDR);
3381                 }
3382             }
3383         }
3384 
3385         /* if there is a VLAN tag then flag that info */
3386         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3387             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3388             m->m_flags |= M_VLANTAG;
3389         }
3390 
3391 #if __FreeBSD_version >= 800000
3392         /* specify what RSS queue was used for this flow */
3393         m->m_pkthdr.flowid = fp->index;
3394         BXE_SET_FLOWID(m);
3395 #endif
3396 
3397 next_rx:
3398 
3399         bd_cons    = RX_BD_NEXT(bd_cons);
3400         bd_prod    = RX_BD_NEXT(bd_prod);
3401         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3402 
3403         /* pass the frame to the stack */
3404         if (__predict_true(m != NULL)) {
3405             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3406             rx_pkts++;
3407             if_input(ifp, m);
3408         }
3409 
3410 next_cqe:
3411 
3412         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3413         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3414 
3415         /* limit spinning on the queue */
3416         if (rc != 0)
3417             break;
3418 
3419         if (rx_pkts == sc->rx_budget) {
3420             fp->eth_q_stats.rx_budget_reached++;
3421             break;
3422         }
3423     } /* while work to do */
3424 
3425     fp->rx_bd_cons = bd_cons;
3426     fp->rx_bd_prod = bd_prod_fw;
3427     fp->rx_cq_cons = sw_cq_cons;
3428     fp->rx_cq_prod = sw_cq_prod;
3429 
3430     /* Update producers */
3431     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3432 
3433     fp->eth_q_stats.rx_pkts += rx_pkts;
3434     fp->eth_q_stats.rx_calls++;
3435 
3436     BXE_FP_RX_UNLOCK(fp);
3437 
3438     return (sw_cq_cons != hw_cq_cons);
3439 }
3440 
3441 static uint16_t
3442 bxe_free_tx_pkt(struct bxe_softc    *sc,
3443                 struct bxe_fastpath *fp,
3444                 uint16_t            idx)
3445 {
3446     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3447     struct eth_tx_start_bd *tx_start_bd;
3448     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3449     uint16_t new_cons;
3450     int nbd;
3451 
3452     /* unmap the mbuf from non-paged memory */
3453     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3454 
3455     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3456     nbd = le16toh(tx_start_bd->nbd) - 1;
3457 
3458     new_cons = (tx_buf->first_bd + nbd);
3459 
3460     /* free the mbuf */
3461     if (__predict_true(tx_buf->m != NULL)) {
3462         m_freem(tx_buf->m);
3463         fp->eth_q_stats.mbuf_alloc_tx--;
3464     } else {
3465         fp->eth_q_stats.tx_chain_lost_mbuf++;
3466     }
3467 
3468     tx_buf->m = NULL;
3469     tx_buf->first_bd = 0;
3470 
3471     return (new_cons);
3472 }
3473 
3474 /* transmit timeout watchdog */
3475 static int
3476 bxe_watchdog(struct bxe_softc    *sc,
3477              struct bxe_fastpath *fp)
3478 {
3479     BXE_FP_TX_LOCK(fp);
3480 
3481     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3482         BXE_FP_TX_UNLOCK(fp);
3483         return (0);
3484     }
3485 
3486     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3487     if(sc->trigger_grcdump) {
3488          /* taking grcdump */
3489          bxe_grc_dump(sc);
3490     }
3491 
3492     BXE_FP_TX_UNLOCK(fp);
3493 
3494     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3495     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3496 
3497     return (-1);
3498 }
3499 
3500 /* processes transmit completions */
3501 static uint8_t
3502 bxe_txeof(struct bxe_softc    *sc,
3503           struct bxe_fastpath *fp)
3504 {
3505     if_t ifp = sc->ifp;
3506     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3507     uint16_t tx_bd_avail;
3508 
3509     BXE_FP_TX_LOCK_ASSERT(fp);
3510 
3511     bd_cons = fp->tx_bd_cons;
3512     hw_cons = le16toh(*fp->tx_cons_sb);
3513     sw_cons = fp->tx_pkt_cons;
3514 
3515     while (sw_cons != hw_cons) {
3516         pkt_cons = TX_BD(sw_cons);
3517 
3518         BLOGD(sc, DBG_TX,
3519               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3520               fp->index, hw_cons, sw_cons, pkt_cons);
3521 
3522         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3523 
3524         sw_cons++;
3525     }
3526 
3527     fp->tx_pkt_cons = sw_cons;
3528     fp->tx_bd_cons  = bd_cons;
3529 
3530     BLOGD(sc, DBG_TX,
3531           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3532           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3533 
3534     mb();
3535 
3536     tx_bd_avail = bxe_tx_avail(sc, fp);
3537 
3538     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3539         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3540     } else {
3541         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3542     }
3543 
3544     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3545         /* reset the watchdog timer if there are pending transmits */
3546         fp->watchdog_timer = BXE_TX_TIMEOUT;
3547         return (TRUE);
3548     } else {
3549         /* clear watchdog when there are no pending transmits */
3550         fp->watchdog_timer = 0;
3551         return (FALSE);
3552     }
3553 }
3554 
3555 static void
3556 bxe_drain_tx_queues(struct bxe_softc *sc)
3557 {
3558     struct bxe_fastpath *fp;
3559     int i, count;
3560 
3561     /* wait until all TX fastpath tasks have completed */
3562     for (i = 0; i < sc->num_queues; i++) {
3563         fp = &sc->fp[i];
3564 
3565         count = 1000;
3566 
3567         while (bxe_has_tx_work(fp)) {
3568 
3569             BXE_FP_TX_LOCK(fp);
3570             bxe_txeof(sc, fp);
3571             BXE_FP_TX_UNLOCK(fp);
3572 
3573             if (count == 0) {
3574                 BLOGE(sc, "Timeout waiting for fp[%d] "
3575                           "transmits to complete!\n", i);
3576                 bxe_panic(sc, ("tx drain failure\n"));
3577                 return;
3578             }
3579 
3580             count--;
3581             DELAY(1000);
3582             rmb();
3583         }
3584     }
3585 
3586     return;
3587 }
3588 
3589 static int
3590 bxe_del_all_macs(struct bxe_softc          *sc,
3591                  struct ecore_vlan_mac_obj *mac_obj,
3592                  int                       mac_type,
3593                  uint8_t                   wait_for_comp)
3594 {
3595     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3596     int rc;
3597 
3598     /* wait for completion of requested */
3599     if (wait_for_comp) {
3600         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3601     }
3602 
3603     /* Set the mac type of addresses we want to clear */
3604     bxe_set_bit(mac_type, &vlan_mac_flags);
3605 
3606     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3607     if (rc < 0) {
3608         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3609             rc, mac_type, wait_for_comp);
3610     }
3611 
3612     return (rc);
3613 }
3614 
3615 static int
3616 bxe_fill_accept_flags(struct bxe_softc *sc,
3617                       uint32_t         rx_mode,
3618                       unsigned long    *rx_accept_flags,
3619                       unsigned long    *tx_accept_flags)
3620 {
3621     /* Clear the flags first */
3622     *rx_accept_flags = 0;
3623     *tx_accept_flags = 0;
3624 
3625     switch (rx_mode) {
3626     case BXE_RX_MODE_NONE:
3627         /*
3628          * 'drop all' supersedes any accept flags that may have been
3629          * passed to the function.
3630          */
3631         break;
3632 
3633     case BXE_RX_MODE_NORMAL:
3634         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3635         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3636         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3637 
3638         /* internal switching mode */
3639         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3640         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3641         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3642 
3643         break;
3644 
3645     case BXE_RX_MODE_ALLMULTI:
3646         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3647         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3648         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3649 
3650         /* internal switching mode */
3651         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3652         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3653         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3654 
3655         break;
3656 
3657     case BXE_RX_MODE_PROMISC:
3658         /*
3659          * According to deffinition of SI mode, iface in promisc mode
3660          * should receive matched and unmatched (in resolution of port)
3661          * unicast packets.
3662          */
3663         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3664         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3665         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3666         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3667 
3668         /* internal switching mode */
3669         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3670         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3671 
3672         if (IS_MF_SI(sc)) {
3673             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3674         } else {
3675             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3676         }
3677 
3678         break;
3679 
3680     default:
3681         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3682         return (-1);
3683     }
3684 
3685     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3686     if (rx_mode != BXE_RX_MODE_NONE) {
3687         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3688         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3689     }
3690 
3691     return (0);
3692 }
3693 
3694 static int
3695 bxe_set_q_rx_mode(struct bxe_softc *sc,
3696                   uint8_t          cl_id,
3697                   unsigned long    rx_mode_flags,
3698                   unsigned long    rx_accept_flags,
3699                   unsigned long    tx_accept_flags,
3700                   unsigned long    ramrod_flags)
3701 {
3702     struct ecore_rx_mode_ramrod_params ramrod_param;
3703     int rc;
3704 
3705     memset(&ramrod_param, 0, sizeof(ramrod_param));
3706 
3707     /* Prepare ramrod parameters */
3708     ramrod_param.cid = 0;
3709     ramrod_param.cl_id = cl_id;
3710     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3711     ramrod_param.func_id = SC_FUNC(sc);
3712 
3713     ramrod_param.pstate = &sc->sp_state;
3714     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3715 
3716     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3717     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3718 
3719     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3720 
3721     ramrod_param.ramrod_flags = ramrod_flags;
3722     ramrod_param.rx_mode_flags = rx_mode_flags;
3723 
3724     ramrod_param.rx_accept_flags = rx_accept_flags;
3725     ramrod_param.tx_accept_flags = tx_accept_flags;
3726 
3727     rc = ecore_config_rx_mode(sc, &ramrod_param);
3728     if (rc < 0) {
3729         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3730             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3731             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3732             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3733             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3734         return (rc);
3735     }
3736 
3737     return (0);
3738 }
3739 
3740 static int
3741 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3742 {
3743     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3744     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3745     int rc;
3746 
3747     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3748                                &tx_accept_flags);
3749     if (rc) {
3750         return (rc);
3751     }
3752 
3753     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3754     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3755 
3756     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3757     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3758                               rx_accept_flags, tx_accept_flags,
3759                               ramrod_flags));
3760 }
3761 
3762 /* returns the "mcp load_code" according to global load_count array */
3763 static int
3764 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3765 {
3766     int path = SC_PATH(sc);
3767     int port = SC_PORT(sc);
3768 
3769     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3770           path, load_count[path][0], load_count[path][1],
3771           load_count[path][2]);
3772     load_count[path][0]++;
3773     load_count[path][1 + port]++;
3774     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3775           path, load_count[path][0], load_count[path][1],
3776           load_count[path][2]);
3777     if (load_count[path][0] == 1) {
3778         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3779     } else if (load_count[path][1 + port] == 1) {
3780         return (FW_MSG_CODE_DRV_LOAD_PORT);
3781     } else {
3782         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3783     }
3784 }
3785 
3786 /* returns the "mcp load_code" according to global load_count array */
3787 static int
3788 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3789 {
3790     int port = SC_PORT(sc);
3791     int path = SC_PATH(sc);
3792 
3793     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3794           path, load_count[path][0], load_count[path][1],
3795           load_count[path][2]);
3796     load_count[path][0]--;
3797     load_count[path][1 + port]--;
3798     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3799           path, load_count[path][0], load_count[path][1],
3800           load_count[path][2]);
3801     if (load_count[path][0] == 0) {
3802         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3803     } else if (load_count[path][1 + port] == 0) {
3804         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3805     } else {
3806         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3807     }
3808 }
3809 
3810 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3811 static uint32_t
3812 bxe_send_unload_req(struct bxe_softc *sc,
3813                     int              unload_mode)
3814 {
3815     uint32_t reset_code = 0;
3816 
3817     /* Select the UNLOAD request mode */
3818     if (unload_mode == UNLOAD_NORMAL) {
3819         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3820     } else {
3821         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3822     }
3823 
3824     /* Send the request to the MCP */
3825     if (!BXE_NOMCP(sc)) {
3826         reset_code = bxe_fw_command(sc, reset_code, 0);
3827     } else {
3828         reset_code = bxe_nic_unload_no_mcp(sc);
3829     }
3830 
3831     return (reset_code);
3832 }
3833 
3834 /* send UNLOAD_DONE command to the MCP */
3835 static void
3836 bxe_send_unload_done(struct bxe_softc *sc,
3837                      uint8_t          keep_link)
3838 {
3839     uint32_t reset_param =
3840         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3841 
3842     /* Report UNLOAD_DONE to MCP */
3843     if (!BXE_NOMCP(sc)) {
3844         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3845     }
3846 }
3847 
3848 static int
3849 bxe_func_wait_started(struct bxe_softc *sc)
3850 {
3851     int tout = 50;
3852 
3853     if (!sc->port.pmf) {
3854         return (0);
3855     }
3856 
3857     /*
3858      * (assumption: No Attention from MCP at this stage)
3859      * PMF probably in the middle of TX disable/enable transaction
3860      * 1. Sync IRS for default SB
3861      * 2. Sync SP queue - this guarantees us that attention handling started
3862      * 3. Wait, that TX disable/enable transaction completes
3863      *
3864      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3865      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3866      * received completion for the transaction the state is TX_STOPPED.
3867      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3868      * transaction.
3869      */
3870 
3871     /* XXX make sure default SB ISR is done */
3872     /* need a way to synchronize an irq (intr_mtx?) */
3873 
3874     /* XXX flush any work queues */
3875 
3876     while (ecore_func_get_state(sc, &sc->func_obj) !=
3877            ECORE_F_STATE_STARTED && tout--) {
3878         DELAY(20000);
3879     }
3880 
3881     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3882         /*
3883          * Failed to complete the transaction in a "good way"
3884          * Force both transactions with CLR bit.
3885          */
3886         struct ecore_func_state_params func_params = { NULL };
3887 
3888         BLOGE(sc, "Unexpected function state! "
3889                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3890 
3891         func_params.f_obj = &sc->func_obj;
3892         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3893 
3894         /* STARTED-->TX_STOPPED */
3895         func_params.cmd = ECORE_F_CMD_TX_STOP;
3896         ecore_func_state_change(sc, &func_params);
3897 
3898         /* TX_STOPPED-->STARTED */
3899         func_params.cmd = ECORE_F_CMD_TX_START;
3900         return (ecore_func_state_change(sc, &func_params));
3901     }
3902 
3903     return (0);
3904 }
3905 
3906 static int
3907 bxe_stop_queue(struct bxe_softc *sc,
3908                int              index)
3909 {
3910     struct bxe_fastpath *fp = &sc->fp[index];
3911     struct ecore_queue_state_params q_params = { NULL };
3912     int rc;
3913 
3914     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3915 
3916     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3917     /* We want to wait for completion in this context */
3918     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3919 
3920     /* Stop the primary connection: */
3921 
3922     /* ...halt the connection */
3923     q_params.cmd = ECORE_Q_CMD_HALT;
3924     rc = ecore_queue_state_change(sc, &q_params);
3925     if (rc) {
3926         return (rc);
3927     }
3928 
3929     /* ...terminate the connection */
3930     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3931     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3932     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3933     rc = ecore_queue_state_change(sc, &q_params);
3934     if (rc) {
3935         return (rc);
3936     }
3937 
3938     /* ...delete cfc entry */
3939     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3940     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3941     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3942     return (ecore_queue_state_change(sc, &q_params));
3943 }
3944 
3945 /* wait for the outstanding SP commands */
3946 static inline uint8_t
3947 bxe_wait_sp_comp(struct bxe_softc *sc,
3948                  unsigned long    mask)
3949 {
3950     unsigned long tmp;
3951     int tout = 5000; /* wait for 5 secs tops */
3952 
3953     while (tout--) {
3954         mb();
3955         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3956             return (TRUE);
3957         }
3958 
3959         DELAY(1000);
3960     }
3961 
3962     mb();
3963 
3964     tmp = atomic_load_acq_long(&sc->sp_state);
3965     if (tmp & mask) {
3966         BLOGE(sc, "Filtering completion timed out: "
3967                   "sp_state 0x%lx, mask 0x%lx\n",
3968               tmp, mask);
3969         return (FALSE);
3970     }
3971 
3972     return (FALSE);
3973 }
3974 
3975 static int
3976 bxe_func_stop(struct bxe_softc *sc)
3977 {
3978     struct ecore_func_state_params func_params = { NULL };
3979     int rc;
3980 
3981     /* prepare parameters for function state transitions */
3982     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3983     func_params.f_obj = &sc->func_obj;
3984     func_params.cmd = ECORE_F_CMD_STOP;
3985 
3986     /*
3987      * Try to stop the function the 'good way'. If it fails (in case
3988      * of a parity error during bxe_chip_cleanup()) and we are
3989      * not in a debug mode, perform a state transaction in order to
3990      * enable further HW_RESET transaction.
3991      */
3992     rc = ecore_func_state_change(sc, &func_params);
3993     if (rc) {
3994         BLOGE(sc, "FUNC_STOP ramrod failed. "
3995                   "Running a dry transaction (%d)\n", rc);
3996         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3997         return (ecore_func_state_change(sc, &func_params));
3998     }
3999 
4000     return (0);
4001 }
4002 
4003 static int
4004 bxe_reset_hw(struct bxe_softc *sc,
4005              uint32_t         load_code)
4006 {
4007     struct ecore_func_state_params func_params = { NULL };
4008 
4009     /* Prepare parameters for function state transitions */
4010     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4011 
4012     func_params.f_obj = &sc->func_obj;
4013     func_params.cmd = ECORE_F_CMD_HW_RESET;
4014 
4015     func_params.params.hw_init.load_phase = load_code;
4016 
4017     return (ecore_func_state_change(sc, &func_params));
4018 }
4019 
4020 static void
4021 bxe_int_disable_sync(struct bxe_softc *sc,
4022                      int              disable_hw)
4023 {
4024     if (disable_hw) {
4025         /* prevent the HW from sending interrupts */
4026         bxe_int_disable(sc);
4027     }
4028 
4029     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4030     /* make sure all ISRs are done */
4031 
4032     /* XXX make sure sp_task is not running */
4033     /* cancel and flush work queues */
4034 }
4035 
4036 static void
4037 bxe_chip_cleanup(struct bxe_softc *sc,
4038                  uint32_t         unload_mode,
4039                  uint8_t          keep_link)
4040 {
4041     int port = SC_PORT(sc);
4042     struct ecore_mcast_ramrod_params rparam = { NULL };
4043     uint32_t reset_code;
4044     int i, rc = 0;
4045 
4046     bxe_drain_tx_queues(sc);
4047 
4048     /* give HW time to discard old tx messages */
4049     DELAY(1000);
4050 
4051     /* Clean all ETH MACs */
4052     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4053     if (rc < 0) {
4054         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4055     }
4056 
4057     /* Clean up UC list  */
4058     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4059     if (rc < 0) {
4060         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4061     }
4062 
4063     /* Disable LLH */
4064     if (!CHIP_IS_E1(sc)) {
4065         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4066     }
4067 
4068     /* Set "drop all" to stop Rx */
4069 
4070     /*
4071      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4072      * a race between the completion code and this code.
4073      */
4074     BXE_MCAST_LOCK(sc);
4075 
4076     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4077         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4078     } else {
4079         bxe_set_storm_rx_mode(sc);
4080     }
4081 
4082     /* Clean up multicast configuration */
4083     rparam.mcast_obj = &sc->mcast_obj;
4084     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4085     if (rc < 0) {
4086         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4087     }
4088 
4089     BXE_MCAST_UNLOCK(sc);
4090 
4091     // XXX bxe_iov_chip_cleanup(sc);
4092 
4093     /*
4094      * Send the UNLOAD_REQUEST to the MCP. This will return if
4095      * this function should perform FUNCTION, PORT, or COMMON HW
4096      * reset.
4097      */
4098     reset_code = bxe_send_unload_req(sc, unload_mode);
4099 
4100     /*
4101      * (assumption: No Attention from MCP at this stage)
4102      * PMF probably in the middle of TX disable/enable transaction
4103      */
4104     rc = bxe_func_wait_started(sc);
4105     if (rc) {
4106         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4107     }
4108 
4109     /*
4110      * Close multi and leading connections
4111      * Completions for ramrods are collected in a synchronous way
4112      */
4113     for (i = 0; i < sc->num_queues; i++) {
4114         if (bxe_stop_queue(sc, i)) {
4115             goto unload_error;
4116         }
4117     }
4118 
4119     /*
4120      * If SP settings didn't get completed so far - something
4121      * very wrong has happen.
4122      */
4123     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4124         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4125     }
4126 
4127 unload_error:
4128 
4129     rc = bxe_func_stop(sc);
4130     if (rc) {
4131         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4132     }
4133 
4134     /* disable HW interrupts */
4135     bxe_int_disable_sync(sc, TRUE);
4136 
4137     /* detach interrupts */
4138     bxe_interrupt_detach(sc);
4139 
4140     /* Reset the chip */
4141     rc = bxe_reset_hw(sc, reset_code);
4142     if (rc) {
4143         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4144     }
4145 
4146     /* Report UNLOAD_DONE to MCP */
4147     bxe_send_unload_done(sc, keep_link);
4148 }
4149 
4150 static void
4151 bxe_disable_close_the_gate(struct bxe_softc *sc)
4152 {
4153     uint32_t val;
4154     int port = SC_PORT(sc);
4155 
4156     BLOGD(sc, DBG_LOAD,
4157           "Disabling 'close the gates'\n");
4158 
4159     if (CHIP_IS_E1(sc)) {
4160         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4161                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4162         val = REG_RD(sc, addr);
4163         val &= ~(0x300);
4164         REG_WR(sc, addr, val);
4165     } else {
4166         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4167         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4168                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4169         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4170     }
4171 }
4172 
4173 /*
4174  * Cleans the object that have internal lists without sending
4175  * ramrods. Should be run when interrutps are disabled.
4176  */
4177 static void
4178 bxe_squeeze_objects(struct bxe_softc *sc)
4179 {
4180     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4181     struct ecore_mcast_ramrod_params rparam = { NULL };
4182     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4183     int rc;
4184 
4185     /* Cleanup MACs' object first... */
4186 
4187     /* Wait for completion of requested */
4188     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4189     /* Perform a dry cleanup */
4190     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4191 
4192     /* Clean ETH primary MAC */
4193     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4194     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4195                              &ramrod_flags);
4196     if (rc != 0) {
4197         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4198     }
4199 
4200     /* Cleanup UC list */
4201     vlan_mac_flags = 0;
4202     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4203     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4204                              &ramrod_flags);
4205     if (rc != 0) {
4206         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4207     }
4208 
4209     /* Now clean mcast object... */
4210 
4211     rparam.mcast_obj = &sc->mcast_obj;
4212     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4213 
4214     /* Add a DEL command... */
4215     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4216     if (rc < 0) {
4217         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4218     }
4219 
4220     /* now wait until all pending commands are cleared */
4221 
4222     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4223     while (rc != 0) {
4224         if (rc < 0) {
4225             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4226             return;
4227         }
4228 
4229         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4230     }
4231 }
4232 
4233 /* stop the controller */
4234 static __noinline int
4235 bxe_nic_unload(struct bxe_softc *sc,
4236                uint32_t         unload_mode,
4237                uint8_t          keep_link)
4238 {
4239     uint8_t global = FALSE;
4240     uint32_t val;
4241     int i;
4242 
4243     BXE_CORE_LOCK_ASSERT(sc);
4244 
4245     if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4246 
4247     for (i = 0; i < sc->num_queues; i++) {
4248         struct bxe_fastpath *fp;
4249 
4250         fp = &sc->fp[i];
4251         BXE_FP_TX_LOCK(fp);
4252         BXE_FP_TX_UNLOCK(fp);
4253     }
4254 
4255     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4256 
4257     /* mark driver as unloaded in shmem2 */
4258     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4259         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4260         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4261                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4262     }
4263 
4264     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4265         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4266         /*
4267          * We can get here if the driver has been unloaded
4268          * during parity error recovery and is either waiting for a
4269          * leader to complete or for other functions to unload and
4270          * then ifconfig down has been issued. In this case we want to
4271          * unload and let other functions to complete a recovery
4272          * process.
4273          */
4274         sc->recovery_state = BXE_RECOVERY_DONE;
4275         sc->is_leader = 0;
4276         bxe_release_leader_lock(sc);
4277         mb();
4278 
4279         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4280         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4281             " state = 0x%x\n", sc->recovery_state, sc->state);
4282         return (-1);
4283     }
4284 
4285     /*
4286      * Nothing to do during unload if previous bxe_nic_load()
4287      * did not completed successfully - all resourses are released.
4288      */
4289     if ((sc->state == BXE_STATE_CLOSED) ||
4290         (sc->state == BXE_STATE_ERROR)) {
4291         return (0);
4292     }
4293 
4294     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4295     mb();
4296 
4297     /* stop tx */
4298     bxe_tx_disable(sc);
4299 
4300     sc->rx_mode = BXE_RX_MODE_NONE;
4301     /* XXX set rx mode ??? */
4302 
4303     if (IS_PF(sc) && !sc->grcdump_done) {
4304         /* set ALWAYS_ALIVE bit in shmem */
4305         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4306 
4307         bxe_drv_pulse(sc);
4308 
4309         bxe_stats_handle(sc, STATS_EVENT_STOP);
4310         bxe_save_statistics(sc);
4311     }
4312 
4313     /* wait till consumers catch up with producers in all queues */
4314     bxe_drain_tx_queues(sc);
4315 
4316     /* if VF indicate to PF this function is going down (PF will delete sp
4317      * elements and clear initializations
4318      */
4319     if (IS_VF(sc)) {
4320         ; /* bxe_vfpf_close_vf(sc); */
4321     } else if (unload_mode != UNLOAD_RECOVERY) {
4322         /* if this is a normal/close unload need to clean up chip */
4323         if (!sc->grcdump_done)
4324             bxe_chip_cleanup(sc, unload_mode, keep_link);
4325     } else {
4326         /* Send the UNLOAD_REQUEST to the MCP */
4327         bxe_send_unload_req(sc, unload_mode);
4328 
4329         /*
4330          * Prevent transactions to host from the functions on the
4331          * engine that doesn't reset global blocks in case of global
4332          * attention once gloabl blocks are reset and gates are opened
4333          * (the engine which leader will perform the recovery
4334          * last).
4335          */
4336         if (!CHIP_IS_E1x(sc)) {
4337             bxe_pf_disable(sc);
4338         }
4339 
4340         /* disable HW interrupts */
4341         bxe_int_disable_sync(sc, TRUE);
4342 
4343         /* detach interrupts */
4344         bxe_interrupt_detach(sc);
4345 
4346         /* Report UNLOAD_DONE to MCP */
4347         bxe_send_unload_done(sc, FALSE);
4348     }
4349 
4350     /*
4351      * At this stage no more interrupts will arrive so we may safely clean
4352      * the queue'able objects here in case they failed to get cleaned so far.
4353      */
4354     if (IS_PF(sc)) {
4355         bxe_squeeze_objects(sc);
4356     }
4357 
4358     /* There should be no more pending SP commands at this stage */
4359     sc->sp_state = 0;
4360 
4361     sc->port.pmf = 0;
4362 
4363     bxe_free_fp_buffers(sc);
4364 
4365     if (IS_PF(sc)) {
4366         bxe_free_mem(sc);
4367     }
4368 
4369     bxe_free_fw_stats_mem(sc);
4370 
4371     sc->state = BXE_STATE_CLOSED;
4372 
4373     /*
4374      * Check if there are pending parity attentions. If there are - set
4375      * RECOVERY_IN_PROGRESS.
4376      */
4377     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4378         bxe_set_reset_in_progress(sc);
4379 
4380         /* Set RESET_IS_GLOBAL if needed */
4381         if (global) {
4382             bxe_set_reset_global(sc);
4383         }
4384     }
4385 
4386     /*
4387      * The last driver must disable a "close the gate" if there is no
4388      * parity attention or "process kill" pending.
4389      */
4390     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4391         bxe_reset_is_done(sc, SC_PATH(sc))) {
4392         bxe_disable_close_the_gate(sc);
4393     }
4394 
4395     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4396 
4397     return (0);
4398 }
4399 
4400 /*
4401  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4402  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4403  */
4404 static int
4405 bxe_ifmedia_update(struct ifnet  *ifp)
4406 {
4407     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4408     struct ifmedia *ifm;
4409 
4410     ifm = &sc->ifmedia;
4411 
4412     /* We only support Ethernet media type. */
4413     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4414         return (EINVAL);
4415     }
4416 
4417     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4418     case IFM_AUTO:
4419          break;
4420     case IFM_10G_CX4:
4421     case IFM_10G_SR:
4422     case IFM_10G_T:
4423     case IFM_10G_TWINAX:
4424     default:
4425         /* We don't support changing the media type. */
4426         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4427               IFM_SUBTYPE(ifm->ifm_media));
4428         return (EINVAL);
4429     }
4430 
4431     return (0);
4432 }
4433 
4434 /*
4435  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4436  */
4437 static void
4438 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4439 {
4440     struct bxe_softc *sc = if_getsoftc(ifp);
4441 
4442     /* Report link down if the driver isn't running. */
4443     if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4444         ifmr->ifm_active |= IFM_NONE;
4445         return;
4446     }
4447 
4448     /* Setup the default interface info. */
4449     ifmr->ifm_status = IFM_AVALID;
4450     ifmr->ifm_active = IFM_ETHER;
4451 
4452     if (sc->link_vars.link_up) {
4453         ifmr->ifm_status |= IFM_ACTIVE;
4454     } else {
4455         ifmr->ifm_active |= IFM_NONE;
4456         return;
4457     }
4458 
4459     ifmr->ifm_active |= sc->media;
4460 
4461     if (sc->link_vars.duplex == DUPLEX_FULL) {
4462         ifmr->ifm_active |= IFM_FDX;
4463     } else {
4464         ifmr->ifm_active |= IFM_HDX;
4465     }
4466 }
4467 
4468 static void
4469 bxe_handle_chip_tq(void *context,
4470                    int  pending)
4471 {
4472     struct bxe_softc *sc = (struct bxe_softc *)context;
4473     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4474 
4475     switch (work)
4476     {
4477 
4478     case CHIP_TQ_REINIT:
4479         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4480             /* restart the interface */
4481             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4482             bxe_periodic_stop(sc);
4483             BXE_CORE_LOCK(sc);
4484             bxe_stop_locked(sc);
4485             bxe_init_locked(sc);
4486             BXE_CORE_UNLOCK(sc);
4487         }
4488         break;
4489 
4490     default:
4491         break;
4492     }
4493 }
4494 
4495 /*
4496  * Handles any IOCTL calls from the operating system.
4497  *
4498  * Returns:
4499  *   0 = Success, >0 Failure
4500  */
4501 static int
4502 bxe_ioctl(if_t ifp,
4503           u_long       command,
4504           caddr_t      data)
4505 {
4506     struct bxe_softc *sc = if_getsoftc(ifp);
4507     struct ifreq *ifr = (struct ifreq *)data;
4508     int mask = 0;
4509     int reinit = 0;
4510     int error = 0;
4511 
4512     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4513     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4514 
4515     switch (command)
4516     {
4517     case SIOCSIFMTU:
4518         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4519               ifr->ifr_mtu);
4520 
4521         if (sc->mtu == ifr->ifr_mtu) {
4522             /* nothing to change */
4523             break;
4524         }
4525 
4526         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4527             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4528                   ifr->ifr_mtu, mtu_min, mtu_max);
4529             error = EINVAL;
4530             break;
4531         }
4532 
4533         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4534                              (unsigned long)ifr->ifr_mtu);
4535 	/*
4536         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4537                               (unsigned long)ifr->ifr_mtu);
4538 	XXX - Not sure why it needs to be atomic
4539 	*/
4540 	if_setmtu(ifp, ifr->ifr_mtu);
4541         reinit = 1;
4542         break;
4543 
4544     case SIOCSIFFLAGS:
4545         /* toggle the interface state up or down */
4546         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4547 
4548 	BXE_CORE_LOCK(sc);
4549         /* check if the interface is up */
4550         if (if_getflags(ifp) & IFF_UP) {
4551             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4552                 /* set the receive mode flags */
4553                 bxe_set_rx_mode(sc);
4554             } else if(sc->state != BXE_STATE_DISABLED) {
4555 		bxe_init_locked(sc);
4556             }
4557         } else {
4558             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4559 		bxe_periodic_stop(sc);
4560 		bxe_stop_locked(sc);
4561             }
4562         }
4563 	BXE_CORE_UNLOCK(sc);
4564 
4565         break;
4566 
4567     case SIOCADDMULTI:
4568     case SIOCDELMULTI:
4569         /* add/delete multicast addresses */
4570         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4571 
4572         /* check if the interface is up */
4573         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4574             /* set the receive mode flags */
4575 	    BXE_CORE_LOCK(sc);
4576             bxe_set_rx_mode(sc);
4577 	    BXE_CORE_UNLOCK(sc);
4578         }
4579 
4580         break;
4581 
4582     case SIOCSIFCAP:
4583         /* find out which capabilities have changed */
4584         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4585 
4586         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4587               mask);
4588 
4589         /* toggle the LRO capabilites enable flag */
4590         if (mask & IFCAP_LRO) {
4591 	    if_togglecapenable(ifp, IFCAP_LRO);
4592             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4593                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4594             reinit = 1;
4595         }
4596 
4597         /* toggle the TXCSUM checksum capabilites enable flag */
4598         if (mask & IFCAP_TXCSUM) {
4599 	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4600             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4601                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4602             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4603                 if_sethwassistbits(ifp, (CSUM_IP      |
4604                                     CSUM_TCP      |
4605                                     CSUM_UDP      |
4606                                     CSUM_TSO      |
4607                                     CSUM_TCP_IPV6 |
4608                                     CSUM_UDP_IPV6), 0);
4609             } else {
4610 		if_clearhwassist(ifp); /* XXX */
4611             }
4612         }
4613 
4614         /* toggle the RXCSUM checksum capabilities enable flag */
4615         if (mask & IFCAP_RXCSUM) {
4616 	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4617             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4618                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4619             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4620                 if_sethwassistbits(ifp, (CSUM_IP      |
4621                                     CSUM_TCP      |
4622                                     CSUM_UDP      |
4623                                     CSUM_TSO      |
4624                                     CSUM_TCP_IPV6 |
4625                                     CSUM_UDP_IPV6), 0);
4626             } else {
4627 		if_clearhwassist(ifp); /* XXX */
4628             }
4629         }
4630 
4631         /* toggle TSO4 capabilities enabled flag */
4632         if (mask & IFCAP_TSO4) {
4633             if_togglecapenable(ifp, IFCAP_TSO4);
4634             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4635                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4636         }
4637 
4638         /* toggle TSO6 capabilities enabled flag */
4639         if (mask & IFCAP_TSO6) {
4640 	    if_togglecapenable(ifp, IFCAP_TSO6);
4641             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4642                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4643         }
4644 
4645         /* toggle VLAN_HWTSO capabilities enabled flag */
4646         if (mask & IFCAP_VLAN_HWTSO) {
4647 
4648 	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4649             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4650                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4651         }
4652 
4653         /* toggle VLAN_HWCSUM capabilities enabled flag */
4654         if (mask & IFCAP_VLAN_HWCSUM) {
4655             /* XXX investigate this... */
4656             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4657             error = EINVAL;
4658         }
4659 
4660         /* toggle VLAN_MTU capabilities enable flag */
4661         if (mask & IFCAP_VLAN_MTU) {
4662             /* XXX investigate this... */
4663             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4664             error = EINVAL;
4665         }
4666 
4667         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4668         if (mask & IFCAP_VLAN_HWTAGGING) {
4669             /* XXX investigate this... */
4670             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4671             error = EINVAL;
4672         }
4673 
4674         /* toggle VLAN_HWFILTER capabilities enabled flag */
4675         if (mask & IFCAP_VLAN_HWFILTER) {
4676             /* XXX investigate this... */
4677             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4678             error = EINVAL;
4679         }
4680 
4681         /* XXX not yet...
4682          * IFCAP_WOL_MAGIC
4683          */
4684 
4685         break;
4686 
4687     case SIOCSIFMEDIA:
4688     case SIOCGIFMEDIA:
4689         /* set/get interface media */
4690         BLOGD(sc, DBG_IOCTL,
4691               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4692               (command & 0xff));
4693         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4694         break;
4695 
4696     default:
4697         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4698               (command & 0xff));
4699         error = ether_ioctl(ifp, command, data);
4700         break;
4701     }
4702 
4703     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4704         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4705               "Re-initializing hardware from IOCTL change\n");
4706 	bxe_periodic_stop(sc);
4707 	BXE_CORE_LOCK(sc);
4708 	bxe_stop_locked(sc);
4709 	bxe_init_locked(sc);
4710 	BXE_CORE_UNLOCK(sc);
4711     }
4712 
4713     return (error);
4714 }
4715 
4716 static __noinline void
4717 bxe_dump_mbuf(struct bxe_softc *sc,
4718               struct mbuf      *m,
4719               uint8_t          contents)
4720 {
4721     char * type;
4722     int i = 0;
4723 
4724     if (!(sc->debug & DBG_MBUF)) {
4725         return;
4726     }
4727 
4728     if (m == NULL) {
4729         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4730         return;
4731     }
4732 
4733     while (m) {
4734 
4735 #if __FreeBSD_version >= 1000000
4736         BLOGD(sc, DBG_MBUF,
4737               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4738               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4739 
4740         if (m->m_flags & M_PKTHDR) {
4741              BLOGD(sc, DBG_MBUF,
4742                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4743                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4744                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4745         }
4746 #else
4747         BLOGD(sc, DBG_MBUF,
4748               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4749               i, m, m->m_len, m->m_flags,
4750               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4751 
4752         if (m->m_flags & M_PKTHDR) {
4753              BLOGD(sc, DBG_MBUF,
4754                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4755                    i, m->m_pkthdr.len, m->m_flags,
4756                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4757                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4758                    "\22M_PROMISC\23M_NOFREE",
4759                    (int)m->m_pkthdr.csum_flags,
4760                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4761                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4762                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4763                    "\14CSUM_PSEUDO_HDR");
4764         }
4765 #endif /* #if __FreeBSD_version >= 1000000 */
4766 
4767         if (m->m_flags & M_EXT) {
4768             switch (m->m_ext.ext_type) {
4769             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4770             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4771             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4772             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4773             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4774             case EXT_PACKET:     type = "EXT_PACKET";     break;
4775             case EXT_MBUF:       type = "EXT_MBUF";       break;
4776             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4777             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4778             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4779             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4780             default:             type = "UNKNOWN";        break;
4781             }
4782 
4783             BLOGD(sc, DBG_MBUF,
4784                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4785                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4786         }
4787 
4788         if (contents) {
4789             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4790         }
4791 
4792         m = m->m_next;
4793         i++;
4794     }
4795 }
4796 
4797 /*
4798  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4799  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4800  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4801  * The headers comes in a separate bd in FreeBSD so 13-3=10.
4802  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4803  */
4804 static int
4805 bxe_chktso_window(struct bxe_softc  *sc,
4806                   int               nsegs,
4807                   bus_dma_segment_t *segs,
4808                   struct mbuf       *m)
4809 {
4810     uint32_t num_wnds, wnd_size, wnd_sum;
4811     int32_t frag_idx, wnd_idx;
4812     unsigned short lso_mss;
4813     int defrag;
4814 
4815     defrag = 0;
4816     wnd_sum = 0;
4817     wnd_size = 10;
4818     num_wnds = nsegs - wnd_size;
4819     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4820 
4821     /*
4822      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4823      * first window sum of data while skipping the first assuming it is the
4824      * header in FreeBSD.
4825      */
4826     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4827         wnd_sum += htole16(segs[frag_idx].ds_len);
4828     }
4829 
4830     /* check the first 10 bd window size */
4831     if (wnd_sum < lso_mss) {
4832         return (1);
4833     }
4834 
4835     /* run through the windows */
4836     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4837         /* subtract the first mbuf->m_len of the last wndw(-header) */
4838         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4839         /* add the next mbuf len to the len of our new window */
4840         wnd_sum += htole16(segs[frag_idx].ds_len);
4841         if (wnd_sum < lso_mss) {
4842             return (1);
4843         }
4844     }
4845 
4846     return (0);
4847 }
4848 
4849 static uint8_t
4850 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4851                     struct mbuf         *m,
4852                     uint32_t            *parsing_data)
4853 {
4854     struct ether_vlan_header *eh = NULL;
4855     struct ip *ip4 = NULL;
4856     struct ip6_hdr *ip6 = NULL;
4857     caddr_t ip = NULL;
4858     struct tcphdr *th = NULL;
4859     int e_hlen, ip_hlen, l4_off;
4860     uint16_t proto;
4861 
4862     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4863         /* no L4 checksum offload needed */
4864         return (0);
4865     }
4866 
4867     /* get the Ethernet header */
4868     eh = mtod(m, struct ether_vlan_header *);
4869 
4870     /* handle VLAN encapsulation if present */
4871     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4872         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4873         proto  = ntohs(eh->evl_proto);
4874     } else {
4875         e_hlen = ETHER_HDR_LEN;
4876         proto  = ntohs(eh->evl_encap_proto);
4877     }
4878 
4879     switch (proto) {
4880     case ETHERTYPE_IP:
4881         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4882         ip4 = (m->m_len < sizeof(struct ip)) ?
4883                   (struct ip *)m->m_next->m_data :
4884                   (struct ip *)(m->m_data + e_hlen);
4885         /* ip_hl is number of 32-bit words */
4886         ip_hlen = (ip4->ip_hl << 2);
4887         ip = (caddr_t)ip4;
4888         break;
4889     case ETHERTYPE_IPV6:
4890         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4891         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4892                   (struct ip6_hdr *)m->m_next->m_data :
4893                   (struct ip6_hdr *)(m->m_data + e_hlen);
4894         /* XXX cannot support offload with IPv6 extensions */
4895         ip_hlen = sizeof(struct ip6_hdr);
4896         ip = (caddr_t)ip6;
4897         break;
4898     default:
4899         /* We can't offload in this case... */
4900         /* XXX error stat ??? */
4901         return (0);
4902     }
4903 
4904     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4905     l4_off = (e_hlen + ip_hlen);
4906 
4907     *parsing_data |=
4908         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4909          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4910 
4911     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4912                                   CSUM_TSO |
4913                                   CSUM_TCP_IPV6)) {
4914         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4915         th = (struct tcphdr *)(ip + ip_hlen);
4916         /* th_off is number of 32-bit words */
4917         *parsing_data |= ((th->th_off <<
4918                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4919                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4920         return (l4_off + (th->th_off << 2)); /* entire header length */
4921     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4922                                          CSUM_UDP_IPV6)) {
4923         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4924         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4925     } else {
4926         /* XXX error stat ??? */
4927         return (0);
4928     }
4929 }
4930 
4931 static uint8_t
4932 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4933                  struct mbuf                *m,
4934                  struct eth_tx_parse_bd_e1x *pbd)
4935 {
4936     struct ether_vlan_header *eh = NULL;
4937     struct ip *ip4 = NULL;
4938     struct ip6_hdr *ip6 = NULL;
4939     caddr_t ip = NULL;
4940     struct tcphdr *th = NULL;
4941     struct udphdr *uh = NULL;
4942     int e_hlen, ip_hlen;
4943     uint16_t proto;
4944     uint8_t hlen;
4945     uint16_t tmp_csum;
4946     uint32_t *tmp_uh;
4947 
4948     /* get the Ethernet header */
4949     eh = mtod(m, struct ether_vlan_header *);
4950 
4951     /* handle VLAN encapsulation if present */
4952     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4953         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4954         proto  = ntohs(eh->evl_proto);
4955     } else {
4956         e_hlen = ETHER_HDR_LEN;
4957         proto  = ntohs(eh->evl_encap_proto);
4958     }
4959 
4960     switch (proto) {
4961     case ETHERTYPE_IP:
4962         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4963         ip4 = (m->m_len < sizeof(struct ip)) ?
4964                   (struct ip *)m->m_next->m_data :
4965                   (struct ip *)(m->m_data + e_hlen);
4966         /* ip_hl is number of 32-bit words */
4967         ip_hlen = (ip4->ip_hl << 1);
4968         ip = (caddr_t)ip4;
4969         break;
4970     case ETHERTYPE_IPV6:
4971         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4972         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4973                   (struct ip6_hdr *)m->m_next->m_data :
4974                   (struct ip6_hdr *)(m->m_data + e_hlen);
4975         /* XXX cannot support offload with IPv6 extensions */
4976         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4977         ip = (caddr_t)ip6;
4978         break;
4979     default:
4980         /* We can't offload in this case... */
4981         /* XXX error stat ??? */
4982         return (0);
4983     }
4984 
4985     hlen = (e_hlen >> 1);
4986 
4987     /* note that rest of global_data is indirectly zeroed here */
4988     if (m->m_flags & M_VLANTAG) {
4989         pbd->global_data =
4990             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4991     } else {
4992         pbd->global_data = htole16(hlen);
4993     }
4994 
4995     pbd->ip_hlen_w = ip_hlen;
4996 
4997     hlen += pbd->ip_hlen_w;
4998 
4999     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5000 
5001     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5002                                   CSUM_TSO |
5003                                   CSUM_TCP_IPV6)) {
5004         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5005         /* th_off is number of 32-bit words */
5006         hlen += (uint16_t)(th->th_off << 1);
5007     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5008                                          CSUM_UDP_IPV6)) {
5009         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5010         hlen += (sizeof(struct udphdr) / 2);
5011     } else {
5012         /* valid case as only CSUM_IP was set */
5013         return (0);
5014     }
5015 
5016     pbd->total_hlen_w = htole16(hlen);
5017 
5018     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5019                                   CSUM_TSO |
5020                                   CSUM_TCP_IPV6)) {
5021         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5022         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5023     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5024                                          CSUM_UDP_IPV6)) {
5025         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5026 
5027         /*
5028          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5029          * checksums and does not know anything about the UDP header and where
5030          * the checksum field is located. It only knows about TCP. Therefore
5031          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5032          * offload. Since the checksum field offset for TCP is 16 bytes and
5033          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5034          * bytes less than the start of the UDP header. This allows the
5035          * hardware to write the checksum in the correct spot. But the
5036          * hardware will compute a checksum which includes the last 10 bytes
5037          * of the IP header. To correct this we tweak the stack computed
5038          * pseudo checksum by folding in the calculation of the inverse
5039          * checksum for those final 10 bytes of the IP header. This allows
5040          * the correct checksum to be computed by the hardware.
5041          */
5042 
5043         /* set pointer 10 bytes before UDP header */
5044         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5045 
5046         /* calculate a pseudo header checksum over the first 10 bytes */
5047         tmp_csum = in_pseudo(*tmp_uh,
5048                              *(tmp_uh + 1),
5049                              *(uint16_t *)(tmp_uh + 2));
5050 
5051         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5052     }
5053 
5054     return (hlen * 2); /* entire header length, number of bytes */
5055 }
5056 
5057 static void
5058 bxe_set_pbd_lso_e2(struct mbuf *m,
5059                    uint32_t    *parsing_data)
5060 {
5061     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5062                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5063                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5064 
5065     /* XXX test for IPv6 with extension header... */
5066 }
5067 
5068 static void
5069 bxe_set_pbd_lso(struct mbuf                *m,
5070                 struct eth_tx_parse_bd_e1x *pbd)
5071 {
5072     struct ether_vlan_header *eh = NULL;
5073     struct ip *ip = NULL;
5074     struct tcphdr *th = NULL;
5075     int e_hlen;
5076 
5077     /* get the Ethernet header */
5078     eh = mtod(m, struct ether_vlan_header *);
5079 
5080     /* handle VLAN encapsulation if present */
5081     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5082                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5083 
5084     /* get the IP and TCP header, with LSO entire header in first mbuf */
5085     /* XXX assuming IPv4 */
5086     ip = (struct ip *)(m->m_data + e_hlen);
5087     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5088 
5089     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5090     pbd->tcp_send_seq = ntohl(th->th_seq);
5091     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5092 
5093 #if 1
5094         /* XXX IPv4 */
5095         pbd->ip_id = ntohs(ip->ip_id);
5096         pbd->tcp_pseudo_csum =
5097             ntohs(in_pseudo(ip->ip_src.s_addr,
5098                             ip->ip_dst.s_addr,
5099                             htons(IPPROTO_TCP)));
5100 #else
5101         /* XXX IPv6 */
5102         pbd->tcp_pseudo_csum =
5103             ntohs(in_pseudo(&ip6->ip6_src,
5104                             &ip6->ip6_dst,
5105                             htons(IPPROTO_TCP)));
5106 #endif
5107 
5108     pbd->global_data |=
5109         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5110 }
5111 
5112 /*
5113  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5114  * visible to the controller.
5115  *
5116  * If an mbuf is submitted to this routine and cannot be given to the
5117  * controller (e.g. it has too many fragments) then the function may free
5118  * the mbuf and return to the caller.
5119  *
5120  * Returns:
5121  *   0 = Success, !0 = Failure
5122  *   Note the side effect that an mbuf may be freed if it causes a problem.
5123  */
5124 static int
5125 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5126 {
5127     bus_dma_segment_t segs[32];
5128     struct mbuf *m0;
5129     struct bxe_sw_tx_bd *tx_buf;
5130     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5131     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5132     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5133     struct eth_tx_bd *tx_data_bd;
5134     struct eth_tx_bd *tx_total_pkt_size_bd;
5135     struct eth_tx_start_bd *tx_start_bd;
5136     uint16_t bd_prod, pkt_prod, total_pkt_size;
5137     uint8_t mac_type;
5138     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5139     struct bxe_softc *sc;
5140     uint16_t tx_bd_avail;
5141     struct ether_vlan_header *eh;
5142     uint32_t pbd_e2_parsing_data = 0;
5143     uint8_t hlen = 0;
5144     int tmp_bd;
5145     int i;
5146 
5147     sc = fp->sc;
5148 
5149 #if __FreeBSD_version >= 800000
5150     M_ASSERTPKTHDR(*m_head);
5151 #endif /* #if __FreeBSD_version >= 800000 */
5152 
5153     m0 = *m_head;
5154     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5155     tx_start_bd = NULL;
5156     tx_data_bd = NULL;
5157     tx_total_pkt_size_bd = NULL;
5158 
5159     /* get the H/W pointer for packets and BDs */
5160     pkt_prod = fp->tx_pkt_prod;
5161     bd_prod = fp->tx_bd_prod;
5162 
5163     mac_type = UNICAST_ADDRESS;
5164 
5165     /* map the mbuf into the next open DMAable memory */
5166     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5167     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5168                                     tx_buf->m_map, m0,
5169                                     segs, &nsegs, BUS_DMA_NOWAIT);
5170 
5171     /* mapping errors */
5172     if(__predict_false(error != 0)) {
5173         fp->eth_q_stats.tx_dma_mapping_failure++;
5174         if (error == ENOMEM) {
5175             /* resource issue, try again later */
5176             rc = ENOMEM;
5177         } else if (error == EFBIG) {
5178             /* possibly recoverable with defragmentation */
5179             fp->eth_q_stats.mbuf_defrag_attempts++;
5180             m0 = m_defrag(*m_head, M_NOWAIT);
5181             if (m0 == NULL) {
5182                 fp->eth_q_stats.mbuf_defrag_failures++;
5183                 rc = ENOBUFS;
5184             } else {
5185                 /* defrag successful, try mapping again */
5186                 *m_head = m0;
5187                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5188                                                 tx_buf->m_map, m0,
5189                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5190                 if (error) {
5191                     fp->eth_q_stats.tx_dma_mapping_failure++;
5192                     rc = error;
5193                 }
5194             }
5195         } else {
5196             /* unknown, unrecoverable mapping error */
5197             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5198             bxe_dump_mbuf(sc, m0, FALSE);
5199             rc = error;
5200         }
5201 
5202         goto bxe_tx_encap_continue;
5203     }
5204 
5205     tx_bd_avail = bxe_tx_avail(sc, fp);
5206 
5207     /* make sure there is enough room in the send queue */
5208     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5209         /* Recoverable, try again later. */
5210         fp->eth_q_stats.tx_hw_queue_full++;
5211         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5212         rc = ENOMEM;
5213         goto bxe_tx_encap_continue;
5214     }
5215 
5216     /* capture the current H/W TX chain high watermark */
5217     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5218                         (TX_BD_USABLE - tx_bd_avail))) {
5219         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5220     }
5221 
5222     /* make sure it fits in the packet window */
5223     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5224         /*
5225          * The mbuf may be to big for the controller to handle. If the frame
5226          * is a TSO frame we'll need to do an additional check.
5227          */
5228         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5229             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5230                 goto bxe_tx_encap_continue; /* OK to send */
5231             } else {
5232                 fp->eth_q_stats.tx_window_violation_tso++;
5233             }
5234         } else {
5235             fp->eth_q_stats.tx_window_violation_std++;
5236         }
5237 
5238         /* lets try to defragment this mbuf and remap it */
5239         fp->eth_q_stats.mbuf_defrag_attempts++;
5240         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5241 
5242         m0 = m_defrag(*m_head, M_NOWAIT);
5243         if (m0 == NULL) {
5244             fp->eth_q_stats.mbuf_defrag_failures++;
5245             /* Ugh, just drop the frame... :( */
5246             rc = ENOBUFS;
5247         } else {
5248             /* defrag successful, try mapping again */
5249             *m_head = m0;
5250             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5251                                             tx_buf->m_map, m0,
5252                                             segs, &nsegs, BUS_DMA_NOWAIT);
5253             if (error) {
5254                 fp->eth_q_stats.tx_dma_mapping_failure++;
5255                 /* No sense in trying to defrag/copy chain, drop it. :( */
5256                 rc = error;
5257             } else {
5258                /* if the chain is still too long then drop it */
5259                 if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5260                     /*
5261                      * in case TSO is enabled nsegs should be checked against
5262                      * BXE_TSO_MAX_SEGMENTS
5263                      */
5264                     if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5265                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5266                         fp->eth_q_stats.nsegs_path1_errors++;
5267                         rc = ENODEV;
5268                     }
5269                 } else {
5270                     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5271                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5272                         fp->eth_q_stats.nsegs_path2_errors++;
5273                         rc = ENODEV;
5274                     }
5275                 }
5276             }
5277         }
5278     }
5279 
5280 bxe_tx_encap_continue:
5281 
5282     /* Check for errors */
5283     if (rc) {
5284         if (rc == ENOMEM) {
5285             /* recoverable try again later  */
5286         } else {
5287             fp->eth_q_stats.tx_soft_errors++;
5288             fp->eth_q_stats.mbuf_alloc_tx--;
5289             m_freem(*m_head);
5290             *m_head = NULL;
5291         }
5292 
5293         return (rc);
5294     }
5295 
5296     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5297     if (m0->m_flags & M_BCAST) {
5298         mac_type = BROADCAST_ADDRESS;
5299     } else if (m0->m_flags & M_MCAST) {
5300         mac_type = MULTICAST_ADDRESS;
5301     }
5302 
5303     /* store the mbuf into the mbuf ring */
5304     tx_buf->m        = m0;
5305     tx_buf->first_bd = fp->tx_bd_prod;
5306     tx_buf->flags    = 0;
5307 
5308     /* prepare the first transmit (start) BD for the mbuf */
5309     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5310 
5311     BLOGD(sc, DBG_TX,
5312           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5313           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5314 
5315     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5316     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5317     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5318     total_pkt_size += tx_start_bd->nbytes;
5319     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5320 
5321     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5322 
5323     /* all frames have at least Start BD + Parsing BD */
5324     nbds = nsegs + 1;
5325     tx_start_bd->nbd = htole16(nbds);
5326 
5327     if (m0->m_flags & M_VLANTAG) {
5328         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5329         tx_start_bd->bd_flags.as_bitfield |=
5330             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5331     } else {
5332         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5333         if (IS_VF(sc)) {
5334             /* map ethernet header to find type and header length */
5335             eh = mtod(m0, struct ether_vlan_header *);
5336             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5337         } else {
5338             /* used by FW for packet accounting */
5339             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5340         }
5341     }
5342 
5343     /*
5344      * add a parsing BD from the chain. The parsing BD is always added
5345      * though it is only used for TSO and chksum
5346      */
5347     bd_prod = TX_BD_NEXT(bd_prod);
5348 
5349     if (m0->m_pkthdr.csum_flags) {
5350         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5351             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5352             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5353         }
5354 
5355         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5356             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5357                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5358         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5359             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5360                                                   ETH_TX_BD_FLAGS_IS_UDP |
5361                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5362         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5363                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5364             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5365         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5366             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5367                                                   ETH_TX_BD_FLAGS_IS_UDP);
5368         }
5369     }
5370 
5371     if (!CHIP_IS_E1x(sc)) {
5372         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5373         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5374 
5375         if (m0->m_pkthdr.csum_flags) {
5376             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5377         }
5378 
5379         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5380                  mac_type);
5381     } else {
5382         uint16_t global_data = 0;
5383 
5384         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5385         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5386 
5387         if (m0->m_pkthdr.csum_flags) {
5388             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5389         }
5390 
5391         SET_FLAG(global_data,
5392                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5393         pbd_e1x->global_data |= htole16(global_data);
5394     }
5395 
5396     /* setup the parsing BD with TSO specific info */
5397     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5398         fp->eth_q_stats.tx_ofld_frames_lso++;
5399         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5400 
5401         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5402             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5403 
5404             /* split the first BD into header/data making the fw job easy */
5405             nbds++;
5406             tx_start_bd->nbd = htole16(nbds);
5407             tx_start_bd->nbytes = htole16(hlen);
5408 
5409             bd_prod = TX_BD_NEXT(bd_prod);
5410 
5411             /* new transmit BD after the tx_parse_bd */
5412             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5413             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5414             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5415             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5416             if (tx_total_pkt_size_bd == NULL) {
5417                 tx_total_pkt_size_bd = tx_data_bd;
5418             }
5419 
5420             BLOGD(sc, DBG_TX,
5421                   "TSO split header size is %d (%x:%x) nbds %d\n",
5422                   le16toh(tx_start_bd->nbytes),
5423                   le32toh(tx_start_bd->addr_hi),
5424                   le32toh(tx_start_bd->addr_lo),
5425                   nbds);
5426         }
5427 
5428         if (!CHIP_IS_E1x(sc)) {
5429             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5430         } else {
5431             bxe_set_pbd_lso(m0, pbd_e1x);
5432         }
5433     }
5434 
5435     if (pbd_e2_parsing_data) {
5436         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5437     }
5438 
5439     /* prepare remaining BDs, start tx bd contains first seg/frag */
5440     for (i = 1; i < nsegs ; i++) {
5441         bd_prod = TX_BD_NEXT(bd_prod);
5442         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5443         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5444         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5445         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5446         if (tx_total_pkt_size_bd == NULL) {
5447             tx_total_pkt_size_bd = tx_data_bd;
5448         }
5449         total_pkt_size += tx_data_bd->nbytes;
5450     }
5451 
5452     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5453 
5454     if (tx_total_pkt_size_bd != NULL) {
5455         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5456     }
5457 
5458     if (__predict_false(sc->debug & DBG_TX)) {
5459         tmp_bd = tx_buf->first_bd;
5460         for (i = 0; i < nbds; i++)
5461         {
5462             if (i == 0) {
5463                 BLOGD(sc, DBG_TX,
5464                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5465                       "bd_flags=0x%x hdr_nbds=%d\n",
5466                       tx_start_bd,
5467                       tmp_bd,
5468                       le16toh(tx_start_bd->nbd),
5469                       le16toh(tx_start_bd->vlan_or_ethertype),
5470                       tx_start_bd->bd_flags.as_bitfield,
5471                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5472             } else if (i == 1) {
5473                 if (pbd_e1x) {
5474                     BLOGD(sc, DBG_TX,
5475                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5476                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5477                           "tcp_seq=%u total_hlen_w=%u\n",
5478                           pbd_e1x,
5479                           tmp_bd,
5480                           pbd_e1x->global_data,
5481                           pbd_e1x->ip_hlen_w,
5482                           pbd_e1x->ip_id,
5483                           pbd_e1x->lso_mss,
5484                           pbd_e1x->tcp_flags,
5485                           pbd_e1x->tcp_pseudo_csum,
5486                           pbd_e1x->tcp_send_seq,
5487                           le16toh(pbd_e1x->total_hlen_w));
5488                 } else { /* if (pbd_e2) */
5489                     BLOGD(sc, DBG_TX,
5490                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5491                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5492                           pbd_e2,
5493                           tmp_bd,
5494                           pbd_e2->data.mac_addr.dst_hi,
5495                           pbd_e2->data.mac_addr.dst_mid,
5496                           pbd_e2->data.mac_addr.dst_lo,
5497                           pbd_e2->data.mac_addr.src_hi,
5498                           pbd_e2->data.mac_addr.src_mid,
5499                           pbd_e2->data.mac_addr.src_lo,
5500                           pbd_e2->parsing_data);
5501                 }
5502             }
5503 
5504             if (i != 1) { /* skip parse db as it doesn't hold data */
5505                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5506                 BLOGD(sc, DBG_TX,
5507                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5508                       tx_data_bd,
5509                       tmp_bd,
5510                       le16toh(tx_data_bd->nbytes),
5511                       le32toh(tx_data_bd->addr_hi),
5512                       le32toh(tx_data_bd->addr_lo));
5513             }
5514 
5515             tmp_bd = TX_BD_NEXT(tmp_bd);
5516         }
5517     }
5518 
5519     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5520 
5521     /* update TX BD producer index value for next TX */
5522     bd_prod = TX_BD_NEXT(bd_prod);
5523 
5524     /*
5525      * If the chain of tx_bd's describing this frame is adjacent to or spans
5526      * an eth_tx_next_bd element then we need to increment the nbds value.
5527      */
5528     if (TX_BD_IDX(bd_prod) < nbds) {
5529         nbds++;
5530     }
5531 
5532     /* don't allow reordering of writes for nbd and packets */
5533     mb();
5534 
5535     fp->tx_db.data.prod += nbds;
5536 
5537     /* producer points to the next free tx_bd at this point */
5538     fp->tx_pkt_prod++;
5539     fp->tx_bd_prod = bd_prod;
5540 
5541     DOORBELL(sc, fp->index, fp->tx_db.raw);
5542 
5543     fp->eth_q_stats.tx_pkts++;
5544 
5545     /* Prevent speculative reads from getting ahead of the status block. */
5546     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5547                       0, 0, BUS_SPACE_BARRIER_READ);
5548 
5549     /* Prevent speculative reads from getting ahead of the doorbell. */
5550     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5551                       0, 0, BUS_SPACE_BARRIER_READ);
5552 
5553     return (0);
5554 }
5555 
5556 static void
5557 bxe_tx_start_locked(struct bxe_softc *sc,
5558                     if_t ifp,
5559                     struct bxe_fastpath *fp)
5560 {
5561     struct mbuf *m = NULL;
5562     int tx_count = 0;
5563     uint16_t tx_bd_avail;
5564 
5565     BXE_FP_TX_LOCK_ASSERT(fp);
5566 
5567     /* keep adding entries while there are frames to send */
5568     while (!if_sendq_empty(ifp)) {
5569 
5570         /*
5571          * check for any frames to send
5572          * dequeue can still be NULL even if queue is not empty
5573          */
5574         m = if_dequeue(ifp);
5575         if (__predict_false(m == NULL)) {
5576             break;
5577         }
5578 
5579         /* the mbuf now belongs to us */
5580         fp->eth_q_stats.mbuf_alloc_tx++;
5581 
5582         /*
5583          * Put the frame into the transmit ring. If we don't have room,
5584          * place the mbuf back at the head of the TX queue, set the
5585          * OACTIVE flag, and wait for the NIC to drain the chain.
5586          */
5587         if (__predict_false(bxe_tx_encap(fp, &m))) {
5588             fp->eth_q_stats.tx_encap_failures++;
5589             if (m != NULL) {
5590                 /* mark the TX queue as full and return the frame */
5591                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5592 		if_sendq_prepend(ifp, m);
5593                 fp->eth_q_stats.mbuf_alloc_tx--;
5594                 fp->eth_q_stats.tx_queue_xoff++;
5595             }
5596 
5597             /* stop looking for more work */
5598             break;
5599         }
5600 
5601         /* the frame was enqueued successfully */
5602         tx_count++;
5603 
5604         /* send a copy of the frame to any BPF listeners. */
5605         if_etherbpfmtap(ifp, m);
5606 
5607         tx_bd_avail = bxe_tx_avail(sc, fp);
5608 
5609         /* handle any completions if we're running low */
5610         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5611             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5612             bxe_txeof(sc, fp);
5613             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5614                 break;
5615             }
5616         }
5617     }
5618 
5619     /* all TX packets were dequeued and/or the tx ring is full */
5620     if (tx_count > 0) {
5621         /* reset the TX watchdog timeout timer */
5622         fp->watchdog_timer = BXE_TX_TIMEOUT;
5623     }
5624 }
5625 
5626 /* Legacy (non-RSS) dispatch routine */
5627 static void
5628 bxe_tx_start(if_t ifp)
5629 {
5630     struct bxe_softc *sc;
5631     struct bxe_fastpath *fp;
5632 
5633     sc = if_getsoftc(ifp);
5634 
5635     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5636         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5637         return;
5638     }
5639 
5640     if (!sc->link_vars.link_up) {
5641         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5642         return;
5643     }
5644 
5645     fp = &sc->fp[0];
5646 
5647     if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5648         fp->eth_q_stats.tx_queue_full_return++;
5649         return;
5650     }
5651 
5652     BXE_FP_TX_LOCK(fp);
5653     bxe_tx_start_locked(sc, ifp, fp);
5654     BXE_FP_TX_UNLOCK(fp);
5655 }
5656 
5657 #if __FreeBSD_version >= 901504
5658 
5659 static int
5660 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5661                        if_t                ifp,
5662                        struct bxe_fastpath *fp,
5663                        struct mbuf         *m)
5664 {
5665     struct buf_ring *tx_br = fp->tx_br;
5666     struct mbuf *next;
5667     int depth, rc, tx_count;
5668     uint16_t tx_bd_avail;
5669 
5670     rc = tx_count = 0;
5671 
5672     BXE_FP_TX_LOCK_ASSERT(fp);
5673 
5674     if (sc->state != BXE_STATE_OPEN)  {
5675         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5676         return ENETDOWN;
5677     }
5678 
5679     if (!tx_br) {
5680         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5681         return (EINVAL);
5682     }
5683 
5684     if (m != NULL) {
5685         rc = drbr_enqueue(ifp, tx_br, m);
5686         if (rc != 0) {
5687             fp->eth_q_stats.tx_soft_errors++;
5688             goto bxe_tx_mq_start_locked_exit;
5689         }
5690     }
5691 
5692     if (!sc->link_vars.link_up || !(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5693         fp->eth_q_stats.tx_request_link_down_failures++;
5694         goto bxe_tx_mq_start_locked_exit;
5695     }
5696 
5697     /* fetch the depth of the driver queue */
5698     depth = drbr_inuse_drv(ifp, tx_br);
5699     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5700         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5701     }
5702 
5703     /* keep adding entries while there are frames to send */
5704     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5705         /* handle any completions if we're running low */
5706         tx_bd_avail = bxe_tx_avail(sc, fp);
5707         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5708             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5709             bxe_txeof(sc, fp);
5710             tx_bd_avail = bxe_tx_avail(sc, fp);
5711             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5712                 fp->eth_q_stats.bd_avail_too_less_failures++;
5713                 m_freem(next);
5714                 drbr_advance(ifp, tx_br);
5715                 rc = ENOBUFS;
5716                 break;
5717             }
5718         }
5719 
5720         /* the mbuf now belongs to us */
5721         fp->eth_q_stats.mbuf_alloc_tx++;
5722 
5723         /*
5724          * Put the frame into the transmit ring. If we don't have room,
5725          * place the mbuf back at the head of the TX queue, set the
5726          * OACTIVE flag, and wait for the NIC to drain the chain.
5727          */
5728         rc = bxe_tx_encap(fp, &next);
5729         if (__predict_false(rc != 0)) {
5730             fp->eth_q_stats.tx_encap_failures++;
5731             if (next != NULL) {
5732                 /* mark the TX queue as full and save the frame */
5733                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5734                 drbr_putback(ifp, tx_br, next);
5735                 fp->eth_q_stats.mbuf_alloc_tx--;
5736                 fp->eth_q_stats.tx_frames_deferred++;
5737             } else
5738                 drbr_advance(ifp, tx_br);
5739 
5740             /* stop looking for more work */
5741             break;
5742         }
5743 
5744         /* the transmit frame was enqueued successfully */
5745         tx_count++;
5746 
5747         /* send a copy of the frame to any BPF listeners */
5748 	if_etherbpfmtap(ifp, next);
5749 
5750         drbr_advance(ifp, tx_br);
5751     }
5752 
5753     /* all TX packets were dequeued and/or the tx ring is full */
5754     if (tx_count > 0) {
5755         /* reset the TX watchdog timeout timer */
5756         fp->watchdog_timer = BXE_TX_TIMEOUT;
5757     }
5758 
5759 bxe_tx_mq_start_locked_exit:
5760     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5761     if (!drbr_empty(ifp, tx_br)) {
5762         fp->eth_q_stats.tx_mq_not_empty++;
5763         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5764     }
5765 
5766     return (rc);
5767 }
5768 
5769 static void
5770 bxe_tx_mq_start_deferred(void *arg,
5771                          int pending)
5772 {
5773     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5774     struct bxe_softc *sc = fp->sc;
5775     if_t ifp = sc->ifp;
5776 
5777     BXE_FP_TX_LOCK(fp);
5778     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5779     BXE_FP_TX_UNLOCK(fp);
5780 }
5781 
5782 /* Multiqueue (TSS) dispatch routine. */
5783 static int
5784 bxe_tx_mq_start(struct ifnet *ifp,
5785                 struct mbuf  *m)
5786 {
5787     struct bxe_softc *sc = if_getsoftc(ifp);
5788     struct bxe_fastpath *fp;
5789     int fp_index, rc;
5790 
5791     fp_index = 0; /* default is the first queue */
5792 
5793     /* check if flowid is set */
5794 
5795     if (BXE_VALID_FLOWID(m))
5796         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5797 
5798     fp = &sc->fp[fp_index];
5799 
5800     if (sc->state != BXE_STATE_OPEN)  {
5801         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5802         return ENETDOWN;
5803     }
5804 
5805     if (BXE_FP_TX_TRYLOCK(fp)) {
5806         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5807         BXE_FP_TX_UNLOCK(fp);
5808     } else {
5809         rc = drbr_enqueue(ifp, fp->tx_br, m);
5810         taskqueue_enqueue(fp->tq, &fp->tx_task);
5811     }
5812 
5813     return (rc);
5814 }
5815 
5816 static void
5817 bxe_mq_flush(struct ifnet *ifp)
5818 {
5819     struct bxe_softc *sc = if_getsoftc(ifp);
5820     struct bxe_fastpath *fp;
5821     struct mbuf *m;
5822     int i;
5823 
5824     for (i = 0; i < sc->num_queues; i++) {
5825         fp = &sc->fp[i];
5826 
5827         if (fp->state != BXE_FP_STATE_IRQ) {
5828             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5829                   fp->index, fp->state);
5830             continue;
5831         }
5832 
5833         if (fp->tx_br != NULL) {
5834             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5835             BXE_FP_TX_LOCK(fp);
5836             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5837                 m_freem(m);
5838             }
5839             BXE_FP_TX_UNLOCK(fp);
5840         }
5841     }
5842 
5843     if_qflush(ifp);
5844 }
5845 
5846 #endif /* FreeBSD_version >= 901504 */
5847 
5848 static uint16_t
5849 bxe_cid_ilt_lines(struct bxe_softc *sc)
5850 {
5851     if (IS_SRIOV(sc)) {
5852         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5853     }
5854     return (L2_ILT_LINES(sc));
5855 }
5856 
5857 static void
5858 bxe_ilt_set_info(struct bxe_softc *sc)
5859 {
5860     struct ilt_client_info *ilt_client;
5861     struct ecore_ilt *ilt = sc->ilt;
5862     uint16_t line = 0;
5863 
5864     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5865     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5866 
5867     /* CDU */
5868     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5869     ilt_client->client_num = ILT_CLIENT_CDU;
5870     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5871     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5872     ilt_client->start = line;
5873     line += bxe_cid_ilt_lines(sc);
5874 
5875     if (CNIC_SUPPORT(sc)) {
5876         line += CNIC_ILT_LINES;
5877     }
5878 
5879     ilt_client->end = (line - 1);
5880 
5881     BLOGD(sc, DBG_LOAD,
5882           "ilt client[CDU]: start %d, end %d, "
5883           "psz 0x%x, flags 0x%x, hw psz %d\n",
5884           ilt_client->start, ilt_client->end,
5885           ilt_client->page_size,
5886           ilt_client->flags,
5887           ilog2(ilt_client->page_size >> 12));
5888 
5889     /* QM */
5890     if (QM_INIT(sc->qm_cid_count)) {
5891         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5892         ilt_client->client_num = ILT_CLIENT_QM;
5893         ilt_client->page_size = QM_ILT_PAGE_SZ;
5894         ilt_client->flags = 0;
5895         ilt_client->start = line;
5896 
5897         /* 4 bytes for each cid */
5898         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5899                              QM_ILT_PAGE_SZ);
5900 
5901         ilt_client->end = (line - 1);
5902 
5903         BLOGD(sc, DBG_LOAD,
5904               "ilt client[QM]: start %d, end %d, "
5905               "psz 0x%x, flags 0x%x, hw psz %d\n",
5906               ilt_client->start, ilt_client->end,
5907               ilt_client->page_size, ilt_client->flags,
5908               ilog2(ilt_client->page_size >> 12));
5909     }
5910 
5911     if (CNIC_SUPPORT(sc)) {
5912         /* SRC */
5913         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5914         ilt_client->client_num = ILT_CLIENT_SRC;
5915         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5916         ilt_client->flags = 0;
5917         ilt_client->start = line;
5918         line += SRC_ILT_LINES;
5919         ilt_client->end = (line - 1);
5920 
5921         BLOGD(sc, DBG_LOAD,
5922               "ilt client[SRC]: start %d, end %d, "
5923               "psz 0x%x, flags 0x%x, hw psz %d\n",
5924               ilt_client->start, ilt_client->end,
5925               ilt_client->page_size, ilt_client->flags,
5926               ilog2(ilt_client->page_size >> 12));
5927 
5928         /* TM */
5929         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5930         ilt_client->client_num = ILT_CLIENT_TM;
5931         ilt_client->page_size = TM_ILT_PAGE_SZ;
5932         ilt_client->flags = 0;
5933         ilt_client->start = line;
5934         line += TM_ILT_LINES;
5935         ilt_client->end = (line - 1);
5936 
5937         BLOGD(sc, DBG_LOAD,
5938               "ilt client[TM]: start %d, end %d, "
5939               "psz 0x%x, flags 0x%x, hw psz %d\n",
5940               ilt_client->start, ilt_client->end,
5941               ilt_client->page_size, ilt_client->flags,
5942               ilog2(ilt_client->page_size >> 12));
5943     }
5944 
5945     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5946 }
5947 
5948 static void
5949 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5950 {
5951     int i;
5952     uint32_t rx_buf_size;
5953 
5954     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5955 
5956     for (i = 0; i < sc->num_queues; i++) {
5957         if(rx_buf_size <= MCLBYTES){
5958             sc->fp[i].rx_buf_size = rx_buf_size;
5959             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5960         }else if (rx_buf_size <= MJUMPAGESIZE){
5961             sc->fp[i].rx_buf_size = rx_buf_size;
5962             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5963         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5964             sc->fp[i].rx_buf_size = MCLBYTES;
5965             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5966         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5967             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5968             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5969         }else {
5970             sc->fp[i].rx_buf_size = MCLBYTES;
5971             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5972         }
5973     }
5974 }
5975 
5976 static int
5977 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5978 {
5979     int rc = 0;
5980 
5981     if ((sc->ilt =
5982          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5983                                     M_BXE_ILT,
5984                                     (M_NOWAIT | M_ZERO))) == NULL) {
5985         rc = 1;
5986     }
5987 
5988     return (rc);
5989 }
5990 
5991 static int
5992 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5993 {
5994     int rc = 0;
5995 
5996     if ((sc->ilt->lines =
5997          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
5998                                     M_BXE_ILT,
5999                                     (M_NOWAIT | M_ZERO))) == NULL) {
6000         rc = 1;
6001     }
6002 
6003     return (rc);
6004 }
6005 
6006 static void
6007 bxe_free_ilt_mem(struct bxe_softc *sc)
6008 {
6009     if (sc->ilt != NULL) {
6010         free(sc->ilt, M_BXE_ILT);
6011         sc->ilt = NULL;
6012     }
6013 }
6014 
6015 static void
6016 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6017 {
6018     if (sc->ilt->lines != NULL) {
6019         free(sc->ilt->lines, M_BXE_ILT);
6020         sc->ilt->lines = NULL;
6021     }
6022 }
6023 
6024 static void
6025 bxe_free_mem(struct bxe_softc *sc)
6026 {
6027     int i;
6028 
6029     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6030         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6031         sc->context[i].vcxt = NULL;
6032         sc->context[i].size = 0;
6033     }
6034 
6035     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6036 
6037     bxe_free_ilt_lines_mem(sc);
6038 
6039 }
6040 
6041 static int
6042 bxe_alloc_mem(struct bxe_softc *sc)
6043 {
6044 
6045     int context_size;
6046     int allocated;
6047     int i;
6048 
6049     /*
6050      * Allocate memory for CDU context:
6051      * This memory is allocated separately and not in the generic ILT
6052      * functions because CDU differs in few aspects:
6053      * 1. There can be multiple entities allocating memory for context -
6054      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6055      * its own ILT lines.
6056      * 2. Since CDU page-size is not a single 4KB page (which is the case
6057      * for the other ILT clients), to be efficient we want to support
6058      * allocation of sub-page-size in the last entry.
6059      * 3. Context pointers are used by the driver to pass to FW / update
6060      * the context (for the other ILT clients the pointers are used just to
6061      * free the memory during unload).
6062      */
6063     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6064     for (i = 0, allocated = 0; allocated < context_size; i++) {
6065         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6066                                   (context_size - allocated));
6067 
6068         if (bxe_dma_alloc(sc, sc->context[i].size,
6069                           &sc->context[i].vcxt_dma,
6070                           "cdu context") != 0) {
6071             bxe_free_mem(sc);
6072             return (-1);
6073         }
6074 
6075         sc->context[i].vcxt =
6076             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6077 
6078         allocated += sc->context[i].size;
6079     }
6080 
6081     bxe_alloc_ilt_lines_mem(sc);
6082 
6083     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6084           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6085     {
6086         for (i = 0; i < 4; i++) {
6087             BLOGD(sc, DBG_LOAD,
6088                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6089                   i,
6090                   sc->ilt->clients[i].page_size,
6091                   sc->ilt->clients[i].start,
6092                   sc->ilt->clients[i].end,
6093                   sc->ilt->clients[i].client_num,
6094                   sc->ilt->clients[i].flags);
6095         }
6096     }
6097     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6098         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6099         bxe_free_mem(sc);
6100         return (-1);
6101     }
6102 
6103     return (0);
6104 }
6105 
6106 static void
6107 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6108 {
6109     struct bxe_softc *sc;
6110     int i;
6111 
6112     sc = fp->sc;
6113 
6114     if (fp->rx_mbuf_tag == NULL) {
6115         return;
6116     }
6117 
6118     /* free all mbufs and unload all maps */
6119     for (i = 0; i < RX_BD_TOTAL; i++) {
6120         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6121             bus_dmamap_sync(fp->rx_mbuf_tag,
6122                             fp->rx_mbuf_chain[i].m_map,
6123                             BUS_DMASYNC_POSTREAD);
6124             bus_dmamap_unload(fp->rx_mbuf_tag,
6125                               fp->rx_mbuf_chain[i].m_map);
6126         }
6127 
6128         if (fp->rx_mbuf_chain[i].m != NULL) {
6129             m_freem(fp->rx_mbuf_chain[i].m);
6130             fp->rx_mbuf_chain[i].m = NULL;
6131             fp->eth_q_stats.mbuf_alloc_rx--;
6132         }
6133     }
6134 }
6135 
6136 static void
6137 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6138 {
6139     struct bxe_softc *sc;
6140     int i, max_agg_queues;
6141 
6142     sc = fp->sc;
6143 
6144     if (fp->rx_mbuf_tag == NULL) {
6145         return;
6146     }
6147 
6148     max_agg_queues = MAX_AGG_QS(sc);
6149 
6150     /* release all mbufs and unload all DMA maps in the TPA pool */
6151     for (i = 0; i < max_agg_queues; i++) {
6152         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6153             bus_dmamap_sync(fp->rx_mbuf_tag,
6154                             fp->rx_tpa_info[i].bd.m_map,
6155                             BUS_DMASYNC_POSTREAD);
6156             bus_dmamap_unload(fp->rx_mbuf_tag,
6157                               fp->rx_tpa_info[i].bd.m_map);
6158         }
6159 
6160         if (fp->rx_tpa_info[i].bd.m != NULL) {
6161             m_freem(fp->rx_tpa_info[i].bd.m);
6162             fp->rx_tpa_info[i].bd.m = NULL;
6163             fp->eth_q_stats.mbuf_alloc_tpa--;
6164         }
6165     }
6166 }
6167 
6168 static void
6169 bxe_free_sge_chain(struct bxe_fastpath *fp)
6170 {
6171     struct bxe_softc *sc;
6172     int i;
6173 
6174     sc = fp->sc;
6175 
6176     if (fp->rx_sge_mbuf_tag == NULL) {
6177         return;
6178     }
6179 
6180     /* rree all mbufs and unload all maps */
6181     for (i = 0; i < RX_SGE_TOTAL; i++) {
6182         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6183             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6184                             fp->rx_sge_mbuf_chain[i].m_map,
6185                             BUS_DMASYNC_POSTREAD);
6186             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6187                               fp->rx_sge_mbuf_chain[i].m_map);
6188         }
6189 
6190         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6191             m_freem(fp->rx_sge_mbuf_chain[i].m);
6192             fp->rx_sge_mbuf_chain[i].m = NULL;
6193             fp->eth_q_stats.mbuf_alloc_sge--;
6194         }
6195     }
6196 }
6197 
6198 static void
6199 bxe_free_fp_buffers(struct bxe_softc *sc)
6200 {
6201     struct bxe_fastpath *fp;
6202     int i;
6203 
6204     for (i = 0; i < sc->num_queues; i++) {
6205         fp = &sc->fp[i];
6206 
6207 #if __FreeBSD_version >= 901504
6208         if (fp->tx_br != NULL) {
6209             /* just in case bxe_mq_flush() wasn't called */
6210             if (mtx_initialized(&fp->tx_mtx)) {
6211                 struct mbuf *m;
6212 
6213                 BXE_FP_TX_LOCK(fp);
6214                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6215                     m_freem(m);
6216                 BXE_FP_TX_UNLOCK(fp);
6217             }
6218         }
6219 #endif
6220 
6221         /* free all RX buffers */
6222         bxe_free_rx_bd_chain(fp);
6223         bxe_free_tpa_pool(fp);
6224         bxe_free_sge_chain(fp);
6225 
6226         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6227             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6228                   fp->eth_q_stats.mbuf_alloc_rx);
6229         }
6230 
6231         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6232             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6233                   fp->eth_q_stats.mbuf_alloc_sge);
6234         }
6235 
6236         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6237             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6238                   fp->eth_q_stats.mbuf_alloc_tpa);
6239         }
6240 
6241         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6242             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6243                   fp->eth_q_stats.mbuf_alloc_tx);
6244         }
6245 
6246         /* XXX verify all mbufs were reclaimed */
6247     }
6248 }
6249 
6250 static int
6251 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6252                      uint16_t            prev_index,
6253                      uint16_t            index)
6254 {
6255     struct bxe_sw_rx_bd *rx_buf;
6256     struct eth_rx_bd *rx_bd;
6257     bus_dma_segment_t segs[1];
6258     bus_dmamap_t map;
6259     struct mbuf *m;
6260     int nsegs, rc;
6261 
6262     rc = 0;
6263 
6264     /* allocate the new RX BD mbuf */
6265     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6266     if (__predict_false(m == NULL)) {
6267         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6268         return (ENOBUFS);
6269     }
6270 
6271     fp->eth_q_stats.mbuf_alloc_rx++;
6272 
6273     /* initialize the mbuf buffer length */
6274     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6275 
6276     /* map the mbuf into non-paged pool */
6277     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6278                                  fp->rx_mbuf_spare_map,
6279                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6280     if (__predict_false(rc != 0)) {
6281         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6282         m_freem(m);
6283         fp->eth_q_stats.mbuf_alloc_rx--;
6284         return (rc);
6285     }
6286 
6287     /* all mbufs must map to a single segment */
6288     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6289 
6290     /* release any existing RX BD mbuf mappings */
6291 
6292     if (prev_index != index) {
6293         rx_buf = &fp->rx_mbuf_chain[prev_index];
6294 
6295         if (rx_buf->m_map != NULL) {
6296             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6297                             BUS_DMASYNC_POSTREAD);
6298             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6299         }
6300 
6301         /*
6302          * We only get here from bxe_rxeof() when the maximum number
6303          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6304          * holds the mbuf in the prev_index so it's OK to NULL it out
6305          * here without concern of a memory leak.
6306          */
6307         fp->rx_mbuf_chain[prev_index].m = NULL;
6308     }
6309 
6310     rx_buf = &fp->rx_mbuf_chain[index];
6311 
6312     if (rx_buf->m_map != NULL) {
6313         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6314                         BUS_DMASYNC_POSTREAD);
6315         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6316     }
6317 
6318     /* save the mbuf and mapping info for a future packet */
6319     map = (prev_index != index) ?
6320               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6321     rx_buf->m_map = fp->rx_mbuf_spare_map;
6322     fp->rx_mbuf_spare_map = map;
6323     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6324                     BUS_DMASYNC_PREREAD);
6325     rx_buf->m = m;
6326 
6327     rx_bd = &fp->rx_chain[index];
6328     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6329     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6330 
6331     return (rc);
6332 }
6333 
6334 static int
6335 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6336                       int                 queue)
6337 {
6338     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6339     bus_dma_segment_t segs[1];
6340     bus_dmamap_t map;
6341     struct mbuf *m;
6342     int nsegs;
6343     int rc = 0;
6344 
6345     /* allocate the new TPA mbuf */
6346     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6347     if (__predict_false(m == NULL)) {
6348         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6349         return (ENOBUFS);
6350     }
6351 
6352     fp->eth_q_stats.mbuf_alloc_tpa++;
6353 
6354     /* initialize the mbuf buffer length */
6355     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6356 
6357     /* map the mbuf into non-paged pool */
6358     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6359                                  fp->rx_tpa_info_mbuf_spare_map,
6360                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6361     if (__predict_false(rc != 0)) {
6362         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6363         m_free(m);
6364         fp->eth_q_stats.mbuf_alloc_tpa--;
6365         return (rc);
6366     }
6367 
6368     /* all mbufs must map to a single segment */
6369     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6370 
6371     /* release any existing TPA mbuf mapping */
6372     if (tpa_info->bd.m_map != NULL) {
6373         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6374                         BUS_DMASYNC_POSTREAD);
6375         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6376     }
6377 
6378     /* save the mbuf and mapping info for the TPA mbuf */
6379     map = tpa_info->bd.m_map;
6380     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6381     fp->rx_tpa_info_mbuf_spare_map = map;
6382     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6383                     BUS_DMASYNC_PREREAD);
6384     tpa_info->bd.m = m;
6385     tpa_info->seg = segs[0];
6386 
6387     return (rc);
6388 }
6389 
6390 /*
6391  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6392  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6393  * chain.
6394  */
6395 static int
6396 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6397                       uint16_t            index)
6398 {
6399     struct bxe_sw_rx_bd *sge_buf;
6400     struct eth_rx_sge *sge;
6401     bus_dma_segment_t segs[1];
6402     bus_dmamap_t map;
6403     struct mbuf *m;
6404     int nsegs;
6405     int rc = 0;
6406 
6407     /* allocate a new SGE mbuf */
6408     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6409     if (__predict_false(m == NULL)) {
6410         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6411         return (ENOMEM);
6412     }
6413 
6414     fp->eth_q_stats.mbuf_alloc_sge++;
6415 
6416     /* initialize the mbuf buffer length */
6417     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6418 
6419     /* map the SGE mbuf into non-paged pool */
6420     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6421                                  fp->rx_sge_mbuf_spare_map,
6422                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6423     if (__predict_false(rc != 0)) {
6424         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6425         m_freem(m);
6426         fp->eth_q_stats.mbuf_alloc_sge--;
6427         return (rc);
6428     }
6429 
6430     /* all mbufs must map to a single segment */
6431     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6432 
6433     sge_buf = &fp->rx_sge_mbuf_chain[index];
6434 
6435     /* release any existing SGE mbuf mapping */
6436     if (sge_buf->m_map != NULL) {
6437         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6438                         BUS_DMASYNC_POSTREAD);
6439         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6440     }
6441 
6442     /* save the mbuf and mapping info for a future packet */
6443     map = sge_buf->m_map;
6444     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6445     fp->rx_sge_mbuf_spare_map = map;
6446     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6447                     BUS_DMASYNC_PREREAD);
6448     sge_buf->m = m;
6449 
6450     sge = &fp->rx_sge_chain[index];
6451     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6452     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6453 
6454     return (rc);
6455 }
6456 
6457 static __noinline int
6458 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6459 {
6460     struct bxe_fastpath *fp;
6461     int i, j, rc = 0;
6462     int ring_prod, cqe_ring_prod;
6463     int max_agg_queues;
6464 
6465     for (i = 0; i < sc->num_queues; i++) {
6466         fp = &sc->fp[i];
6467 
6468         ring_prod = cqe_ring_prod = 0;
6469         fp->rx_bd_cons = 0;
6470         fp->rx_cq_cons = 0;
6471 
6472         /* allocate buffers for the RX BDs in RX BD chain */
6473         for (j = 0; j < sc->max_rx_bufs; j++) {
6474             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6475             if (rc != 0) {
6476                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6477                       i, rc);
6478                 goto bxe_alloc_fp_buffers_error;
6479             }
6480 
6481             ring_prod     = RX_BD_NEXT(ring_prod);
6482             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6483         }
6484 
6485         fp->rx_bd_prod = ring_prod;
6486         fp->rx_cq_prod = cqe_ring_prod;
6487         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6488 
6489         max_agg_queues = MAX_AGG_QS(sc);
6490 
6491         fp->tpa_enable = TRUE;
6492 
6493         /* fill the TPA pool */
6494         for (j = 0; j < max_agg_queues; j++) {
6495             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6496             if (rc != 0) {
6497                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6498                           i, j);
6499                 fp->tpa_enable = FALSE;
6500                 goto bxe_alloc_fp_buffers_error;
6501             }
6502 
6503             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6504         }
6505 
6506         if (fp->tpa_enable) {
6507             /* fill the RX SGE chain */
6508             ring_prod = 0;
6509             for (j = 0; j < RX_SGE_USABLE; j++) {
6510                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6511                 if (rc != 0) {
6512                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6513                               i, ring_prod);
6514                     fp->tpa_enable = FALSE;
6515                     ring_prod = 0;
6516                     goto bxe_alloc_fp_buffers_error;
6517                 }
6518 
6519                 ring_prod = RX_SGE_NEXT(ring_prod);
6520             }
6521 
6522             fp->rx_sge_prod = ring_prod;
6523         }
6524     }
6525 
6526     return (0);
6527 
6528 bxe_alloc_fp_buffers_error:
6529 
6530     /* unwind what was already allocated */
6531     bxe_free_rx_bd_chain(fp);
6532     bxe_free_tpa_pool(fp);
6533     bxe_free_sge_chain(fp);
6534 
6535     return (ENOBUFS);
6536 }
6537 
6538 static void
6539 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6540 {
6541     bxe_dma_free(sc, &sc->fw_stats_dma);
6542 
6543     sc->fw_stats_num = 0;
6544 
6545     sc->fw_stats_req_size = 0;
6546     sc->fw_stats_req = NULL;
6547     sc->fw_stats_req_mapping = 0;
6548 
6549     sc->fw_stats_data_size = 0;
6550     sc->fw_stats_data = NULL;
6551     sc->fw_stats_data_mapping = 0;
6552 }
6553 
6554 static int
6555 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6556 {
6557     uint8_t num_queue_stats;
6558     int num_groups;
6559 
6560     /* number of queues for statistics is number of eth queues */
6561     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6562 
6563     /*
6564      * Total number of FW statistics requests =
6565      *   1 for port stats + 1 for PF stats + num of queues
6566      */
6567     sc->fw_stats_num = (2 + num_queue_stats);
6568 
6569     /*
6570      * Request is built from stats_query_header and an array of
6571      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6572      * rules. The real number or requests is configured in the
6573      * stats_query_header.
6574      */
6575     num_groups =
6576         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6577          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6578 
6579     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6580           sc->fw_stats_num, num_groups);
6581 
6582     sc->fw_stats_req_size =
6583         (sizeof(struct stats_query_header) +
6584          (num_groups * sizeof(struct stats_query_cmd_group)));
6585 
6586     /*
6587      * Data for statistics requests + stats_counter.
6588      * stats_counter holds per-STORM counters that are incremented when
6589      * STORM has finished with the current request. Memory for FCoE
6590      * offloaded statistics are counted anyway, even if they will not be sent.
6591      * VF stats are not accounted for here as the data of VF stats is stored
6592      * in memory allocated by the VF, not here.
6593      */
6594     sc->fw_stats_data_size =
6595         (sizeof(struct stats_counter) +
6596          sizeof(struct per_port_stats) +
6597          sizeof(struct per_pf_stats) +
6598          /* sizeof(struct fcoe_statistics_params) + */
6599          (sizeof(struct per_queue_stats) * num_queue_stats));
6600 
6601     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6602                       &sc->fw_stats_dma, "fw stats") != 0) {
6603         bxe_free_fw_stats_mem(sc);
6604         return (-1);
6605     }
6606 
6607     /* set up the shortcuts */
6608 
6609     sc->fw_stats_req =
6610         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6611     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6612 
6613     sc->fw_stats_data =
6614         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6615                                      sc->fw_stats_req_size);
6616     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6617                                  sc->fw_stats_req_size);
6618 
6619     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6620           (uintmax_t)sc->fw_stats_req_mapping);
6621 
6622     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6623           (uintmax_t)sc->fw_stats_data_mapping);
6624 
6625     return (0);
6626 }
6627 
6628 /*
6629  * Bits map:
6630  * 0-7  - Engine0 load counter.
6631  * 8-15 - Engine1 load counter.
6632  * 16   - Engine0 RESET_IN_PROGRESS bit.
6633  * 17   - Engine1 RESET_IN_PROGRESS bit.
6634  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6635  *        function on the engine
6636  * 19   - Engine1 ONE_IS_LOADED.
6637  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6638  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6639  *        for just the one belonging to its engine).
6640  */
6641 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6642 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6643 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6644 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6645 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6646 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6647 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6648 #define BXE_GLOBAL_RESET_BIT      0x00040000
6649 
6650 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6651 static void
6652 bxe_set_reset_global(struct bxe_softc *sc)
6653 {
6654     uint32_t val;
6655     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6656     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6657     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6658     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6659 }
6660 
6661 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6662 static void
6663 bxe_clear_reset_global(struct bxe_softc *sc)
6664 {
6665     uint32_t val;
6666     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6667     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6668     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6669     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6670 }
6671 
6672 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6673 static uint8_t
6674 bxe_reset_is_global(struct bxe_softc *sc)
6675 {
6676     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6677     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6678     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6679 }
6680 
6681 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6682 static void
6683 bxe_set_reset_done(struct bxe_softc *sc)
6684 {
6685     uint32_t val;
6686     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6687                                  BXE_PATH0_RST_IN_PROG_BIT;
6688 
6689     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6690 
6691     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6692     /* Clear the bit */
6693     val &= ~bit;
6694     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6695 
6696     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6697 }
6698 
6699 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6700 static void
6701 bxe_set_reset_in_progress(struct bxe_softc *sc)
6702 {
6703     uint32_t val;
6704     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6705                                  BXE_PATH0_RST_IN_PROG_BIT;
6706 
6707     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6708 
6709     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6710     /* Set the bit */
6711     val |= bit;
6712     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6713 
6714     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6715 }
6716 
6717 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6718 static uint8_t
6719 bxe_reset_is_done(struct bxe_softc *sc,
6720                   int              engine)
6721 {
6722     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6723     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6724                             BXE_PATH0_RST_IN_PROG_BIT;
6725 
6726     /* return false if bit is set */
6727     return (val & bit) ? FALSE : TRUE;
6728 }
6729 
6730 /* get the load status for an engine, should be run under rtnl lock */
6731 static uint8_t
6732 bxe_get_load_status(struct bxe_softc *sc,
6733                     int              engine)
6734 {
6735     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6736                              BXE_PATH0_LOAD_CNT_MASK;
6737     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6738                               BXE_PATH0_LOAD_CNT_SHIFT;
6739     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6740 
6741     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6742 
6743     val = ((val & mask) >> shift);
6744 
6745     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6746 
6747     return (val != 0);
6748 }
6749 
6750 /* set pf load mark */
6751 /* XXX needs to be under rtnl lock */
6752 static void
6753 bxe_set_pf_load(struct bxe_softc *sc)
6754 {
6755     uint32_t val;
6756     uint32_t val1;
6757     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6758                                   BXE_PATH0_LOAD_CNT_MASK;
6759     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6760                                    BXE_PATH0_LOAD_CNT_SHIFT;
6761 
6762     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6763 
6764     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6765     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6766 
6767     /* get the current counter value */
6768     val1 = ((val & mask) >> shift);
6769 
6770     /* set bit of this PF */
6771     val1 |= (1 << SC_ABS_FUNC(sc));
6772 
6773     /* clear the old value */
6774     val &= ~mask;
6775 
6776     /* set the new one */
6777     val |= ((val1 << shift) & mask);
6778 
6779     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6780 
6781     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6782 }
6783 
6784 /* clear pf load mark */
6785 /* XXX needs to be under rtnl lock */
6786 static uint8_t
6787 bxe_clear_pf_load(struct bxe_softc *sc)
6788 {
6789     uint32_t val1, val;
6790     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6791                                   BXE_PATH0_LOAD_CNT_MASK;
6792     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6793                                    BXE_PATH0_LOAD_CNT_SHIFT;
6794 
6795     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6796     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6797     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6798 
6799     /* get the current counter value */
6800     val1 = (val & mask) >> shift;
6801 
6802     /* clear bit of that PF */
6803     val1 &= ~(1 << SC_ABS_FUNC(sc));
6804 
6805     /* clear the old value */
6806     val &= ~mask;
6807 
6808     /* set the new one */
6809     val |= ((val1 << shift) & mask);
6810 
6811     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6812     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6813     return (val1 != 0);
6814 }
6815 
6816 /* send load requrest to mcp and analyze response */
6817 static int
6818 bxe_nic_load_request(struct bxe_softc *sc,
6819                      uint32_t         *load_code)
6820 {
6821     /* init fw_seq */
6822     sc->fw_seq =
6823         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6824          DRV_MSG_SEQ_NUMBER_MASK);
6825 
6826     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6827 
6828     /* get the current FW pulse sequence */
6829     sc->fw_drv_pulse_wr_seq =
6830         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6831          DRV_PULSE_SEQ_MASK);
6832 
6833     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6834           sc->fw_drv_pulse_wr_seq);
6835 
6836     /* load request */
6837     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6838                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6839 
6840     /* if the MCP fails to respond we must abort */
6841     if (!(*load_code)) {
6842         BLOGE(sc, "MCP response failure!\n");
6843         return (-1);
6844     }
6845 
6846     /* if MCP refused then must abort */
6847     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6848         BLOGE(sc, "MCP refused load request\n");
6849         return (-1);
6850     }
6851 
6852     return (0);
6853 }
6854 
6855 /*
6856  * Check whether another PF has already loaded FW to chip. In virtualized
6857  * environments a pf from anoth VM may have already initialized the device
6858  * including loading FW.
6859  */
6860 static int
6861 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6862                          uint32_t         load_code)
6863 {
6864     uint32_t my_fw, loaded_fw;
6865 
6866     /* is another pf loaded on this engine? */
6867     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6868         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6869         /* build my FW version dword */
6870         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6871                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6872                  (BCM_5710_FW_REVISION_VERSION << 16) +
6873                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6874 
6875         /* read loaded FW from chip */
6876         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6877         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6878               loaded_fw, my_fw);
6879 
6880         /* abort nic load if version mismatch */
6881         if (my_fw != loaded_fw) {
6882             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6883                   loaded_fw, my_fw);
6884             return (-1);
6885         }
6886     }
6887 
6888     return (0);
6889 }
6890 
6891 /* mark PMF if applicable */
6892 static void
6893 bxe_nic_load_pmf(struct bxe_softc *sc,
6894                  uint32_t         load_code)
6895 {
6896     uint32_t ncsi_oem_data_addr;
6897 
6898     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6899         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6900         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6901         /*
6902          * Barrier here for ordering between the writing to sc->port.pmf here
6903          * and reading it from the periodic task.
6904          */
6905         sc->port.pmf = 1;
6906         mb();
6907     } else {
6908         sc->port.pmf = 0;
6909     }
6910 
6911     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6912 
6913     /* XXX needed? */
6914     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6915         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6916             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6917             if (ncsi_oem_data_addr) {
6918                 REG_WR(sc,
6919                        (ncsi_oem_data_addr +
6920                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6921                        0);
6922             }
6923         }
6924     }
6925 }
6926 
6927 static void
6928 bxe_read_mf_cfg(struct bxe_softc *sc)
6929 {
6930     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6931     int abs_func;
6932     int vn;
6933 
6934     if (BXE_NOMCP(sc)) {
6935         return; /* what should be the default bvalue in this case */
6936     }
6937 
6938     /*
6939      * The formula for computing the absolute function number is...
6940      * For 2 port configuration (4 functions per port):
6941      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6942      * For 4 port configuration (2 functions per port):
6943      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6944      */
6945     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6946         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6947         if (abs_func >= E1H_FUNC_MAX) {
6948             break;
6949         }
6950         sc->devinfo.mf_info.mf_config[vn] =
6951             MFCFG_RD(sc, func_mf_config[abs_func].config);
6952     }
6953 
6954     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6955         FUNC_MF_CFG_FUNC_DISABLED) {
6956         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6957         sc->flags |= BXE_MF_FUNC_DIS;
6958     } else {
6959         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6960         sc->flags &= ~BXE_MF_FUNC_DIS;
6961     }
6962 }
6963 
6964 /* acquire split MCP access lock register */
6965 static int bxe_acquire_alr(struct bxe_softc *sc)
6966 {
6967     uint32_t j, val;
6968 
6969     for (j = 0; j < 1000; j++) {
6970         val = (1UL << 31);
6971         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6972         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6973         if (val & (1L << 31))
6974             break;
6975 
6976         DELAY(5000);
6977     }
6978 
6979     if (!(val & (1L << 31))) {
6980         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6981         return (-1);
6982     }
6983 
6984     return (0);
6985 }
6986 
6987 /* release split MCP access lock register */
6988 static void bxe_release_alr(struct bxe_softc *sc)
6989 {
6990     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6991 }
6992 
6993 static void
6994 bxe_fan_failure(struct bxe_softc *sc)
6995 {
6996     int port = SC_PORT(sc);
6997     uint32_t ext_phy_config;
6998 
6999     /* mark the failure */
7000     ext_phy_config =
7001         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7002 
7003     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7004     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7005     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7006              ext_phy_config);
7007 
7008     /* log the failure */
7009     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7010               "the card to prevent permanent damage. "
7011               "Please contact OEM Support for assistance\n");
7012 
7013     /* XXX */
7014 #if 1
7015     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7016 #else
7017     /*
7018      * Schedule device reset (unload)
7019      * This is due to some boards consuming sufficient power when driver is
7020      * up to overheat if fan fails.
7021      */
7022     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7023     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7024 #endif
7025 }
7026 
7027 /* this function is called upon a link interrupt */
7028 static void
7029 bxe_link_attn(struct bxe_softc *sc)
7030 {
7031     uint32_t pause_enabled = 0;
7032     struct host_port_stats *pstats;
7033     int cmng_fns;
7034     struct bxe_fastpath *fp;
7035     int i;
7036 
7037     /* Make sure that we are synced with the current statistics */
7038     bxe_stats_handle(sc, STATS_EVENT_STOP);
7039 	BLOGI(sc, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7040     elink_link_update(&sc->link_params, &sc->link_vars);
7041 
7042     if (sc->link_vars.link_up) {
7043 
7044         /* dropless flow control */
7045         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7046             pause_enabled = 0;
7047 
7048             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7049                 pause_enabled = 1;
7050             }
7051 
7052             REG_WR(sc,
7053                    (BAR_USTRORM_INTMEM +
7054                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7055                    pause_enabled);
7056         }
7057 
7058         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7059             pstats = BXE_SP(sc, port_stats);
7060             /* reset old mac stats */
7061             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7062         }
7063 
7064         if (sc->state == BXE_STATE_OPEN) {
7065             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7066         }
7067 
7068 	/* Restart tx when the link comes back. */
7069         FOR_EACH_ETH_QUEUE(sc, i) {
7070             fp = &sc->fp[i];
7071             taskqueue_enqueue(fp->tq, &fp->tx_task);
7072 	}
7073     }
7074 
7075     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7076         cmng_fns = bxe_get_cmng_fns_mode(sc);
7077 
7078         if (cmng_fns != CMNG_FNS_NONE) {
7079             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7080             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7081         } else {
7082             /* rate shaping and fairness are disabled */
7083             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7084         }
7085     }
7086 
7087     bxe_link_report_locked(sc);
7088 
7089     if (IS_MF(sc)) {
7090         ; // XXX bxe_link_sync_notify(sc);
7091     }
7092 }
7093 
7094 static void
7095 bxe_attn_int_asserted(struct bxe_softc *sc,
7096                       uint32_t         asserted)
7097 {
7098     int port = SC_PORT(sc);
7099     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7100                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7101     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7102                                         NIG_REG_MASK_INTERRUPT_PORT0;
7103     uint32_t aeu_mask;
7104     uint32_t nig_mask = 0;
7105     uint32_t reg_addr;
7106     uint32_t igu_acked;
7107     uint32_t cnt;
7108 
7109     if (sc->attn_state & asserted) {
7110         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7111     }
7112 
7113     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7114 
7115     aeu_mask = REG_RD(sc, aeu_addr);
7116 
7117     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7118           aeu_mask, asserted);
7119 
7120     aeu_mask &= ~(asserted & 0x3ff);
7121 
7122     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7123 
7124     REG_WR(sc, aeu_addr, aeu_mask);
7125 
7126     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7127 
7128     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7129     sc->attn_state |= asserted;
7130     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7131 
7132     if (asserted & ATTN_HARD_WIRED_MASK) {
7133         if (asserted & ATTN_NIG_FOR_FUNC) {
7134 
7135 	    bxe_acquire_phy_lock(sc);
7136             /* save nig interrupt mask */
7137             nig_mask = REG_RD(sc, nig_int_mask_addr);
7138 
7139             /* If nig_mask is not set, no need to call the update function */
7140             if (nig_mask) {
7141                 REG_WR(sc, nig_int_mask_addr, 0);
7142 
7143                 bxe_link_attn(sc);
7144             }
7145 
7146             /* handle unicore attn? */
7147         }
7148 
7149         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7150             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7151         }
7152 
7153         if (asserted & GPIO_2_FUNC) {
7154             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7155         }
7156 
7157         if (asserted & GPIO_3_FUNC) {
7158             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7159         }
7160 
7161         if (asserted & GPIO_4_FUNC) {
7162             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7163         }
7164 
7165         if (port == 0) {
7166             if (asserted & ATTN_GENERAL_ATTN_1) {
7167                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7168                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7169             }
7170             if (asserted & ATTN_GENERAL_ATTN_2) {
7171                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7172                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7173             }
7174             if (asserted & ATTN_GENERAL_ATTN_3) {
7175                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7176                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7177             }
7178         } else {
7179             if (asserted & ATTN_GENERAL_ATTN_4) {
7180                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7181                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7182             }
7183             if (asserted & ATTN_GENERAL_ATTN_5) {
7184                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7185                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7186             }
7187             if (asserted & ATTN_GENERAL_ATTN_6) {
7188                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7189                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7190             }
7191         }
7192     } /* hardwired */
7193 
7194     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7195         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7196     } else {
7197         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7198     }
7199 
7200     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7201           asserted,
7202           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7203     REG_WR(sc, reg_addr, asserted);
7204 
7205     /* now set back the mask */
7206     if (asserted & ATTN_NIG_FOR_FUNC) {
7207         /*
7208          * Verify that IGU ack through BAR was written before restoring
7209          * NIG mask. This loop should exit after 2-3 iterations max.
7210          */
7211         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7212             cnt = 0;
7213 
7214             do {
7215                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7216             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7217                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7218 
7219             if (!igu_acked) {
7220                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7221             }
7222 
7223             mb();
7224         }
7225 
7226         REG_WR(sc, nig_int_mask_addr, nig_mask);
7227 
7228 	bxe_release_phy_lock(sc);
7229     }
7230 }
7231 
7232 static void
7233 bxe_print_next_block(struct bxe_softc *sc,
7234                      int              idx,
7235                      const char       *blk)
7236 {
7237     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7238 }
7239 
7240 static int
7241 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7242                               uint32_t         sig,
7243                               int              par_num,
7244                               uint8_t          print)
7245 {
7246     uint32_t cur_bit = 0;
7247     int i = 0;
7248 
7249     for (i = 0; sig; i++) {
7250         cur_bit = ((uint32_t)0x1 << i);
7251         if (sig & cur_bit) {
7252             switch (cur_bit) {
7253             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7254                 if (print)
7255                     bxe_print_next_block(sc, par_num++, "BRB");
7256                 break;
7257             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7258                 if (print)
7259                     bxe_print_next_block(sc, par_num++, "PARSER");
7260                 break;
7261             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7262                 if (print)
7263                     bxe_print_next_block(sc, par_num++, "TSDM");
7264                 break;
7265             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7266                 if (print)
7267                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7268                 break;
7269             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7270                 if (print)
7271                     bxe_print_next_block(sc, par_num++, "TCM");
7272                 break;
7273             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7274                 if (print)
7275                     bxe_print_next_block(sc, par_num++, "TSEMI");
7276                 break;
7277             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7278                 if (print)
7279                     bxe_print_next_block(sc, par_num++, "XPB");
7280                 break;
7281             }
7282 
7283             /* Clear the bit */
7284             sig &= ~cur_bit;
7285         }
7286     }
7287 
7288     return (par_num);
7289 }
7290 
7291 static int
7292 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7293                               uint32_t         sig,
7294                               int              par_num,
7295                               uint8_t          *global,
7296                               uint8_t          print)
7297 {
7298     int i = 0;
7299     uint32_t cur_bit = 0;
7300     for (i = 0; sig; i++) {
7301         cur_bit = ((uint32_t)0x1 << i);
7302         if (sig & cur_bit) {
7303             switch (cur_bit) {
7304             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7305                 if (print)
7306                     bxe_print_next_block(sc, par_num++, "PBF");
7307                 break;
7308             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7309                 if (print)
7310                     bxe_print_next_block(sc, par_num++, "QM");
7311                 break;
7312             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7313                 if (print)
7314                     bxe_print_next_block(sc, par_num++, "TM");
7315                 break;
7316             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7317                 if (print)
7318                     bxe_print_next_block(sc, par_num++, "XSDM");
7319                 break;
7320             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7321                 if (print)
7322                     bxe_print_next_block(sc, par_num++, "XCM");
7323                 break;
7324             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7325                 if (print)
7326                     bxe_print_next_block(sc, par_num++, "XSEMI");
7327                 break;
7328             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7329                 if (print)
7330                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7331                 break;
7332             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7333                 if (print)
7334                     bxe_print_next_block(sc, par_num++, "NIG");
7335                 break;
7336             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7337                 if (print)
7338                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7339                 *global = TRUE;
7340                 break;
7341             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7342                 if (print)
7343                     bxe_print_next_block(sc, par_num++, "DEBUG");
7344                 break;
7345             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7346                 if (print)
7347                     bxe_print_next_block(sc, par_num++, "USDM");
7348                 break;
7349             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7350                 if (print)
7351                     bxe_print_next_block(sc, par_num++, "UCM");
7352                 break;
7353             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7354                 if (print)
7355                     bxe_print_next_block(sc, par_num++, "USEMI");
7356                 break;
7357             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7358                 if (print)
7359                     bxe_print_next_block(sc, par_num++, "UPB");
7360                 break;
7361             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7362                 if (print)
7363                     bxe_print_next_block(sc, par_num++, "CSDM");
7364                 break;
7365             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7366                 if (print)
7367                     bxe_print_next_block(sc, par_num++, "CCM");
7368                 break;
7369             }
7370 
7371             /* Clear the bit */
7372             sig &= ~cur_bit;
7373         }
7374     }
7375 
7376     return (par_num);
7377 }
7378 
7379 static int
7380 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7381                               uint32_t         sig,
7382                               int              par_num,
7383                               uint8_t          print)
7384 {
7385     uint32_t cur_bit = 0;
7386     int i = 0;
7387 
7388     for (i = 0; sig; i++) {
7389         cur_bit = ((uint32_t)0x1 << i);
7390         if (sig & cur_bit) {
7391             switch (cur_bit) {
7392             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7393                 if (print)
7394                     bxe_print_next_block(sc, par_num++, "CSEMI");
7395                 break;
7396             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7397                 if (print)
7398                     bxe_print_next_block(sc, par_num++, "PXP");
7399                 break;
7400             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7401                 if (print)
7402                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7403                 break;
7404             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7405                 if (print)
7406                     bxe_print_next_block(sc, par_num++, "CFC");
7407                 break;
7408             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7409                 if (print)
7410                     bxe_print_next_block(sc, par_num++, "CDU");
7411                 break;
7412             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7413                 if (print)
7414                     bxe_print_next_block(sc, par_num++, "DMAE");
7415                 break;
7416             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7417                 if (print)
7418                     bxe_print_next_block(sc, par_num++, "IGU");
7419                 break;
7420             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7421                 if (print)
7422                     bxe_print_next_block(sc, par_num++, "MISC");
7423                 break;
7424             }
7425 
7426             /* Clear the bit */
7427             sig &= ~cur_bit;
7428         }
7429     }
7430 
7431     return (par_num);
7432 }
7433 
7434 static int
7435 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7436                               uint32_t         sig,
7437                               int              par_num,
7438                               uint8_t          *global,
7439                               uint8_t          print)
7440 {
7441     uint32_t cur_bit = 0;
7442     int i = 0;
7443 
7444     for (i = 0; sig; i++) {
7445         cur_bit = ((uint32_t)0x1 << i);
7446         if (sig & cur_bit) {
7447             switch (cur_bit) {
7448             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7449                 if (print)
7450                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7451                 *global = TRUE;
7452                 break;
7453             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7454                 if (print)
7455                     bxe_print_next_block(sc, par_num++,
7456                               "MCP UMP RX");
7457                 *global = TRUE;
7458                 break;
7459             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7460                 if (print)
7461                     bxe_print_next_block(sc, par_num++,
7462                               "MCP UMP TX");
7463                 *global = TRUE;
7464                 break;
7465             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7466                 if (print)
7467                     bxe_print_next_block(sc, par_num++,
7468                               "MCP SCPAD");
7469                 *global = TRUE;
7470                 break;
7471             }
7472 
7473             /* Clear the bit */
7474             sig &= ~cur_bit;
7475         }
7476     }
7477 
7478     return (par_num);
7479 }
7480 
7481 static int
7482 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7483                               uint32_t         sig,
7484                               int              par_num,
7485                               uint8_t          print)
7486 {
7487     uint32_t cur_bit = 0;
7488     int i = 0;
7489 
7490     for (i = 0; sig; i++) {
7491         cur_bit = ((uint32_t)0x1 << i);
7492         if (sig & cur_bit) {
7493             switch (cur_bit) {
7494             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7495                 if (print)
7496                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7497                 break;
7498             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7499                 if (print)
7500                     bxe_print_next_block(sc, par_num++, "ATC");
7501                 break;
7502             }
7503 
7504             /* Clear the bit */
7505             sig &= ~cur_bit;
7506         }
7507     }
7508 
7509     return (par_num);
7510 }
7511 
7512 static uint8_t
7513 bxe_parity_attn(struct bxe_softc *sc,
7514                 uint8_t          *global,
7515                 uint8_t          print,
7516                 uint32_t         *sig)
7517 {
7518     int par_num = 0;
7519 
7520     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7521         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7522         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7523         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7524         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7525         BLOGE(sc, "Parity error: HW block parity attention:\n"
7526                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7527               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7528               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7529               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7530               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7531               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7532 
7533         if (print)
7534             BLOGI(sc, "Parity errors detected in blocks: ");
7535 
7536         par_num =
7537             bxe_check_blocks_with_parity0(sc, sig[0] &
7538                                           HW_PRTY_ASSERT_SET_0,
7539                                           par_num, print);
7540         par_num =
7541             bxe_check_blocks_with_parity1(sc, sig[1] &
7542                                           HW_PRTY_ASSERT_SET_1,
7543                                           par_num, global, print);
7544         par_num =
7545             bxe_check_blocks_with_parity2(sc, sig[2] &
7546                                           HW_PRTY_ASSERT_SET_2,
7547                                           par_num, print);
7548         par_num =
7549             bxe_check_blocks_with_parity3(sc, sig[3] &
7550                                           HW_PRTY_ASSERT_SET_3,
7551                                           par_num, global, print);
7552         par_num =
7553             bxe_check_blocks_with_parity4(sc, sig[4] &
7554                                           HW_PRTY_ASSERT_SET_4,
7555                                           par_num, print);
7556 
7557         if (print)
7558             BLOGI(sc, "\n");
7559 
7560         return (TRUE);
7561     }
7562 
7563     return (FALSE);
7564 }
7565 
7566 static uint8_t
7567 bxe_chk_parity_attn(struct bxe_softc *sc,
7568                     uint8_t          *global,
7569                     uint8_t          print)
7570 {
7571     struct attn_route attn = { {0} };
7572     int port = SC_PORT(sc);
7573 
7574     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7575     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7576     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7577     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7578 
7579     /*
7580      * Since MCP attentions can't be disabled inside the block, we need to
7581      * read AEU registers to see whether they're currently disabled
7582      */
7583     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7584                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7585                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7586                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7587 
7588 
7589     if (!CHIP_IS_E1x(sc))
7590         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7591 
7592     return (bxe_parity_attn(sc, global, print, attn.sig));
7593 }
7594 
7595 static void
7596 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7597                          uint32_t         attn)
7598 {
7599     uint32_t val;
7600 
7601     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7602         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7603         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7604         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7605             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7606         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7607             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7608         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7609             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7610         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7611             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7612         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7613             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7614         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7615             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7616         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7617             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7618         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7619             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7620         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7621             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7622     }
7623 
7624     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7625         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7626         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7627         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7628             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7629         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7630             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7631         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7632             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7633         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7634             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7635         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7636             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7637         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7638             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7639     }
7640 
7641     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7642                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7643         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7644               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7645                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7646     }
7647 }
7648 
7649 static void
7650 bxe_e1h_disable(struct bxe_softc *sc)
7651 {
7652     int port = SC_PORT(sc);
7653 
7654     bxe_tx_disable(sc);
7655 
7656     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7657 }
7658 
7659 static void
7660 bxe_e1h_enable(struct bxe_softc *sc)
7661 {
7662     int port = SC_PORT(sc);
7663 
7664     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7665 
7666     // XXX bxe_tx_enable(sc);
7667 }
7668 
7669 /*
7670  * called due to MCP event (on pmf):
7671  *   reread new bandwidth configuration
7672  *   configure FW
7673  *   notify others function about the change
7674  */
7675 static void
7676 bxe_config_mf_bw(struct bxe_softc *sc)
7677 {
7678     if (sc->link_vars.link_up) {
7679         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7680         // XXX bxe_link_sync_notify(sc);
7681     }
7682 
7683     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7684 }
7685 
7686 static void
7687 bxe_set_mf_bw(struct bxe_softc *sc)
7688 {
7689     bxe_config_mf_bw(sc);
7690     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7691 }
7692 
7693 static void
7694 bxe_handle_eee_event(struct bxe_softc *sc)
7695 {
7696     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7697     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7698 }
7699 
7700 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7701 
7702 static void
7703 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7704 {
7705     struct eth_stats_info *ether_stat =
7706         &sc->sp->drv_info_to_mcp.ether_stat;
7707 
7708     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7709             ETH_STAT_INFO_VERSION_LEN);
7710 
7711     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7712     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7713                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7714                                           ether_stat->mac_local + MAC_PAD,
7715                                           MAC_PAD, ETH_ALEN);
7716 
7717     ether_stat->mtu_size = sc->mtu;
7718 
7719     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7720     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7721         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7722     }
7723 
7724     // XXX ether_stat->feature_flags |= ???;
7725 
7726     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7727 
7728     ether_stat->txq_size = sc->tx_ring_size;
7729     ether_stat->rxq_size = sc->rx_ring_size;
7730 }
7731 
7732 static void
7733 bxe_handle_drv_info_req(struct bxe_softc *sc)
7734 {
7735     enum drv_info_opcode op_code;
7736     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7737 
7738     /* if drv_info version supported by MFW doesn't match - send NACK */
7739     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7740         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7741         return;
7742     }
7743 
7744     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7745                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7746 
7747     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7748 
7749     switch (op_code) {
7750     case ETH_STATS_OPCODE:
7751         bxe_drv_info_ether_stat(sc);
7752         break;
7753     case FCOE_STATS_OPCODE:
7754     case ISCSI_STATS_OPCODE:
7755     default:
7756         /* if op code isn't supported - send NACK */
7757         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7758         return;
7759     }
7760 
7761     /*
7762      * If we got drv_info attn from MFW then these fields are defined in
7763      * shmem2 for sure
7764      */
7765     SHMEM2_WR(sc, drv_info_host_addr_lo,
7766               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7767     SHMEM2_WR(sc, drv_info_host_addr_hi,
7768               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7769 
7770     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7771 }
7772 
7773 static void
7774 bxe_dcc_event(struct bxe_softc *sc,
7775               uint32_t         dcc_event)
7776 {
7777     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7778 
7779     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7780         /*
7781          * This is the only place besides the function initialization
7782          * where the sc->flags can change so it is done without any
7783          * locks
7784          */
7785         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7786             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7787             sc->flags |= BXE_MF_FUNC_DIS;
7788             bxe_e1h_disable(sc);
7789         } else {
7790             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7791             sc->flags &= ~BXE_MF_FUNC_DIS;
7792             bxe_e1h_enable(sc);
7793         }
7794         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7795     }
7796 
7797     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7798         bxe_config_mf_bw(sc);
7799         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7800     }
7801 
7802     /* Report results to MCP */
7803     if (dcc_event)
7804         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7805     else
7806         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7807 }
7808 
7809 static void
7810 bxe_pmf_update(struct bxe_softc *sc)
7811 {
7812     int port = SC_PORT(sc);
7813     uint32_t val;
7814 
7815     sc->port.pmf = 1;
7816     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7817 
7818     /*
7819      * We need the mb() to ensure the ordering between the writing to
7820      * sc->port.pmf here and reading it from the bxe_periodic_task().
7821      */
7822     mb();
7823 
7824     /* queue a periodic task */
7825     // XXX schedule task...
7826 
7827     // XXX bxe_dcbx_pmf_update(sc);
7828 
7829     /* enable nig attention */
7830     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7831     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7832         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7833         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7834     } else if (!CHIP_IS_E1x(sc)) {
7835         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7836         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7837     }
7838 
7839     bxe_stats_handle(sc, STATS_EVENT_PMF);
7840 }
7841 
7842 static int
7843 bxe_mc_assert(struct bxe_softc *sc)
7844 {
7845     char last_idx;
7846     int i, rc = 0;
7847     uint32_t row0, row1, row2, row3;
7848 
7849     /* XSTORM */
7850     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7851     if (last_idx)
7852         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7853 
7854     /* print the asserts */
7855     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7856 
7857         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7858         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7859         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7860         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7861 
7862         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7863             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7864                   i, row3, row2, row1, row0);
7865             rc++;
7866         } else {
7867             break;
7868         }
7869     }
7870 
7871     /* TSTORM */
7872     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7873     if (last_idx) {
7874         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7875     }
7876 
7877     /* print the asserts */
7878     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7879 
7880         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7881         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7882         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7883         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7884 
7885         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7886             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7887                   i, row3, row2, row1, row0);
7888             rc++;
7889         } else {
7890             break;
7891         }
7892     }
7893 
7894     /* CSTORM */
7895     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7896     if (last_idx) {
7897         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7898     }
7899 
7900     /* print the asserts */
7901     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7902 
7903         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7904         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7905         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7906         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7907 
7908         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7909             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7910                   i, row3, row2, row1, row0);
7911             rc++;
7912         } else {
7913             break;
7914         }
7915     }
7916 
7917     /* USTORM */
7918     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7919     if (last_idx) {
7920         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7921     }
7922 
7923     /* print the asserts */
7924     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7925 
7926         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7927         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7928         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7929         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7930 
7931         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7932             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7933                   i, row3, row2, row1, row0);
7934             rc++;
7935         } else {
7936             break;
7937         }
7938     }
7939 
7940     return (rc);
7941 }
7942 
7943 static void
7944 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7945                          uint32_t         attn)
7946 {
7947     int func = SC_FUNC(sc);
7948     uint32_t val;
7949 
7950     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7951 
7952         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7953 
7954             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7955             bxe_read_mf_cfg(sc);
7956             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7957                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7958             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7959 
7960             if (val & DRV_STATUS_DCC_EVENT_MASK)
7961                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7962 
7963             if (val & DRV_STATUS_SET_MF_BW)
7964                 bxe_set_mf_bw(sc);
7965 
7966             if (val & DRV_STATUS_DRV_INFO_REQ)
7967                 bxe_handle_drv_info_req(sc);
7968 
7969             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7970                 bxe_pmf_update(sc);
7971 
7972             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7973                 bxe_handle_eee_event(sc);
7974 
7975             if (sc->link_vars.periodic_flags &
7976                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7977                 /* sync with link */
7978 		bxe_acquire_phy_lock(sc);
7979                 sc->link_vars.periodic_flags &=
7980                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7981 		bxe_release_phy_lock(sc);
7982                 if (IS_MF(sc))
7983                     ; // XXX bxe_link_sync_notify(sc);
7984                 bxe_link_report(sc);
7985             }
7986 
7987             /*
7988              * Always call it here: bxe_link_report() will
7989              * prevent the link indication duplication.
7990              */
7991             bxe_link_status_update(sc);
7992 
7993         } else if (attn & BXE_MC_ASSERT_BITS) {
7994 
7995             BLOGE(sc, "MC assert!\n");
7996             bxe_mc_assert(sc);
7997             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
7998             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
7999             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8000             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8001             bxe_panic(sc, ("MC assert!\n"));
8002 
8003         } else if (attn & BXE_MCP_ASSERT) {
8004 
8005             BLOGE(sc, "MCP assert!\n");
8006             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8007             // XXX bxe_fw_dump(sc);
8008 
8009         } else {
8010             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8011         }
8012     }
8013 
8014     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8015         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8016         if (attn & BXE_GRC_TIMEOUT) {
8017             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8018             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8019         }
8020         if (attn & BXE_GRC_RSV) {
8021             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8022             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8023         }
8024         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8025     }
8026 }
8027 
8028 static void
8029 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8030                          uint32_t         attn)
8031 {
8032     int port = SC_PORT(sc);
8033     int reg_offset;
8034     uint32_t val0, mask0, val1, mask1;
8035     uint32_t val;
8036 
8037     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8038         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8039         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8040         /* CFC error attention */
8041         if (val & 0x2) {
8042             BLOGE(sc, "FATAL error from CFC\n");
8043         }
8044     }
8045 
8046     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8047         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8048         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8049         /* RQ_USDMDP_FIFO_OVERFLOW */
8050         if (val & 0x18000) {
8051             BLOGE(sc, "FATAL error from PXP\n");
8052         }
8053 
8054         if (!CHIP_IS_E1x(sc)) {
8055             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8056             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8057         }
8058     }
8059 
8060 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8061 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8062 
8063     if (attn & AEU_PXP2_HW_INT_BIT) {
8064         /*  CQ47854 workaround do not panic on
8065          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8066          */
8067         if (!CHIP_IS_E1x(sc)) {
8068             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8069             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8070             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8071             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8072             /*
8073              * If the only PXP2_EOP_ERROR_BIT is set in
8074              * STS0 and STS1 - clear it
8075              *
8076              * probably we lose additional attentions between
8077              * STS0 and STS_CLR0, in this case user will not
8078              * be notified about them
8079              */
8080             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8081                 !(val1 & mask1))
8082                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8083 
8084             /* print the register, since no one can restore it */
8085             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8086 
8087             /*
8088              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8089              * then notify
8090              */
8091             if (val0 & PXP2_EOP_ERROR_BIT) {
8092                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8093 
8094                 /*
8095                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8096                  * set then clear attention from PXP2 block without panic
8097                  */
8098                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8099                     ((val1 & mask1) == 0))
8100                     attn &= ~AEU_PXP2_HW_INT_BIT;
8101             }
8102         }
8103     }
8104 
8105     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8106         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8107                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8108 
8109         val = REG_RD(sc, reg_offset);
8110         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8111         REG_WR(sc, reg_offset, val);
8112 
8113         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8114               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8115         bxe_panic(sc, ("HW block attention set2\n"));
8116     }
8117 }
8118 
8119 static void
8120 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8121                          uint32_t         attn)
8122 {
8123     int port = SC_PORT(sc);
8124     int reg_offset;
8125     uint32_t val;
8126 
8127     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8128         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8129         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8130         /* DORQ discard attention */
8131         if (val & 0x2) {
8132             BLOGE(sc, "FATAL error from DORQ\n");
8133         }
8134     }
8135 
8136     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8137         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8138                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8139 
8140         val = REG_RD(sc, reg_offset);
8141         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8142         REG_WR(sc, reg_offset, val);
8143 
8144         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8145               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8146         bxe_panic(sc, ("HW block attention set1\n"));
8147     }
8148 }
8149 
8150 static void
8151 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8152                          uint32_t         attn)
8153 {
8154     int port = SC_PORT(sc);
8155     int reg_offset;
8156     uint32_t val;
8157 
8158     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8159                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8160 
8161     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8162         val = REG_RD(sc, reg_offset);
8163         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8164         REG_WR(sc, reg_offset, val);
8165 
8166         BLOGW(sc, "SPIO5 hw attention\n");
8167 
8168         /* Fan failure attention */
8169         elink_hw_reset_phy(&sc->link_params);
8170         bxe_fan_failure(sc);
8171     }
8172 
8173     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8174 	bxe_acquire_phy_lock(sc);
8175         elink_handle_module_detect_int(&sc->link_params);
8176 	bxe_release_phy_lock(sc);
8177     }
8178 
8179     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8180         val = REG_RD(sc, reg_offset);
8181         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8182         REG_WR(sc, reg_offset, val);
8183 
8184         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8185                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8186     }
8187 }
8188 
8189 static void
8190 bxe_attn_int_deasserted(struct bxe_softc *sc,
8191                         uint32_t         deasserted)
8192 {
8193     struct attn_route attn;
8194     struct attn_route *group_mask;
8195     int port = SC_PORT(sc);
8196     int index;
8197     uint32_t reg_addr;
8198     uint32_t val;
8199     uint32_t aeu_mask;
8200     uint8_t global = FALSE;
8201 
8202     /*
8203      * Need to take HW lock because MCP or other port might also
8204      * try to handle this event.
8205      */
8206     bxe_acquire_alr(sc);
8207 
8208     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8209         /* XXX
8210          * In case of parity errors don't handle attentions so that
8211          * other function would "see" parity errors.
8212          */
8213         sc->recovery_state = BXE_RECOVERY_INIT;
8214         // XXX schedule a recovery task...
8215         /* disable HW interrupts */
8216         bxe_int_disable(sc);
8217         bxe_release_alr(sc);
8218         return;
8219     }
8220 
8221     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8222     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8223     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8224     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8225     if (!CHIP_IS_E1x(sc)) {
8226         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8227     } else {
8228         attn.sig[4] = 0;
8229     }
8230 
8231     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8232           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8233 
8234     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8235         if (deasserted & (1 << index)) {
8236             group_mask = &sc->attn_group[index];
8237 
8238             BLOGD(sc, DBG_INTR,
8239                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8240                   group_mask->sig[0], group_mask->sig[1],
8241                   group_mask->sig[2], group_mask->sig[3],
8242                   group_mask->sig[4]);
8243 
8244             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8245             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8246             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8247             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8248             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8249         }
8250     }
8251 
8252     bxe_release_alr(sc);
8253 
8254     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8255         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8256                     COMMAND_REG_ATTN_BITS_CLR);
8257     } else {
8258         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8259     }
8260 
8261     val = ~deasserted;
8262     BLOGD(sc, DBG_INTR,
8263           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8264           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8265     REG_WR(sc, reg_addr, val);
8266 
8267     if (~sc->attn_state & deasserted) {
8268         BLOGE(sc, "IGU error\n");
8269     }
8270 
8271     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8272                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8273 
8274     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8275 
8276     aeu_mask = REG_RD(sc, reg_addr);
8277 
8278     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8279           aeu_mask, deasserted);
8280     aeu_mask |= (deasserted & 0x3ff);
8281     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8282 
8283     REG_WR(sc, reg_addr, aeu_mask);
8284     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8285 
8286     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8287     sc->attn_state &= ~deasserted;
8288     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8289 }
8290 
8291 static void
8292 bxe_attn_int(struct bxe_softc *sc)
8293 {
8294     /* read local copy of bits */
8295     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8296     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8297     uint32_t attn_state = sc->attn_state;
8298 
8299     /* look for changed bits */
8300     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8301     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8302 
8303     BLOGD(sc, DBG_INTR,
8304           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8305           attn_bits, attn_ack, asserted, deasserted);
8306 
8307     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8308         BLOGE(sc, "BAD attention state\n");
8309     }
8310 
8311     /* handle bits that were raised */
8312     if (asserted) {
8313         bxe_attn_int_asserted(sc, asserted);
8314     }
8315 
8316     if (deasserted) {
8317         bxe_attn_int_deasserted(sc, deasserted);
8318     }
8319 }
8320 
8321 static uint16_t
8322 bxe_update_dsb_idx(struct bxe_softc *sc)
8323 {
8324     struct host_sp_status_block *def_sb = sc->def_sb;
8325     uint16_t rc = 0;
8326 
8327     mb(); /* status block is written to by the chip */
8328 
8329     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8330         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8331         rc |= BXE_DEF_SB_ATT_IDX;
8332     }
8333 
8334     if (sc->def_idx != def_sb->sp_sb.running_index) {
8335         sc->def_idx = def_sb->sp_sb.running_index;
8336         rc |= BXE_DEF_SB_IDX;
8337     }
8338 
8339     mb();
8340 
8341     return (rc);
8342 }
8343 
8344 static inline struct ecore_queue_sp_obj *
8345 bxe_cid_to_q_obj(struct bxe_softc *sc,
8346                  uint32_t         cid)
8347 {
8348     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8349     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8350 }
8351 
8352 static void
8353 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8354 {
8355     struct ecore_mcast_ramrod_params rparam;
8356     int rc;
8357 
8358     memset(&rparam, 0, sizeof(rparam));
8359 
8360     rparam.mcast_obj = &sc->mcast_obj;
8361 
8362     BXE_MCAST_LOCK(sc);
8363 
8364     /* clear pending state for the last command */
8365     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8366 
8367     /* if there are pending mcast commands - send them */
8368     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8369         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8370         if (rc < 0) {
8371             BLOGD(sc, DBG_SP,
8372                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8373         }
8374     }
8375 
8376     BXE_MCAST_UNLOCK(sc);
8377 }
8378 
8379 static void
8380 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8381                               union event_ring_elem *elem)
8382 {
8383     unsigned long ramrod_flags = 0;
8384     int rc = 0;
8385     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8386     struct ecore_vlan_mac_obj *vlan_mac_obj;
8387 
8388     /* always push next commands out, don't wait here */
8389     bit_set(&ramrod_flags, RAMROD_CONT);
8390 
8391     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8392     case ECORE_FILTER_MAC_PENDING:
8393         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8394         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8395         break;
8396 
8397     case ECORE_FILTER_MCAST_PENDING:
8398         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8399         /*
8400          * This is only relevant for 57710 where multicast MACs are
8401          * configured as unicast MACs using the same ramrod.
8402          */
8403         bxe_handle_mcast_eqe(sc);
8404         return;
8405 
8406     default:
8407         BLOGE(sc, "Unsupported classification command: %d\n",
8408               elem->message.data.eth_event.echo);
8409         return;
8410     }
8411 
8412     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8413 
8414     if (rc < 0) {
8415         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8416     } else if (rc > 0) {
8417         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8418     }
8419 }
8420 
8421 static void
8422 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8423                        union event_ring_elem *elem)
8424 {
8425     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8426 
8427     /* send rx_mode command again if was requested */
8428     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8429                                &sc->sp_state)) {
8430         bxe_set_storm_rx_mode(sc);
8431     }
8432 }
8433 
8434 static void
8435 bxe_update_eq_prod(struct bxe_softc *sc,
8436                    uint16_t         prod)
8437 {
8438     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8439     wmb(); /* keep prod updates ordered */
8440 }
8441 
8442 static void
8443 bxe_eq_int(struct bxe_softc *sc)
8444 {
8445     uint16_t hw_cons, sw_cons, sw_prod;
8446     union event_ring_elem *elem;
8447     uint8_t echo;
8448     uint32_t cid;
8449     uint8_t opcode;
8450     int spqe_cnt = 0;
8451     struct ecore_queue_sp_obj *q_obj;
8452     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8453     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8454 
8455     hw_cons = le16toh(*sc->eq_cons_sb);
8456 
8457     /*
8458      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8459      * when we get to the next-page we need to adjust so the loop
8460      * condition below will be met. The next element is the size of a
8461      * regular element and hence incrementing by 1
8462      */
8463     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8464         hw_cons++;
8465     }
8466 
8467     /*
8468      * This function may never run in parallel with itself for a
8469      * specific sc and no need for a read memory barrier here.
8470      */
8471     sw_cons = sc->eq_cons;
8472     sw_prod = sc->eq_prod;
8473 
8474     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8475           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8476 
8477     for (;
8478          sw_cons != hw_cons;
8479          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8480 
8481         elem = &sc->eq[EQ_DESC(sw_cons)];
8482 
8483         /* elem CID originates from FW, actually LE */
8484         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8485         opcode = elem->message.opcode;
8486 
8487         /* handle eq element */
8488         switch (opcode) {
8489 
8490         case EVENT_RING_OPCODE_STAT_QUERY:
8491             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8492                   sc->stats_comp++);
8493             /* nothing to do with stats comp */
8494             goto next_spqe;
8495 
8496         case EVENT_RING_OPCODE_CFC_DEL:
8497             /* handle according to cid range */
8498             /* we may want to verify here that the sc state is HALTING */
8499             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8500             q_obj = bxe_cid_to_q_obj(sc, cid);
8501             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8502                 break;
8503             }
8504             goto next_spqe;
8505 
8506         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8507             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8508             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8509                 break;
8510             }
8511             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8512             goto next_spqe;
8513 
8514         case EVENT_RING_OPCODE_START_TRAFFIC:
8515             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8516             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8517                 break;
8518             }
8519             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8520             goto next_spqe;
8521 
8522         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8523             echo = elem->message.data.function_update_event.echo;
8524             if (echo == SWITCH_UPDATE) {
8525                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8526                 if (f_obj->complete_cmd(sc, f_obj,
8527                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8528                     break;
8529                 }
8530             }
8531             else {
8532                 BLOGD(sc, DBG_SP,
8533                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8534             }
8535             goto next_spqe;
8536 
8537         case EVENT_RING_OPCODE_FORWARD_SETUP:
8538             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8539             if (q_obj->complete_cmd(sc, q_obj,
8540                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8541                 break;
8542             }
8543             goto next_spqe;
8544 
8545         case EVENT_RING_OPCODE_FUNCTION_START:
8546             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8547             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8548                 break;
8549             }
8550             goto next_spqe;
8551 
8552         case EVENT_RING_OPCODE_FUNCTION_STOP:
8553             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8554             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8555                 break;
8556             }
8557             goto next_spqe;
8558         }
8559 
8560         switch (opcode | sc->state) {
8561         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8562         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8563             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8564             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8565             rss_raw->clear_pending(rss_raw);
8566             break;
8567 
8568         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8569         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8570         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8571         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8572         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8573         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8574             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8575             bxe_handle_classification_eqe(sc, elem);
8576             break;
8577 
8578         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8579         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8580         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8581             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8582             bxe_handle_mcast_eqe(sc);
8583             break;
8584 
8585         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8586         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8587         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8588             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8589             bxe_handle_rx_mode_eqe(sc, elem);
8590             break;
8591 
8592         default:
8593             /* unknown event log error and continue */
8594             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8595                   elem->message.opcode, sc->state);
8596         }
8597 
8598 next_spqe:
8599         spqe_cnt++;
8600     } /* for */
8601 
8602     mb();
8603     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8604 
8605     sc->eq_cons = sw_cons;
8606     sc->eq_prod = sw_prod;
8607 
8608     /* make sure that above mem writes were issued towards the memory */
8609     wmb();
8610 
8611     /* update producer */
8612     bxe_update_eq_prod(sc, sc->eq_prod);
8613 }
8614 
8615 static void
8616 bxe_handle_sp_tq(void *context,
8617                  int  pending)
8618 {
8619     struct bxe_softc *sc = (struct bxe_softc *)context;
8620     uint16_t status;
8621 
8622     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8623 
8624     /* what work needs to be performed? */
8625     status = bxe_update_dsb_idx(sc);
8626 
8627     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8628 
8629     /* HW attentions */
8630     if (status & BXE_DEF_SB_ATT_IDX) {
8631         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8632         bxe_attn_int(sc);
8633         status &= ~BXE_DEF_SB_ATT_IDX;
8634     }
8635 
8636     /* SP events: STAT_QUERY and others */
8637     if (status & BXE_DEF_SB_IDX) {
8638         /* handle EQ completions */
8639         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8640         bxe_eq_int(sc);
8641         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8642                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8643         status &= ~BXE_DEF_SB_IDX;
8644     }
8645 
8646     /* if status is non zero then something went wrong */
8647     if (__predict_false(status)) {
8648         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8649     }
8650 
8651     /* ack status block only if something was actually handled */
8652     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8653                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8654 
8655     /*
8656      * Must be called after the EQ processing (since eq leads to sriov
8657      * ramrod completion flows).
8658      * This flow may have been scheduled by the arrival of a ramrod
8659      * completion, or by the sriov code rescheduling itself.
8660      */
8661     // XXX bxe_iov_sp_task(sc);
8662 
8663 }
8664 
8665 static void
8666 bxe_handle_fp_tq(void *context,
8667                  int  pending)
8668 {
8669     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8670     struct bxe_softc *sc = fp->sc;
8671     uint8_t more_tx = FALSE;
8672     uint8_t more_rx = FALSE;
8673 
8674     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8675 
8676     /* XXX
8677      * IFF_DRV_RUNNING state can't be checked here since we process
8678      * slowpath events on a client queue during setup. Instead
8679      * we need to add a "process/continue" flag here that the driver
8680      * can use to tell the task here not to do anything.
8681      */
8682 #if 0
8683     if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8684         return;
8685     }
8686 #endif
8687 
8688     /* update the fastpath index */
8689     bxe_update_fp_sb_idx(fp);
8690 
8691     /* XXX add loop here if ever support multiple tx CoS */
8692     /* fp->txdata[cos] */
8693     if (bxe_has_tx_work(fp)) {
8694         BXE_FP_TX_LOCK(fp);
8695         more_tx = bxe_txeof(sc, fp);
8696         BXE_FP_TX_UNLOCK(fp);
8697     }
8698 
8699     if (bxe_has_rx_work(fp)) {
8700         more_rx = bxe_rxeof(sc, fp);
8701     }
8702 
8703     if (more_rx /*|| more_tx*/) {
8704         /* still more work to do */
8705         taskqueue_enqueue(fp->tq, &fp->tq_task);
8706         return;
8707     }
8708 
8709     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8710                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8711 }
8712 
8713 static void
8714 bxe_task_fp(struct bxe_fastpath *fp)
8715 {
8716     struct bxe_softc *sc = fp->sc;
8717     uint8_t more_tx = FALSE;
8718     uint8_t more_rx = FALSE;
8719 
8720     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8721 
8722     /* update the fastpath index */
8723     bxe_update_fp_sb_idx(fp);
8724 
8725     /* XXX add loop here if ever support multiple tx CoS */
8726     /* fp->txdata[cos] */
8727     if (bxe_has_tx_work(fp)) {
8728         BXE_FP_TX_LOCK(fp);
8729         more_tx = bxe_txeof(sc, fp);
8730         BXE_FP_TX_UNLOCK(fp);
8731     }
8732 
8733     if (bxe_has_rx_work(fp)) {
8734         more_rx = bxe_rxeof(sc, fp);
8735     }
8736 
8737     if (more_rx /*|| more_tx*/) {
8738         /* still more work to do, bail out if this ISR and process later */
8739         taskqueue_enqueue(fp->tq, &fp->tq_task);
8740         return;
8741     }
8742 
8743     /*
8744      * Here we write the fastpath index taken before doing any tx or rx work.
8745      * It is very well possible other hw events occurred up to this point and
8746      * they were actually processed accordingly above. Since we're going to
8747      * write an older fastpath index, an interrupt is coming which we might
8748      * not do any work in.
8749      */
8750     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8751                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8752 }
8753 
8754 /*
8755  * Legacy interrupt entry point.
8756  *
8757  * Verifies that the controller generated the interrupt and
8758  * then calls a separate routine to handle the various
8759  * interrupt causes: link, RX, and TX.
8760  */
8761 static void
8762 bxe_intr_legacy(void *xsc)
8763 {
8764     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8765     struct bxe_fastpath *fp;
8766     uint16_t status, mask;
8767     int i;
8768 
8769     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8770 
8771     /*
8772      * 0 for ustorm, 1 for cstorm
8773      * the bits returned from ack_int() are 0-15
8774      * bit 0 = attention status block
8775      * bit 1 = fast path status block
8776      * a mask of 0x2 or more = tx/rx event
8777      * a mask of 1 = slow path event
8778      */
8779 
8780     status = bxe_ack_int(sc);
8781 
8782     /* the interrupt is not for us */
8783     if (__predict_false(status == 0)) {
8784         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8785         return;
8786     }
8787 
8788     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8789 
8790     FOR_EACH_ETH_QUEUE(sc, i) {
8791         fp = &sc->fp[i];
8792         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8793         if (status & mask) {
8794             /* acknowledge and disable further fastpath interrupts */
8795             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8796             bxe_task_fp(fp);
8797             status &= ~mask;
8798         }
8799     }
8800 
8801     if (__predict_false(status & 0x1)) {
8802         /* acknowledge and disable further slowpath interrupts */
8803         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8804 
8805         /* schedule slowpath handler */
8806         taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8807 
8808         status &= ~0x1;
8809     }
8810 
8811     if (__predict_false(status)) {
8812         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8813     }
8814 }
8815 
8816 /* slowpath interrupt entry point */
8817 static void
8818 bxe_intr_sp(void *xsc)
8819 {
8820     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8821 
8822     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8823 
8824     /* acknowledge and disable further slowpath interrupts */
8825     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8826 
8827     /* schedule slowpath handler */
8828     taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8829 }
8830 
8831 /* fastpath interrupt entry point */
8832 static void
8833 bxe_intr_fp(void *xfp)
8834 {
8835     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8836     struct bxe_softc *sc = fp->sc;
8837 
8838     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8839 
8840     BLOGD(sc, DBG_INTR,
8841           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8842           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8843 
8844     /* acknowledge and disable further fastpath interrupts */
8845     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8846 
8847     bxe_task_fp(fp);
8848 }
8849 
8850 /* Release all interrupts allocated by the driver. */
8851 static void
8852 bxe_interrupt_free(struct bxe_softc *sc)
8853 {
8854     int i;
8855 
8856     switch (sc->interrupt_mode) {
8857     case INTR_MODE_INTX:
8858         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8859         if (sc->intr[0].resource != NULL) {
8860             bus_release_resource(sc->dev,
8861                                  SYS_RES_IRQ,
8862                                  sc->intr[0].rid,
8863                                  sc->intr[0].resource);
8864         }
8865         break;
8866     case INTR_MODE_MSI:
8867         for (i = 0; i < sc->intr_count; i++) {
8868             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8869             if (sc->intr[i].resource && sc->intr[i].rid) {
8870                 bus_release_resource(sc->dev,
8871                                      SYS_RES_IRQ,
8872                                      sc->intr[i].rid,
8873                                      sc->intr[i].resource);
8874             }
8875         }
8876         pci_release_msi(sc->dev);
8877         break;
8878     case INTR_MODE_MSIX:
8879         for (i = 0; i < sc->intr_count; i++) {
8880             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8881             if (sc->intr[i].resource && sc->intr[i].rid) {
8882                 bus_release_resource(sc->dev,
8883                                      SYS_RES_IRQ,
8884                                      sc->intr[i].rid,
8885                                      sc->intr[i].resource);
8886             }
8887         }
8888         pci_release_msi(sc->dev);
8889         break;
8890     default:
8891         /* nothing to do as initial allocation failed */
8892         break;
8893     }
8894 }
8895 
8896 /*
8897  * This function determines and allocates the appropriate
8898  * interrupt based on system capabilites and user request.
8899  *
8900  * The user may force a particular interrupt mode, specify
8901  * the number of receive queues, specify the method for
8902  * distribuitng received frames to receive queues, or use
8903  * the default settings which will automatically select the
8904  * best supported combination.  In addition, the OS may or
8905  * may not support certain combinations of these settings.
8906  * This routine attempts to reconcile the settings requested
8907  * by the user with the capabilites available from the system
8908  * to select the optimal combination of features.
8909  *
8910  * Returns:
8911  *   0 = Success, !0 = Failure.
8912  */
8913 static int
8914 bxe_interrupt_alloc(struct bxe_softc *sc)
8915 {
8916     int msix_count = 0;
8917     int msi_count = 0;
8918     int num_requested = 0;
8919     int num_allocated = 0;
8920     int rid, i, j;
8921     int rc;
8922 
8923     /* get the number of available MSI/MSI-X interrupts from the OS */
8924     if (sc->interrupt_mode > 0) {
8925         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8926             msix_count = pci_msix_count(sc->dev);
8927         }
8928 
8929         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8930             msi_count = pci_msi_count(sc->dev);
8931         }
8932 
8933         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8934               msi_count, msix_count);
8935     }
8936 
8937     do { /* try allocating MSI-X interrupt resources (at least 2) */
8938         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8939             break;
8940         }
8941 
8942         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8943             (msix_count < 2)) {
8944             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8945             break;
8946         }
8947 
8948         /* ask for the necessary number of MSI-X vectors */
8949         num_requested = min((sc->num_queues + 1), msix_count);
8950 
8951         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8952 
8953         num_allocated = num_requested;
8954         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8955             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8956             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8957             break;
8958         }
8959 
8960         if (num_allocated < 2) { /* possible? */
8961             BLOGE(sc, "MSI-X allocation less than 2!\n");
8962             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8963             pci_release_msi(sc->dev);
8964             break;
8965         }
8966 
8967         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8968               num_requested, num_allocated);
8969 
8970         /* best effort so use the number of vectors allocated to us */
8971         sc->intr_count = num_allocated;
8972         sc->num_queues = num_allocated - 1;
8973 
8974         rid = 1; /* initial resource identifier */
8975 
8976         /* allocate the MSI-X vectors */
8977         for (i = 0; i < num_allocated; i++) {
8978             sc->intr[i].rid = (rid + i);
8979 
8980             if ((sc->intr[i].resource =
8981                  bus_alloc_resource_any(sc->dev,
8982                                         SYS_RES_IRQ,
8983                                         &sc->intr[i].rid,
8984                                         RF_ACTIVE)) == NULL) {
8985                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8986                       i, (rid + i));
8987 
8988                 for (j = (i - 1); j >= 0; j--) {
8989                     bus_release_resource(sc->dev,
8990                                          SYS_RES_IRQ,
8991                                          sc->intr[j].rid,
8992                                          sc->intr[j].resource);
8993                 }
8994 
8995                 sc->intr_count = 0;
8996                 sc->num_queues = 0;
8997                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8998                 pci_release_msi(sc->dev);
8999                 break;
9000             }
9001 
9002             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9003         }
9004     } while (0);
9005 
9006     do { /* try allocating MSI vector resources (at least 2) */
9007         if (sc->interrupt_mode != INTR_MODE_MSI) {
9008             break;
9009         }
9010 
9011         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9012             (msi_count < 1)) {
9013             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9014             break;
9015         }
9016 
9017         /* ask for a single MSI vector */
9018         num_requested = 1;
9019 
9020         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9021 
9022         num_allocated = num_requested;
9023         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9024             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9025             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9026             break;
9027         }
9028 
9029         if (num_allocated != 1) { /* possible? */
9030             BLOGE(sc, "MSI allocation is not 1!\n");
9031             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9032             pci_release_msi(sc->dev);
9033             break;
9034         }
9035 
9036         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9037               num_requested, num_allocated);
9038 
9039         /* best effort so use the number of vectors allocated to us */
9040         sc->intr_count = num_allocated;
9041         sc->num_queues = num_allocated;
9042 
9043         rid = 1; /* initial resource identifier */
9044 
9045         sc->intr[0].rid = rid;
9046 
9047         if ((sc->intr[0].resource =
9048              bus_alloc_resource_any(sc->dev,
9049                                     SYS_RES_IRQ,
9050                                     &sc->intr[0].rid,
9051                                     RF_ACTIVE)) == NULL) {
9052             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9053             sc->intr_count = 0;
9054             sc->num_queues = 0;
9055             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9056             pci_release_msi(sc->dev);
9057             break;
9058         }
9059 
9060         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9061     } while (0);
9062 
9063     do { /* try allocating INTx vector resources */
9064         if (sc->interrupt_mode != INTR_MODE_INTX) {
9065             break;
9066         }
9067 
9068         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9069 
9070         /* only one vector for INTx */
9071         sc->intr_count = 1;
9072         sc->num_queues = 1;
9073 
9074         rid = 0; /* initial resource identifier */
9075 
9076         sc->intr[0].rid = rid;
9077 
9078         if ((sc->intr[0].resource =
9079              bus_alloc_resource_any(sc->dev,
9080                                     SYS_RES_IRQ,
9081                                     &sc->intr[0].rid,
9082                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9083             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9084             sc->intr_count = 0;
9085             sc->num_queues = 0;
9086             sc->interrupt_mode = -1; /* Failed! */
9087             break;
9088         }
9089 
9090         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9091     } while (0);
9092 
9093     if (sc->interrupt_mode == -1) {
9094         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9095         rc = 1;
9096     } else {
9097         BLOGD(sc, DBG_LOAD,
9098               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9099               sc->interrupt_mode, sc->num_queues);
9100         rc = 0;
9101     }
9102 
9103     return (rc);
9104 }
9105 
9106 static void
9107 bxe_interrupt_detach(struct bxe_softc *sc)
9108 {
9109     struct bxe_fastpath *fp;
9110     int i;
9111 
9112     /* release interrupt resources */
9113     for (i = 0; i < sc->intr_count; i++) {
9114         if (sc->intr[i].resource && sc->intr[i].tag) {
9115             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9116             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9117         }
9118     }
9119 
9120     for (i = 0; i < sc->num_queues; i++) {
9121         fp = &sc->fp[i];
9122         if (fp->tq) {
9123             taskqueue_drain(fp->tq, &fp->tq_task);
9124             taskqueue_drain(fp->tq, &fp->tx_task);
9125             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9126                 NULL))
9127                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9128             taskqueue_free(fp->tq);
9129             fp->tq = NULL;
9130         }
9131     }
9132 
9133 
9134     if (sc->sp_tq) {
9135         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9136         taskqueue_free(sc->sp_tq);
9137         sc->sp_tq = NULL;
9138     }
9139 }
9140 
9141 /*
9142  * Enables interrupts and attach to the ISR.
9143  *
9144  * When using multiple MSI/MSI-X vectors the first vector
9145  * is used for slowpath operations while all remaining
9146  * vectors are used for fastpath operations.  If only a
9147  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9148  * ISR must look for both slowpath and fastpath completions.
9149  */
9150 static int
9151 bxe_interrupt_attach(struct bxe_softc *sc)
9152 {
9153     struct bxe_fastpath *fp;
9154     int rc = 0;
9155     int i;
9156 
9157     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9158              "bxe%d_sp_tq", sc->unit);
9159     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9160     sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9161                                  taskqueue_thread_enqueue,
9162                                  &sc->sp_tq);
9163     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9164                             "%s", sc->sp_tq_name);
9165 
9166 
9167     for (i = 0; i < sc->num_queues; i++) {
9168         fp = &sc->fp[i];
9169         snprintf(fp->tq_name, sizeof(fp->tq_name),
9170                  "bxe%d_fp%d_tq", sc->unit, i);
9171         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9172         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9173         fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9174                                   taskqueue_thread_enqueue,
9175                                   &fp->tq);
9176         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9177                           bxe_tx_mq_start_deferred, fp);
9178         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9179                                 "%s", fp->tq_name);
9180     }
9181 
9182     /* setup interrupt handlers */
9183     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9184         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9185 
9186         /*
9187          * Setup the interrupt handler. Note that we pass the driver instance
9188          * to the interrupt handler for the slowpath.
9189          */
9190         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9191                                  (INTR_TYPE_NET | INTR_MPSAFE),
9192                                  NULL, bxe_intr_sp, sc,
9193                                  &sc->intr[0].tag)) != 0) {
9194             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9195             goto bxe_interrupt_attach_exit;
9196         }
9197 
9198         bus_describe_intr(sc->dev, sc->intr[0].resource,
9199                           sc->intr[0].tag, "sp");
9200 
9201         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9202 
9203         /* initialize the fastpath vectors (note the first was used for sp) */
9204         for (i = 0; i < sc->num_queues; i++) {
9205             fp = &sc->fp[i];
9206             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9207 
9208             /*
9209              * Setup the interrupt handler. Note that we pass the
9210              * fastpath context to the interrupt handler in this
9211              * case.
9212              */
9213             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9214                                      (INTR_TYPE_NET | INTR_MPSAFE),
9215                                      NULL, bxe_intr_fp, fp,
9216                                      &sc->intr[i + 1].tag)) != 0) {
9217                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9218                       (i + 1), rc);
9219                 goto bxe_interrupt_attach_exit;
9220             }
9221 
9222             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9223                               sc->intr[i + 1].tag, "fp%02d", i);
9224 
9225             /* bind the fastpath instance to a cpu */
9226             if (sc->num_queues > 1) {
9227                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9228             }
9229 
9230             fp->state = BXE_FP_STATE_IRQ;
9231         }
9232     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9233         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9234 
9235         /*
9236          * Setup the interrupt handler. Note that we pass the
9237          * driver instance to the interrupt handler which
9238          * will handle both the slowpath and fastpath.
9239          */
9240         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9241                                  (INTR_TYPE_NET | INTR_MPSAFE),
9242                                  NULL, bxe_intr_legacy, sc,
9243                                  &sc->intr[0].tag)) != 0) {
9244             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9245             goto bxe_interrupt_attach_exit;
9246         }
9247 
9248     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9249         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9250 
9251         /*
9252          * Setup the interrupt handler. Note that we pass the
9253          * driver instance to the interrupt handler which
9254          * will handle both the slowpath and fastpath.
9255          */
9256         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9257                                  (INTR_TYPE_NET | INTR_MPSAFE),
9258                                  NULL, bxe_intr_legacy, sc,
9259                                  &sc->intr[0].tag)) != 0) {
9260             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9261             goto bxe_interrupt_attach_exit;
9262         }
9263     }
9264 
9265 bxe_interrupt_attach_exit:
9266 
9267     return (rc);
9268 }
9269 
9270 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9271 static int  bxe_init_hw_common(struct bxe_softc *sc);
9272 static int  bxe_init_hw_port(struct bxe_softc *sc);
9273 static int  bxe_init_hw_func(struct bxe_softc *sc);
9274 static void bxe_reset_common(struct bxe_softc *sc);
9275 static void bxe_reset_port(struct bxe_softc *sc);
9276 static void bxe_reset_func(struct bxe_softc *sc);
9277 static int  bxe_gunzip_init(struct bxe_softc *sc);
9278 static void bxe_gunzip_end(struct bxe_softc *sc);
9279 static int  bxe_init_firmware(struct bxe_softc *sc);
9280 static void bxe_release_firmware(struct bxe_softc *sc);
9281 
9282 static struct
9283 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9284     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9285     .init_hw_cmn      = bxe_init_hw_common,
9286     .init_hw_port     = bxe_init_hw_port,
9287     .init_hw_func     = bxe_init_hw_func,
9288 
9289     .reset_hw_cmn     = bxe_reset_common,
9290     .reset_hw_port    = bxe_reset_port,
9291     .reset_hw_func    = bxe_reset_func,
9292 
9293     .gunzip_init      = bxe_gunzip_init,
9294     .gunzip_end       = bxe_gunzip_end,
9295 
9296     .init_fw          = bxe_init_firmware,
9297     .release_fw       = bxe_release_firmware,
9298 };
9299 
9300 static void
9301 bxe_init_func_obj(struct bxe_softc *sc)
9302 {
9303     sc->dmae_ready = 0;
9304 
9305     ecore_init_func_obj(sc,
9306                         &sc->func_obj,
9307                         BXE_SP(sc, func_rdata),
9308                         BXE_SP_MAPPING(sc, func_rdata),
9309                         BXE_SP(sc, func_afex_rdata),
9310                         BXE_SP_MAPPING(sc, func_afex_rdata),
9311                         &bxe_func_sp_drv);
9312 }
9313 
9314 static int
9315 bxe_init_hw(struct bxe_softc *sc,
9316             uint32_t         load_code)
9317 {
9318     struct ecore_func_state_params func_params = { NULL };
9319     int rc;
9320 
9321     /* prepare the parameters for function state transitions */
9322     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9323 
9324     func_params.f_obj = &sc->func_obj;
9325     func_params.cmd = ECORE_F_CMD_HW_INIT;
9326 
9327     func_params.params.hw_init.load_phase = load_code;
9328 
9329     /*
9330      * Via a plethora of function pointers, we will eventually reach
9331      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9332      */
9333     rc = ecore_func_state_change(sc, &func_params);
9334 
9335     return (rc);
9336 }
9337 
9338 static void
9339 bxe_fill(struct bxe_softc *sc,
9340          uint32_t         addr,
9341          int              fill,
9342          uint32_t         len)
9343 {
9344     uint32_t i;
9345 
9346     if (!(len % 4) && !(addr % 4)) {
9347         for (i = 0; i < len; i += 4) {
9348             REG_WR(sc, (addr + i), fill);
9349         }
9350     } else {
9351         for (i = 0; i < len; i++) {
9352             REG_WR8(sc, (addr + i), fill);
9353         }
9354     }
9355 }
9356 
9357 /* writes FP SP data to FW - data_size in dwords */
9358 static void
9359 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9360                   int              fw_sb_id,
9361                   uint32_t         *sb_data_p,
9362                   uint32_t         data_size)
9363 {
9364     int index;
9365 
9366     for (index = 0; index < data_size; index++) {
9367         REG_WR(sc,
9368                (BAR_CSTRORM_INTMEM +
9369                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9370                 (sizeof(uint32_t) * index)),
9371                *(sb_data_p + index));
9372     }
9373 }
9374 
9375 static void
9376 bxe_zero_fp_sb(struct bxe_softc *sc,
9377                int              fw_sb_id)
9378 {
9379     struct hc_status_block_data_e2 sb_data_e2;
9380     struct hc_status_block_data_e1x sb_data_e1x;
9381     uint32_t *sb_data_p;
9382     uint32_t data_size = 0;
9383 
9384     if (!CHIP_IS_E1x(sc)) {
9385         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9386         sb_data_e2.common.state = SB_DISABLED;
9387         sb_data_e2.common.p_func.vf_valid = FALSE;
9388         sb_data_p = (uint32_t *)&sb_data_e2;
9389         data_size = (sizeof(struct hc_status_block_data_e2) /
9390                      sizeof(uint32_t));
9391     } else {
9392         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9393         sb_data_e1x.common.state = SB_DISABLED;
9394         sb_data_e1x.common.p_func.vf_valid = FALSE;
9395         sb_data_p = (uint32_t *)&sb_data_e1x;
9396         data_size = (sizeof(struct hc_status_block_data_e1x) /
9397                      sizeof(uint32_t));
9398     }
9399 
9400     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9401 
9402     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9403              0, CSTORM_STATUS_BLOCK_SIZE);
9404     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9405              0, CSTORM_SYNC_BLOCK_SIZE);
9406 }
9407 
9408 static void
9409 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9410                   struct hc_sp_status_block_data *sp_sb_data)
9411 {
9412     int i;
9413 
9414     for (i = 0;
9415          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9416          i++) {
9417         REG_WR(sc,
9418                (BAR_CSTRORM_INTMEM +
9419                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9420                 (i * sizeof(uint32_t))),
9421                *((uint32_t *)sp_sb_data + i));
9422     }
9423 }
9424 
9425 static void
9426 bxe_zero_sp_sb(struct bxe_softc *sc)
9427 {
9428     struct hc_sp_status_block_data sp_sb_data;
9429 
9430     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9431 
9432     sp_sb_data.state           = SB_DISABLED;
9433     sp_sb_data.p_func.vf_valid = FALSE;
9434 
9435     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9436 
9437     bxe_fill(sc,
9438              (BAR_CSTRORM_INTMEM +
9439               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9440               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9441     bxe_fill(sc,
9442              (BAR_CSTRORM_INTMEM +
9443               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9444               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9445 }
9446 
9447 static void
9448 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9449                              int                       igu_sb_id,
9450                              int                       igu_seg_id)
9451 {
9452     hc_sm->igu_sb_id      = igu_sb_id;
9453     hc_sm->igu_seg_id     = igu_seg_id;
9454     hc_sm->timer_value    = 0xFF;
9455     hc_sm->time_to_expire = 0xFFFFFFFF;
9456 }
9457 
9458 static void
9459 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9460 {
9461     /* zero out state machine indices */
9462 
9463     /* rx indices */
9464     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9465 
9466     /* tx indices */
9467     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9468     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9469     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9470     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9471 
9472     /* map indices */
9473 
9474     /* rx indices */
9475     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9476         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9477 
9478     /* tx indices */
9479     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9480         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9481     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9482         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9483     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9484         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9485     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9486         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9487 }
9488 
9489 static void
9490 bxe_init_sb(struct bxe_softc *sc,
9491             bus_addr_t       busaddr,
9492             int              vfid,
9493             uint8_t          vf_valid,
9494             int              fw_sb_id,
9495             int              igu_sb_id)
9496 {
9497     struct hc_status_block_data_e2  sb_data_e2;
9498     struct hc_status_block_data_e1x sb_data_e1x;
9499     struct hc_status_block_sm       *hc_sm_p;
9500     uint32_t *sb_data_p;
9501     int igu_seg_id;
9502     int data_size;
9503 
9504     if (CHIP_INT_MODE_IS_BC(sc)) {
9505         igu_seg_id = HC_SEG_ACCESS_NORM;
9506     } else {
9507         igu_seg_id = IGU_SEG_ACCESS_NORM;
9508     }
9509 
9510     bxe_zero_fp_sb(sc, fw_sb_id);
9511 
9512     if (!CHIP_IS_E1x(sc)) {
9513         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9514         sb_data_e2.common.state = SB_ENABLED;
9515         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9516         sb_data_e2.common.p_func.vf_id = vfid;
9517         sb_data_e2.common.p_func.vf_valid = vf_valid;
9518         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9519         sb_data_e2.common.same_igu_sb_1b = TRUE;
9520         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9521         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9522         hc_sm_p = sb_data_e2.common.state_machine;
9523         sb_data_p = (uint32_t *)&sb_data_e2;
9524         data_size = (sizeof(struct hc_status_block_data_e2) /
9525                      sizeof(uint32_t));
9526         bxe_map_sb_state_machines(sb_data_e2.index_data);
9527     } else {
9528         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9529         sb_data_e1x.common.state = SB_ENABLED;
9530         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9531         sb_data_e1x.common.p_func.vf_id = 0xff;
9532         sb_data_e1x.common.p_func.vf_valid = FALSE;
9533         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9534         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9535         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9536         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9537         hc_sm_p = sb_data_e1x.common.state_machine;
9538         sb_data_p = (uint32_t *)&sb_data_e1x;
9539         data_size = (sizeof(struct hc_status_block_data_e1x) /
9540                      sizeof(uint32_t));
9541         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9542     }
9543 
9544     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9545     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9546 
9547     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9548 
9549     /* write indices to HW - PCI guarantees endianity of regpairs */
9550     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9551 }
9552 
9553 static inline uint8_t
9554 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9555 {
9556     if (CHIP_IS_E1x(fp->sc)) {
9557         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9558     } else {
9559         return (fp->cl_id);
9560     }
9561 }
9562 
9563 static inline uint32_t
9564 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9565                            struct bxe_fastpath *fp)
9566 {
9567     uint32_t offset = BAR_USTRORM_INTMEM;
9568 
9569     if (!CHIP_IS_E1x(sc)) {
9570         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9571     } else {
9572         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9573     }
9574 
9575     return (offset);
9576 }
9577 
9578 static void
9579 bxe_init_eth_fp(struct bxe_softc *sc,
9580                 int              idx)
9581 {
9582     struct bxe_fastpath *fp = &sc->fp[idx];
9583     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9584     unsigned long q_type = 0;
9585     int cos;
9586 
9587     fp->sc    = sc;
9588     fp->index = idx;
9589 
9590     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9591     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9592 
9593     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9594                     (SC_L_ID(sc) + idx) :
9595                     /* want client ID same as IGU SB ID for non-E1 */
9596                     fp->igu_sb_id;
9597     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9598 
9599     /* setup sb indices */
9600     if (!CHIP_IS_E1x(sc)) {
9601         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9602         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9603     } else {
9604         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9605         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9606     }
9607 
9608     /* init shortcut */
9609     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9610 
9611     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9612 
9613     /*
9614      * XXX If multiple CoS is ever supported then each fastpath structure
9615      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9616      */
9617     for (cos = 0; cos < sc->max_cos; cos++) {
9618         cids[cos] = idx;
9619     }
9620     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9621 
9622     /* nothing more for a VF to do */
9623     if (IS_VF(sc)) {
9624         return;
9625     }
9626 
9627     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9628                 fp->fw_sb_id, fp->igu_sb_id);
9629 
9630     bxe_update_fp_sb_idx(fp);
9631 
9632     /* Configure Queue State object */
9633     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9634     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9635 
9636     ecore_init_queue_obj(sc,
9637                          &sc->sp_objs[idx].q_obj,
9638                          fp->cl_id,
9639                          cids,
9640                          sc->max_cos,
9641                          SC_FUNC(sc),
9642                          BXE_SP(sc, q_rdata),
9643                          BXE_SP_MAPPING(sc, q_rdata),
9644                          q_type);
9645 
9646     /* configure classification DBs */
9647     ecore_init_mac_obj(sc,
9648                        &sc->sp_objs[idx].mac_obj,
9649                        fp->cl_id,
9650                        idx,
9651                        SC_FUNC(sc),
9652                        BXE_SP(sc, mac_rdata),
9653                        BXE_SP_MAPPING(sc, mac_rdata),
9654                        ECORE_FILTER_MAC_PENDING,
9655                        &sc->sp_state,
9656                        ECORE_OBJ_TYPE_RX_TX,
9657                        &sc->macs_pool);
9658 
9659     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9660           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9661 }
9662 
9663 static inline void
9664 bxe_update_rx_prod(struct bxe_softc    *sc,
9665                    struct bxe_fastpath *fp,
9666                    uint16_t            rx_bd_prod,
9667                    uint16_t            rx_cq_prod,
9668                    uint16_t            rx_sge_prod)
9669 {
9670     struct ustorm_eth_rx_producers rx_prods = { 0 };
9671     uint32_t i;
9672 
9673     /* update producers */
9674     rx_prods.bd_prod  = rx_bd_prod;
9675     rx_prods.cqe_prod = rx_cq_prod;
9676     rx_prods.sge_prod = rx_sge_prod;
9677 
9678     /*
9679      * Make sure that the BD and SGE data is updated before updating the
9680      * producers since FW might read the BD/SGE right after the producer
9681      * is updated.
9682      * This is only applicable for weak-ordered memory model archs such
9683      * as IA-64. The following barrier is also mandatory since FW will
9684      * assumes BDs must have buffers.
9685      */
9686     wmb();
9687 
9688     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9689         REG_WR(sc,
9690                (fp->ustorm_rx_prods_offset + (i * 4)),
9691                ((uint32_t *)&rx_prods)[i]);
9692     }
9693 
9694     wmb(); /* keep prod updates ordered */
9695 
9696     BLOGD(sc, DBG_RX,
9697           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9698           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9699 }
9700 
9701 static void
9702 bxe_init_rx_rings(struct bxe_softc *sc)
9703 {
9704     struct bxe_fastpath *fp;
9705     int i;
9706 
9707     for (i = 0; i < sc->num_queues; i++) {
9708         fp = &sc->fp[i];
9709 
9710         fp->rx_bd_cons = 0;
9711 
9712         /*
9713          * Activate the BD ring...
9714          * Warning, this will generate an interrupt (to the TSTORM)
9715          * so this can only be done after the chip is initialized
9716          */
9717         bxe_update_rx_prod(sc, fp,
9718                            fp->rx_bd_prod,
9719                            fp->rx_cq_prod,
9720                            fp->rx_sge_prod);
9721 
9722         if (i != 0) {
9723             continue;
9724         }
9725 
9726         if (CHIP_IS_E1(sc)) {
9727             REG_WR(sc,
9728                    (BAR_USTRORM_INTMEM +
9729                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9730                    U64_LO(fp->rcq_dma.paddr));
9731             REG_WR(sc,
9732                    (BAR_USTRORM_INTMEM +
9733                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9734                    U64_HI(fp->rcq_dma.paddr));
9735         }
9736     }
9737 }
9738 
9739 static void
9740 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9741 {
9742     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9743     fp->tx_db.data.zero_fill1 = 0;
9744     fp->tx_db.data.prod = 0;
9745 
9746     fp->tx_pkt_prod = 0;
9747     fp->tx_pkt_cons = 0;
9748     fp->tx_bd_prod = 0;
9749     fp->tx_bd_cons = 0;
9750     fp->eth_q_stats.tx_pkts = 0;
9751 }
9752 
9753 static inline void
9754 bxe_init_tx_rings(struct bxe_softc *sc)
9755 {
9756     int i;
9757 
9758     for (i = 0; i < sc->num_queues; i++) {
9759         bxe_init_tx_ring_one(&sc->fp[i]);
9760     }
9761 }
9762 
9763 static void
9764 bxe_init_def_sb(struct bxe_softc *sc)
9765 {
9766     struct host_sp_status_block *def_sb = sc->def_sb;
9767     bus_addr_t mapping = sc->def_sb_dma.paddr;
9768     int igu_sp_sb_index;
9769     int igu_seg_id;
9770     int port = SC_PORT(sc);
9771     int func = SC_FUNC(sc);
9772     int reg_offset, reg_offset_en5;
9773     uint64_t section;
9774     int index, sindex;
9775     struct hc_sp_status_block_data sp_sb_data;
9776 
9777     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9778 
9779     if (CHIP_INT_MODE_IS_BC(sc)) {
9780         igu_sp_sb_index = DEF_SB_IGU_ID;
9781         igu_seg_id = HC_SEG_ACCESS_DEF;
9782     } else {
9783         igu_sp_sb_index = sc->igu_dsb_id;
9784         igu_seg_id = IGU_SEG_ACCESS_DEF;
9785     }
9786 
9787     /* attentions */
9788     section = ((uint64_t)mapping +
9789                offsetof(struct host_sp_status_block, atten_status_block));
9790     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9791     sc->attn_state = 0;
9792 
9793     reg_offset = (port) ?
9794                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9795                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9796     reg_offset_en5 = (port) ?
9797                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9798                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9799 
9800     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9801         /* take care of sig[0]..sig[4] */
9802         for (sindex = 0; sindex < 4; sindex++) {
9803             sc->attn_group[index].sig[sindex] =
9804                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9805         }
9806 
9807         if (!CHIP_IS_E1x(sc)) {
9808             /*
9809              * enable5 is separate from the rest of the registers,
9810              * and the address skip is 4 and not 16 between the
9811              * different groups
9812              */
9813             sc->attn_group[index].sig[4] =
9814                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9815         } else {
9816             sc->attn_group[index].sig[4] = 0;
9817         }
9818     }
9819 
9820     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9821         reg_offset = (port) ?
9822                          HC_REG_ATTN_MSG1_ADDR_L :
9823                          HC_REG_ATTN_MSG0_ADDR_L;
9824         REG_WR(sc, reg_offset, U64_LO(section));
9825         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9826     } else if (!CHIP_IS_E1x(sc)) {
9827         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9828         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9829     }
9830 
9831     section = ((uint64_t)mapping +
9832                offsetof(struct host_sp_status_block, sp_sb));
9833 
9834     bxe_zero_sp_sb(sc);
9835 
9836     /* PCI guarantees endianity of regpair */
9837     sp_sb_data.state           = SB_ENABLED;
9838     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9839     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9840     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9841     sp_sb_data.igu_seg_id      = igu_seg_id;
9842     sp_sb_data.p_func.pf_id    = func;
9843     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9844     sp_sb_data.p_func.vf_id    = 0xff;
9845 
9846     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9847 
9848     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9849 }
9850 
9851 static void
9852 bxe_init_sp_ring(struct bxe_softc *sc)
9853 {
9854     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9855     sc->spq_prod_idx = 0;
9856     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9857     sc->spq_prod_bd = sc->spq;
9858     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9859 }
9860 
9861 static void
9862 bxe_init_eq_ring(struct bxe_softc *sc)
9863 {
9864     union event_ring_elem *elem;
9865     int i;
9866 
9867     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9868         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9869 
9870         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9871                                                  BCM_PAGE_SIZE *
9872                                                  (i % NUM_EQ_PAGES)));
9873         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9874                                                  BCM_PAGE_SIZE *
9875                                                  (i % NUM_EQ_PAGES)));
9876     }
9877 
9878     sc->eq_cons    = 0;
9879     sc->eq_prod    = NUM_EQ_DESC;
9880     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9881 
9882     atomic_store_rel_long(&sc->eq_spq_left,
9883                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9884                                NUM_EQ_DESC) - 1));
9885 }
9886 
9887 static void
9888 bxe_init_internal_common(struct bxe_softc *sc)
9889 {
9890     int i;
9891 
9892     /*
9893      * Zero this manually as its initialization is currently missing
9894      * in the initTool.
9895      */
9896     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9897         REG_WR(sc,
9898                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9899                0);
9900     }
9901 
9902     if (!CHIP_IS_E1x(sc)) {
9903         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9904                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9905     }
9906 }
9907 
9908 static void
9909 bxe_init_internal(struct bxe_softc *sc,
9910                   uint32_t         load_code)
9911 {
9912     switch (load_code) {
9913     case FW_MSG_CODE_DRV_LOAD_COMMON:
9914     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9915         bxe_init_internal_common(sc);
9916         /* no break */
9917 
9918     case FW_MSG_CODE_DRV_LOAD_PORT:
9919         /* nothing to do */
9920         /* no break */
9921 
9922     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9923         /* internal memory per function is initialized inside bxe_pf_init */
9924         break;
9925 
9926     default:
9927         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9928         break;
9929     }
9930 }
9931 
9932 static void
9933 storm_memset_func_cfg(struct bxe_softc                         *sc,
9934                       struct tstorm_eth_function_common_config *tcfg,
9935                       uint16_t                                  abs_fid)
9936 {
9937     uint32_t addr;
9938     size_t size;
9939 
9940     addr = (BAR_TSTRORM_INTMEM +
9941             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9942     size = sizeof(struct tstorm_eth_function_common_config);
9943     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9944 }
9945 
9946 static void
9947 bxe_func_init(struct bxe_softc            *sc,
9948               struct bxe_func_init_params *p)
9949 {
9950     struct tstorm_eth_function_common_config tcfg = { 0 };
9951 
9952     if (CHIP_IS_E1x(sc)) {
9953         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9954     }
9955 
9956     /* Enable the function in the FW */
9957     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9958     storm_memset_func_en(sc, p->func_id, 1);
9959 
9960     /* spq */
9961     if (p->func_flgs & FUNC_FLG_SPQ) {
9962         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9963         REG_WR(sc,
9964                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9965                p->spq_prod);
9966     }
9967 }
9968 
9969 /*
9970  * Calculates the sum of vn_min_rates.
9971  * It's needed for further normalizing of the min_rates.
9972  * Returns:
9973  *   sum of vn_min_rates.
9974  *     or
9975  *   0 - if all the min_rates are 0.
9976  * In the later case fainess algorithm should be deactivated.
9977  * If all min rates are not zero then those that are zeroes will be set to 1.
9978  */
9979 static void
9980 bxe_calc_vn_min(struct bxe_softc       *sc,
9981                 struct cmng_init_input *input)
9982 {
9983     uint32_t vn_cfg;
9984     uint32_t vn_min_rate;
9985     int all_zero = 1;
9986     int vn;
9987 
9988     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9989         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9990         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9991                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9992 
9993         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9994             /* skip hidden VNs */
9995             vn_min_rate = 0;
9996         } else if (!vn_min_rate) {
9997             /* If min rate is zero - set it to 100 */
9998             vn_min_rate = DEF_MIN_RATE;
9999         } else {
10000             all_zero = 0;
10001         }
10002 
10003         input->vnic_min_rate[vn] = vn_min_rate;
10004     }
10005 
10006     /* if ETS or all min rates are zeros - disable fairness */
10007     if (BXE_IS_ETS_ENABLED(sc)) {
10008         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10009         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10010     } else if (all_zero) {
10011         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10012         BLOGD(sc, DBG_LOAD,
10013               "Fariness disabled (all MIN values are zeroes)\n");
10014     } else {
10015         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10016     }
10017 }
10018 
10019 static inline uint16_t
10020 bxe_extract_max_cfg(struct bxe_softc *sc,
10021                     uint32_t         mf_cfg)
10022 {
10023     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10024                         FUNC_MF_CFG_MAX_BW_SHIFT);
10025 
10026     if (!max_cfg) {
10027         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10028         max_cfg = 100;
10029     }
10030 
10031     return (max_cfg);
10032 }
10033 
10034 static void
10035 bxe_calc_vn_max(struct bxe_softc       *sc,
10036                 int                    vn,
10037                 struct cmng_init_input *input)
10038 {
10039     uint16_t vn_max_rate;
10040     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10041     uint32_t max_cfg;
10042 
10043     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10044         vn_max_rate = 0;
10045     } else {
10046         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10047 
10048         if (IS_MF_SI(sc)) {
10049             /* max_cfg in percents of linkspeed */
10050             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10051         } else { /* SD modes */
10052             /* max_cfg is absolute in 100Mb units */
10053             vn_max_rate = (max_cfg * 100);
10054         }
10055     }
10056 
10057     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10058 
10059     input->vnic_max_rate[vn] = vn_max_rate;
10060 }
10061 
10062 static void
10063 bxe_cmng_fns_init(struct bxe_softc *sc,
10064                   uint8_t          read_cfg,
10065                   uint8_t          cmng_type)
10066 {
10067     struct cmng_init_input input;
10068     int vn;
10069 
10070     memset(&input, 0, sizeof(struct cmng_init_input));
10071 
10072     input.port_rate = sc->link_vars.line_speed;
10073 
10074     if (cmng_type == CMNG_FNS_MINMAX) {
10075         /* read mf conf from shmem */
10076         if (read_cfg) {
10077             bxe_read_mf_cfg(sc);
10078         }
10079 
10080         /* get VN min rate and enable fairness if not 0 */
10081         bxe_calc_vn_min(sc, &input);
10082 
10083         /* get VN max rate */
10084         if (sc->port.pmf) {
10085             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10086                 bxe_calc_vn_max(sc, vn, &input);
10087             }
10088         }
10089 
10090         /* always enable rate shaping and fairness */
10091         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10092 
10093         ecore_init_cmng(&input, &sc->cmng);
10094         return;
10095     }
10096 
10097     /* rate shaping and fairness are disabled */
10098     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10099 }
10100 
10101 static int
10102 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10103 {
10104     if (CHIP_REV_IS_SLOW(sc)) {
10105         return (CMNG_FNS_NONE);
10106     }
10107 
10108     if (IS_MF(sc)) {
10109         return (CMNG_FNS_MINMAX);
10110     }
10111 
10112     return (CMNG_FNS_NONE);
10113 }
10114 
10115 static void
10116 storm_memset_cmng(struct bxe_softc *sc,
10117                   struct cmng_init *cmng,
10118                   uint8_t          port)
10119 {
10120     int vn;
10121     int func;
10122     uint32_t addr;
10123     size_t size;
10124 
10125     addr = (BAR_XSTRORM_INTMEM +
10126             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10127     size = sizeof(struct cmng_struct_per_port);
10128     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10129 
10130     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10131         func = func_by_vn(sc, vn);
10132 
10133         addr = (BAR_XSTRORM_INTMEM +
10134                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10135         size = sizeof(struct rate_shaping_vars_per_vn);
10136         ecore_storm_memset_struct(sc, addr, size,
10137                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10138 
10139         addr = (BAR_XSTRORM_INTMEM +
10140                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10141         size = sizeof(struct fairness_vars_per_vn);
10142         ecore_storm_memset_struct(sc, addr, size,
10143                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10144     }
10145 }
10146 
10147 static void
10148 bxe_pf_init(struct bxe_softc *sc)
10149 {
10150     struct bxe_func_init_params func_init = { 0 };
10151     struct event_ring_data eq_data = { { 0 } };
10152     uint16_t flags;
10153 
10154     if (!CHIP_IS_E1x(sc)) {
10155         /* reset IGU PF statistics: MSIX + ATTN */
10156         /* PF */
10157         REG_WR(sc,
10158                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10159                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10160                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10161                0);
10162         /* ATTN */
10163         REG_WR(sc,
10164                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10165                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10166                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10167                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10168                0);
10169     }
10170 
10171     /* function setup flags */
10172     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10173 
10174     /*
10175      * This flag is relevant for E1x only.
10176      * E2 doesn't have a TPA configuration in a function level.
10177      */
10178     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10179 
10180     func_init.func_flgs = flags;
10181     func_init.pf_id     = SC_FUNC(sc);
10182     func_init.func_id   = SC_FUNC(sc);
10183     func_init.spq_map   = sc->spq_dma.paddr;
10184     func_init.spq_prod  = sc->spq_prod_idx;
10185 
10186     bxe_func_init(sc, &func_init);
10187 
10188     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10189 
10190     /*
10191      * Congestion management values depend on the link rate.
10192      * There is no active link so initial link rate is set to 10Gbps.
10193      * When the link comes up the congestion management values are
10194      * re-calculated according to the actual link rate.
10195      */
10196     sc->link_vars.line_speed = SPEED_10000;
10197     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10198 
10199     /* Only the PMF sets the HW */
10200     if (sc->port.pmf) {
10201         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10202     }
10203 
10204     /* init Event Queue - PCI bus guarantees correct endainity */
10205     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10206     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10207     eq_data.producer     = sc->eq_prod;
10208     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10209     eq_data.sb_id        = DEF_SB_ID;
10210     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10211 }
10212 
10213 static void
10214 bxe_hc_int_enable(struct bxe_softc *sc)
10215 {
10216     int port = SC_PORT(sc);
10217     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10218     uint32_t val = REG_RD(sc, addr);
10219     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10220     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10221                            (sc->intr_count == 1)) ? TRUE : FALSE;
10222     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10223 
10224     if (msix) {
10225         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10226                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10227         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10228                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10229         if (single_msix) {
10230             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10231         }
10232     } else if (msi) {
10233         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10234         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10235                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10236                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10237     } else {
10238         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10239                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10240                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10241                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10242 
10243         if (!CHIP_IS_E1(sc)) {
10244             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10245                   val, port, addr);
10246 
10247             REG_WR(sc, addr, val);
10248 
10249             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10250         }
10251     }
10252 
10253     if (CHIP_IS_E1(sc)) {
10254         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10255     }
10256 
10257     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10258           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10259 
10260     REG_WR(sc, addr, val);
10261 
10262     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10263     mb();
10264 
10265     if (!CHIP_IS_E1(sc)) {
10266         /* init leading/trailing edge */
10267         if (IS_MF(sc)) {
10268             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10269             if (sc->port.pmf) {
10270                 /* enable nig and gpio3 attention */
10271                 val |= 0x1100;
10272             }
10273         } else {
10274             val = 0xffff;
10275         }
10276 
10277         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10278         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10279     }
10280 
10281     /* make sure that interrupts are indeed enabled from here on */
10282     mb();
10283 }
10284 
10285 static void
10286 bxe_igu_int_enable(struct bxe_softc *sc)
10287 {
10288     uint32_t val;
10289     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10290     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10291                            (sc->intr_count == 1)) ? TRUE : FALSE;
10292     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10293 
10294     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10295 
10296     if (msix) {
10297         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10298                  IGU_PF_CONF_SINGLE_ISR_EN);
10299         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10300                 IGU_PF_CONF_ATTN_BIT_EN);
10301         if (single_msix) {
10302             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10303         }
10304     } else if (msi) {
10305         val &= ~IGU_PF_CONF_INT_LINE_EN;
10306         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10307                 IGU_PF_CONF_ATTN_BIT_EN |
10308                 IGU_PF_CONF_SINGLE_ISR_EN);
10309     } else {
10310         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10311         val |= (IGU_PF_CONF_INT_LINE_EN |
10312                 IGU_PF_CONF_ATTN_BIT_EN |
10313                 IGU_PF_CONF_SINGLE_ISR_EN);
10314     }
10315 
10316     /* clean previous status - need to configure igu prior to ack*/
10317     if ((!msix) || single_msix) {
10318         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10319         bxe_ack_int(sc);
10320     }
10321 
10322     val |= IGU_PF_CONF_FUNC_EN;
10323 
10324     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10325           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10326 
10327     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10328 
10329     mb();
10330 
10331     /* init leading/trailing edge */
10332     if (IS_MF(sc)) {
10333         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10334         if (sc->port.pmf) {
10335             /* enable nig and gpio3 attention */
10336             val |= 0x1100;
10337         }
10338     } else {
10339         val = 0xffff;
10340     }
10341 
10342     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10343     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10344 
10345     /* make sure that interrupts are indeed enabled from here on */
10346     mb();
10347 }
10348 
10349 static void
10350 bxe_int_enable(struct bxe_softc *sc)
10351 {
10352     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10353         bxe_hc_int_enable(sc);
10354     } else {
10355         bxe_igu_int_enable(sc);
10356     }
10357 }
10358 
10359 static void
10360 bxe_hc_int_disable(struct bxe_softc *sc)
10361 {
10362     int port = SC_PORT(sc);
10363     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10364     uint32_t val = REG_RD(sc, addr);
10365 
10366     /*
10367      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10368      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10369      * block
10370      */
10371     if (CHIP_IS_E1(sc)) {
10372         /*
10373          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10374          * to prevent from HC sending interrupts after we exit the function
10375          */
10376         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10377 
10378         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10379                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10380                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10381     } else {
10382         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10383                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10384                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10385                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10386     }
10387 
10388     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10389 
10390     /* flush all outstanding writes */
10391     mb();
10392 
10393     REG_WR(sc, addr, val);
10394     if (REG_RD(sc, addr) != val) {
10395         BLOGE(sc, "proper val not read from HC IGU!\n");
10396     }
10397 }
10398 
10399 static void
10400 bxe_igu_int_disable(struct bxe_softc *sc)
10401 {
10402     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10403 
10404     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10405              IGU_PF_CONF_INT_LINE_EN |
10406              IGU_PF_CONF_ATTN_BIT_EN);
10407 
10408     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10409 
10410     /* flush all outstanding writes */
10411     mb();
10412 
10413     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10414     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10415         BLOGE(sc, "proper val not read from IGU!\n");
10416     }
10417 }
10418 
10419 static void
10420 bxe_int_disable(struct bxe_softc *sc)
10421 {
10422     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10423         bxe_hc_int_disable(sc);
10424     } else {
10425         bxe_igu_int_disable(sc);
10426     }
10427 }
10428 
10429 static void
10430 bxe_nic_init(struct bxe_softc *sc,
10431              int              load_code)
10432 {
10433     int i;
10434 
10435     for (i = 0; i < sc->num_queues; i++) {
10436         bxe_init_eth_fp(sc, i);
10437     }
10438 
10439     rmb(); /* ensure status block indices were read */
10440 
10441     bxe_init_rx_rings(sc);
10442     bxe_init_tx_rings(sc);
10443 
10444     if (IS_VF(sc)) {
10445         return;
10446     }
10447 
10448     /* initialize MOD_ABS interrupts */
10449     elink_init_mod_abs_int(sc, &sc->link_vars,
10450                            sc->devinfo.chip_id,
10451                            sc->devinfo.shmem_base,
10452                            sc->devinfo.shmem2_base,
10453                            SC_PORT(sc));
10454 
10455     bxe_init_def_sb(sc);
10456     bxe_update_dsb_idx(sc);
10457     bxe_init_sp_ring(sc);
10458     bxe_init_eq_ring(sc);
10459     bxe_init_internal(sc, load_code);
10460     bxe_pf_init(sc);
10461     bxe_stats_init(sc);
10462 
10463     /* flush all before enabling interrupts */
10464     mb();
10465 
10466     bxe_int_enable(sc);
10467 
10468     /* check for SPIO5 */
10469     bxe_attn_int_deasserted0(sc,
10470                              REG_RD(sc,
10471                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10472                                      SC_PORT(sc)*4)) &
10473                              AEU_INPUTS_ATTN_BITS_SPIO5);
10474 }
10475 
10476 static inline void
10477 bxe_init_objs(struct bxe_softc *sc)
10478 {
10479     /* mcast rules must be added to tx if tx switching is enabled */
10480     ecore_obj_type o_type =
10481         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10482                                          ECORE_OBJ_TYPE_RX;
10483 
10484     /* RX_MODE controlling object */
10485     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10486 
10487     /* multicast configuration controlling object */
10488     ecore_init_mcast_obj(sc,
10489                          &sc->mcast_obj,
10490                          sc->fp[0].cl_id,
10491                          sc->fp[0].index,
10492                          SC_FUNC(sc),
10493                          SC_FUNC(sc),
10494                          BXE_SP(sc, mcast_rdata),
10495                          BXE_SP_MAPPING(sc, mcast_rdata),
10496                          ECORE_FILTER_MCAST_PENDING,
10497                          &sc->sp_state,
10498                          o_type);
10499 
10500     /* Setup CAM credit pools */
10501     ecore_init_mac_credit_pool(sc,
10502                                &sc->macs_pool,
10503                                SC_FUNC(sc),
10504                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10505                                                  VNICS_PER_PATH(sc));
10506 
10507     ecore_init_vlan_credit_pool(sc,
10508                                 &sc->vlans_pool,
10509                                 SC_ABS_FUNC(sc) >> 1,
10510                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10511                                                   VNICS_PER_PATH(sc));
10512 
10513     /* RSS configuration object */
10514     ecore_init_rss_config_obj(sc,
10515                               &sc->rss_conf_obj,
10516                               sc->fp[0].cl_id,
10517                               sc->fp[0].index,
10518                               SC_FUNC(sc),
10519                               SC_FUNC(sc),
10520                               BXE_SP(sc, rss_rdata),
10521                               BXE_SP_MAPPING(sc, rss_rdata),
10522                               ECORE_FILTER_RSS_CONF_PENDING,
10523                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10524 }
10525 
10526 /*
10527  * Initialize the function. This must be called before sending CLIENT_SETUP
10528  * for the first client.
10529  */
10530 static inline int
10531 bxe_func_start(struct bxe_softc *sc)
10532 {
10533     struct ecore_func_state_params func_params = { NULL };
10534     struct ecore_func_start_params *start_params = &func_params.params.start;
10535 
10536     /* Prepare parameters for function state transitions */
10537     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10538 
10539     func_params.f_obj = &sc->func_obj;
10540     func_params.cmd = ECORE_F_CMD_START;
10541 
10542     /* Function parameters */
10543     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10544     start_params->sd_vlan_tag = OVLAN(sc);
10545 
10546     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10547         start_params->network_cos_mode = STATIC_COS;
10548     } else { /* CHIP_IS_E1X */
10549         start_params->network_cos_mode = FW_WRR;
10550     }
10551 
10552     //start_params->gre_tunnel_mode = 0;
10553     //start_params->gre_tunnel_rss  = 0;
10554 
10555     return (ecore_func_state_change(sc, &func_params));
10556 }
10557 
10558 static int
10559 bxe_set_power_state(struct bxe_softc *sc,
10560                     uint8_t          state)
10561 {
10562     uint16_t pmcsr;
10563 
10564     /* If there is no power capability, silently succeed */
10565     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10566         BLOGW(sc, "No power capability\n");
10567         return (0);
10568     }
10569 
10570     pmcsr = pci_read_config(sc->dev,
10571                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10572                             2);
10573 
10574     switch (state) {
10575     case PCI_PM_D0:
10576         pci_write_config(sc->dev,
10577                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10578                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10579 
10580         if (pmcsr & PCIM_PSTAT_DMASK) {
10581             /* delay required during transition out of D3hot */
10582             DELAY(20000);
10583         }
10584 
10585         break;
10586 
10587     case PCI_PM_D3hot:
10588         /* XXX if there are other clients above don't shut down the power */
10589 
10590         /* don't shut down the power for emulation and FPGA */
10591         if (CHIP_REV_IS_SLOW(sc)) {
10592             return (0);
10593         }
10594 
10595         pmcsr &= ~PCIM_PSTAT_DMASK;
10596         pmcsr |= PCIM_PSTAT_D3;
10597 
10598         if (sc->wol) {
10599             pmcsr |= PCIM_PSTAT_PMEENABLE;
10600         }
10601 
10602         pci_write_config(sc->dev,
10603                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10604                          pmcsr, 4);
10605 
10606         /*
10607          * No more memory access after this point until device is brought back
10608          * to D0 state.
10609          */
10610         break;
10611 
10612     default:
10613         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10614             state, pmcsr);
10615         return (-1);
10616     }
10617 
10618     return (0);
10619 }
10620 
10621 
10622 /* return true if succeeded to acquire the lock */
10623 static uint8_t
10624 bxe_trylock_hw_lock(struct bxe_softc *sc,
10625                     uint32_t         resource)
10626 {
10627     uint32_t lock_status;
10628     uint32_t resource_bit = (1 << resource);
10629     int func = SC_FUNC(sc);
10630     uint32_t hw_lock_control_reg;
10631 
10632     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10633 
10634     /* Validating that the resource is within range */
10635     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10636         BLOGD(sc, DBG_LOAD,
10637               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10638               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10639         return (FALSE);
10640     }
10641 
10642     if (func <= 5) {
10643         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10644     } else {
10645         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10646     }
10647 
10648     /* try to acquire the lock */
10649     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10650     lock_status = REG_RD(sc, hw_lock_control_reg);
10651     if (lock_status & resource_bit) {
10652         return (TRUE);
10653     }
10654 
10655     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10656         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10657         lock_status, resource_bit);
10658 
10659     return (FALSE);
10660 }
10661 
10662 /*
10663  * Get the recovery leader resource id according to the engine this function
10664  * belongs to. Currently only only 2 engines is supported.
10665  */
10666 static int
10667 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10668 {
10669     if (SC_PATH(sc)) {
10670         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10671     } else {
10672         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10673     }
10674 }
10675 
10676 /* try to acquire a leader lock for current engine */
10677 static uint8_t
10678 bxe_trylock_leader_lock(struct bxe_softc *sc)
10679 {
10680     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10681 }
10682 
10683 static int
10684 bxe_release_leader_lock(struct bxe_softc *sc)
10685 {
10686     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10687 }
10688 
10689 /* close gates #2, #3 and #4 */
10690 static void
10691 bxe_set_234_gates(struct bxe_softc *sc,
10692                   uint8_t          close)
10693 {
10694     uint32_t val;
10695 
10696     /* gates #2 and #4a are closed/opened for "not E1" only */
10697     if (!CHIP_IS_E1(sc)) {
10698         /* #4 */
10699         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10700         /* #2 */
10701         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10702     }
10703 
10704     /* #3 */
10705     if (CHIP_IS_E1x(sc)) {
10706         /* prevent interrupts from HC on both ports */
10707         val = REG_RD(sc, HC_REG_CONFIG_1);
10708         REG_WR(sc, HC_REG_CONFIG_1,
10709                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10710                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10711 
10712         val = REG_RD(sc, HC_REG_CONFIG_0);
10713         REG_WR(sc, HC_REG_CONFIG_0,
10714                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10715                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10716     } else {
10717         /* Prevent incoming interrupts in IGU */
10718         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10719 
10720         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10721                (!close) ?
10722                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10723                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10724     }
10725 
10726     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10727           close ? "closing" : "opening");
10728 
10729     wmb();
10730 }
10731 
10732 /* poll for pending writes bit, it should get cleared in no more than 1s */
10733 static int
10734 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10735 {
10736     uint32_t cnt = 1000;
10737     uint32_t pend_bits = 0;
10738 
10739     do {
10740         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10741 
10742         if (pend_bits == 0) {
10743             break;
10744         }
10745 
10746         DELAY(1000);
10747     } while (--cnt > 0);
10748 
10749     if (cnt == 0) {
10750         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10751         return (-1);
10752     }
10753 
10754     return (0);
10755 }
10756 
10757 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10758 
10759 static void
10760 bxe_clp_reset_prep(struct bxe_softc *sc,
10761                    uint32_t         *magic_val)
10762 {
10763     /* Do some magic... */
10764     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10765     *magic_val = val & SHARED_MF_CLP_MAGIC;
10766     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10767 }
10768 
10769 /* restore the value of the 'magic' bit */
10770 static void
10771 bxe_clp_reset_done(struct bxe_softc *sc,
10772                    uint32_t         magic_val)
10773 {
10774     /* Restore the 'magic' bit value... */
10775     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10776     MFCFG_WR(sc, shared_mf_config.clp_mb,
10777               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10778 }
10779 
10780 /* prepare for MCP reset, takes care of CLP configurations */
10781 static void
10782 bxe_reset_mcp_prep(struct bxe_softc *sc,
10783                    uint32_t         *magic_val)
10784 {
10785     uint32_t shmem;
10786     uint32_t validity_offset;
10787 
10788     /* set `magic' bit in order to save MF config */
10789     if (!CHIP_IS_E1(sc)) {
10790         bxe_clp_reset_prep(sc, magic_val);
10791     }
10792 
10793     /* get shmem offset */
10794     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10795     validity_offset =
10796         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10797 
10798     /* Clear validity map flags */
10799     if (shmem > 0) {
10800         REG_WR(sc, shmem + validity_offset, 0);
10801     }
10802 }
10803 
10804 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10805 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10806 
10807 static void
10808 bxe_mcp_wait_one(struct bxe_softc *sc)
10809 {
10810     /* special handling for emulation and FPGA (10 times longer) */
10811     if (CHIP_REV_IS_SLOW(sc)) {
10812         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10813     } else {
10814         DELAY((MCP_ONE_TIMEOUT) * 1000);
10815     }
10816 }
10817 
10818 /* initialize shmem_base and waits for validity signature to appear */
10819 static int
10820 bxe_init_shmem(struct bxe_softc *sc)
10821 {
10822     int cnt = 0;
10823     uint32_t val = 0;
10824 
10825     do {
10826         sc->devinfo.shmem_base     =
10827         sc->link_params.shmem_base =
10828             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10829 
10830         if (sc->devinfo.shmem_base) {
10831             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10832             if (val & SHR_MEM_VALIDITY_MB)
10833                 return (0);
10834         }
10835 
10836         bxe_mcp_wait_one(sc);
10837 
10838     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10839 
10840     BLOGE(sc, "BAD MCP validity signature\n");
10841 
10842     return (-1);
10843 }
10844 
10845 static int
10846 bxe_reset_mcp_comp(struct bxe_softc *sc,
10847                    uint32_t         magic_val)
10848 {
10849     int rc = bxe_init_shmem(sc);
10850 
10851     /* Restore the `magic' bit value */
10852     if (!CHIP_IS_E1(sc)) {
10853         bxe_clp_reset_done(sc, magic_val);
10854     }
10855 
10856     return (rc);
10857 }
10858 
10859 static void
10860 bxe_pxp_prep(struct bxe_softc *sc)
10861 {
10862     if (!CHIP_IS_E1(sc)) {
10863         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10864         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10865         wmb();
10866     }
10867 }
10868 
10869 /*
10870  * Reset the whole chip except for:
10871  *      - PCIE core
10872  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10873  *      - IGU
10874  *      - MISC (including AEU)
10875  *      - GRC
10876  *      - RBCN, RBCP
10877  */
10878 static void
10879 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10880                             uint8_t          global)
10881 {
10882     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10883     uint32_t global_bits2, stay_reset2;
10884 
10885     /*
10886      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10887      * (per chip) blocks.
10888      */
10889     global_bits2 =
10890         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10891         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10892 
10893     /*
10894      * Don't reset the following blocks.
10895      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10896      *            reset, as in 4 port device they might still be owned
10897      *            by the MCP (there is only one leader per path).
10898      */
10899     not_reset_mask1 =
10900         MISC_REGISTERS_RESET_REG_1_RST_HC |
10901         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10902         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10903 
10904     not_reset_mask2 =
10905         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10906         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10907         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10908         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10909         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10910         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10911         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10912         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10913         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10914         MISC_REGISTERS_RESET_REG_2_PGLC |
10915         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10916         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10917         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10918         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10919         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10920         MISC_REGISTERS_RESET_REG_2_UMAC1;
10921 
10922     /*
10923      * Keep the following blocks in reset:
10924      *  - all xxMACs are handled by the elink code.
10925      */
10926     stay_reset2 =
10927         MISC_REGISTERS_RESET_REG_2_XMAC |
10928         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10929 
10930     /* Full reset masks according to the chip */
10931     reset_mask1 = 0xffffffff;
10932 
10933     if (CHIP_IS_E1(sc))
10934         reset_mask2 = 0xffff;
10935     else if (CHIP_IS_E1H(sc))
10936         reset_mask2 = 0x1ffff;
10937     else if (CHIP_IS_E2(sc))
10938         reset_mask2 = 0xfffff;
10939     else /* CHIP_IS_E3 */
10940         reset_mask2 = 0x3ffffff;
10941 
10942     /* Don't reset global blocks unless we need to */
10943     if (!global)
10944         reset_mask2 &= ~global_bits2;
10945 
10946     /*
10947      * In case of attention in the QM, we need to reset PXP
10948      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10949      * because otherwise QM reset would release 'close the gates' shortly
10950      * before resetting the PXP, then the PSWRQ would send a write
10951      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10952      * read the payload data from PSWWR, but PSWWR would not
10953      * respond. The write queue in PGLUE would stuck, dmae commands
10954      * would not return. Therefore it's important to reset the second
10955      * reset register (containing the
10956      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10957      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10958      * bit).
10959      */
10960     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10961            reset_mask2 & (~not_reset_mask2));
10962 
10963     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10964            reset_mask1 & (~not_reset_mask1));
10965 
10966     mb();
10967     wmb();
10968 
10969     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10970            reset_mask2 & (~stay_reset2));
10971 
10972     mb();
10973     wmb();
10974 
10975     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10976     wmb();
10977 }
10978 
10979 static int
10980 bxe_process_kill(struct bxe_softc *sc,
10981                  uint8_t          global)
10982 {
10983     int cnt = 1000;
10984     uint32_t val = 0;
10985     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10986     uint32_t tags_63_32 = 0;
10987 
10988     /* Empty the Tetris buffer, wait for 1s */
10989     do {
10990         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10991         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10992         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10993         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10994         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10995         if (CHIP_IS_E3(sc)) {
10996             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10997         }
10998 
10999         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11000             ((port_is_idle_0 & 0x1) == 0x1) &&
11001             ((port_is_idle_1 & 0x1) == 0x1) &&
11002             (pgl_exp_rom2 == 0xffffffff) &&
11003             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11004             break;
11005         DELAY(1000);
11006     } while (cnt-- > 0);
11007 
11008     if (cnt <= 0) {
11009         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11010                   "are still outstanding read requests after 1s! "
11011                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11012                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11013               sr_cnt, blk_cnt, port_is_idle_0,
11014               port_is_idle_1, pgl_exp_rom2);
11015         return (-1);
11016     }
11017 
11018     mb();
11019 
11020     /* Close gates #2, #3 and #4 */
11021     bxe_set_234_gates(sc, TRUE);
11022 
11023     /* Poll for IGU VQs for 57712 and newer chips */
11024     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11025         return (-1);
11026     }
11027 
11028     /* XXX indicate that "process kill" is in progress to MCP */
11029 
11030     /* clear "unprepared" bit */
11031     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11032     mb();
11033 
11034     /* Make sure all is written to the chip before the reset */
11035     wmb();
11036 
11037     /*
11038      * Wait for 1ms to empty GLUE and PCI-E core queues,
11039      * PSWHST, GRC and PSWRD Tetris buffer.
11040      */
11041     DELAY(1000);
11042 
11043     /* Prepare to chip reset: */
11044     /* MCP */
11045     if (global) {
11046         bxe_reset_mcp_prep(sc, &val);
11047     }
11048 
11049     /* PXP */
11050     bxe_pxp_prep(sc);
11051     mb();
11052 
11053     /* reset the chip */
11054     bxe_process_kill_chip_reset(sc, global);
11055     mb();
11056 
11057     /* clear errors in PGB */
11058     if (!CHIP_IS_E1(sc))
11059         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11060 
11061     /* Recover after reset: */
11062     /* MCP */
11063     if (global && bxe_reset_mcp_comp(sc, val)) {
11064         return (-1);
11065     }
11066 
11067     /* XXX add resetting the NO_MCP mode DB here */
11068 
11069     /* Open the gates #2, #3 and #4 */
11070     bxe_set_234_gates(sc, FALSE);
11071 
11072     /* XXX
11073      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11074      * re-enable attentions
11075      */
11076 
11077     return (0);
11078 }
11079 
11080 static int
11081 bxe_leader_reset(struct bxe_softc *sc)
11082 {
11083     int rc = 0;
11084     uint8_t global = bxe_reset_is_global(sc);
11085     uint32_t load_code;
11086 
11087     /*
11088      * If not going to reset MCP, load "fake" driver to reset HW while
11089      * driver is owner of the HW.
11090      */
11091     if (!global && !BXE_NOMCP(sc)) {
11092         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11093                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11094         if (!load_code) {
11095             BLOGE(sc, "MCP response failure, aborting\n");
11096             rc = -1;
11097             goto exit_leader_reset;
11098         }
11099 
11100         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11101             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11102             BLOGE(sc, "MCP unexpected response, aborting\n");
11103             rc = -1;
11104             goto exit_leader_reset2;
11105         }
11106 
11107         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11108         if (!load_code) {
11109             BLOGE(sc, "MCP response failure, aborting\n");
11110             rc = -1;
11111             goto exit_leader_reset2;
11112         }
11113     }
11114 
11115     /* try to recover after the failure */
11116     if (bxe_process_kill(sc, global)) {
11117         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11118         rc = -1;
11119         goto exit_leader_reset2;
11120     }
11121 
11122     /*
11123      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11124      * state.
11125      */
11126     bxe_set_reset_done(sc);
11127     if (global) {
11128         bxe_clear_reset_global(sc);
11129     }
11130 
11131 exit_leader_reset2:
11132 
11133     /* unload "fake driver" if it was loaded */
11134     if (!global && !BXE_NOMCP(sc)) {
11135         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11136         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11137     }
11138 
11139 exit_leader_reset:
11140 
11141     sc->is_leader = 0;
11142     bxe_release_leader_lock(sc);
11143 
11144     mb();
11145     return (rc);
11146 }
11147 
11148 /*
11149  * prepare INIT transition, parameters configured:
11150  *   - HC configuration
11151  *   - Queue's CDU context
11152  */
11153 static void
11154 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11155                    struct bxe_fastpath            *fp,
11156                    struct ecore_queue_init_params *init_params)
11157 {
11158     uint8_t cos;
11159     int cxt_index, cxt_offset;
11160 
11161     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11162     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11163 
11164     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11165     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11166 
11167     /* HC rate */
11168     init_params->rx.hc_rate =
11169         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11170     init_params->tx.hc_rate =
11171         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11172 
11173     /* FW SB ID */
11174     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11175 
11176     /* CQ index among the SB indices */
11177     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11178     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11179 
11180     /* set maximum number of COSs supported by this queue */
11181     init_params->max_cos = sc->max_cos;
11182 
11183     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11184           fp->index, init_params->max_cos);
11185 
11186     /* set the context pointers queue object */
11187     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11188         /* XXX change index/cid here if ever support multiple tx CoS */
11189         /* fp->txdata[cos]->cid */
11190         cxt_index = fp->index / ILT_PAGE_CIDS;
11191         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11192         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11193     }
11194 }
11195 
11196 /* set flags that are common for the Tx-only and not normal connections */
11197 static unsigned long
11198 bxe_get_common_flags(struct bxe_softc    *sc,
11199                      struct bxe_fastpath *fp,
11200                      uint8_t             zero_stats)
11201 {
11202     unsigned long flags = 0;
11203 
11204     /* PF driver will always initialize the Queue to an ACTIVE state */
11205     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11206 
11207     /*
11208      * tx only connections collect statistics (on the same index as the
11209      * parent connection). The statistics are zeroed when the parent
11210      * connection is initialized.
11211      */
11212 
11213     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11214     if (zero_stats) {
11215         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11216     }
11217 
11218     /*
11219      * tx only connections can support tx-switching, though their
11220      * CoS-ness doesn't survive the loopback
11221      */
11222     if (sc->flags & BXE_TX_SWITCHING) {
11223         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11224     }
11225 
11226     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11227 
11228     return (flags);
11229 }
11230 
11231 static unsigned long
11232 bxe_get_q_flags(struct bxe_softc    *sc,
11233                 struct bxe_fastpath *fp,
11234                 uint8_t             leading)
11235 {
11236     unsigned long flags = 0;
11237 
11238     if (IS_MF_SD(sc)) {
11239         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11240     }
11241 
11242     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11243         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11244 #if __FreeBSD_version >= 800000
11245         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11246 #endif
11247     }
11248 
11249     if (leading) {
11250         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11251         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11252     }
11253 
11254     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11255 
11256     /* merge with common flags */
11257     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11258 }
11259 
11260 static void
11261 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11262                       struct bxe_fastpath               *fp,
11263                       struct ecore_general_setup_params *gen_init,
11264                       uint8_t                           cos)
11265 {
11266     gen_init->stat_id = bxe_stats_id(fp);
11267     gen_init->spcl_id = fp->cl_id;
11268     gen_init->mtu = sc->mtu;
11269     gen_init->cos = cos;
11270 }
11271 
11272 static void
11273 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11274                  struct bxe_fastpath           *fp,
11275                  struct rxq_pause_params       *pause,
11276                  struct ecore_rxq_setup_params *rxq_init)
11277 {
11278     uint8_t max_sge = 0;
11279     uint16_t sge_sz = 0;
11280     uint16_t tpa_agg_size = 0;
11281 
11282     pause->sge_th_lo = SGE_TH_LO(sc);
11283     pause->sge_th_hi = SGE_TH_HI(sc);
11284 
11285     /* validate SGE ring has enough to cross high threshold */
11286     if (sc->dropless_fc &&
11287             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11288             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11289         BLOGW(sc, "sge ring threshold limit\n");
11290     }
11291 
11292     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11293     tpa_agg_size = (2 * sc->mtu);
11294     if (tpa_agg_size < sc->max_aggregation_size) {
11295         tpa_agg_size = sc->max_aggregation_size;
11296     }
11297 
11298     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11299     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11300                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11301     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11302 
11303     /* pause - not for e1 */
11304     if (!CHIP_IS_E1(sc)) {
11305         pause->bd_th_lo = BD_TH_LO(sc);
11306         pause->bd_th_hi = BD_TH_HI(sc);
11307 
11308         pause->rcq_th_lo = RCQ_TH_LO(sc);
11309         pause->rcq_th_hi = RCQ_TH_HI(sc);
11310 
11311         /* validate rings have enough entries to cross high thresholds */
11312         if (sc->dropless_fc &&
11313             pause->bd_th_hi + FW_PREFETCH_CNT >
11314             sc->rx_ring_size) {
11315             BLOGW(sc, "rx bd ring threshold limit\n");
11316         }
11317 
11318         if (sc->dropless_fc &&
11319             pause->rcq_th_hi + FW_PREFETCH_CNT >
11320             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11321             BLOGW(sc, "rcq ring threshold limit\n");
11322         }
11323 
11324         pause->pri_map = 1;
11325     }
11326 
11327     /* rxq setup */
11328     rxq_init->dscr_map   = fp->rx_dma.paddr;
11329     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11330     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11331     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11332 
11333     /*
11334      * This should be a maximum number of data bytes that may be
11335      * placed on the BD (not including paddings).
11336      */
11337     rxq_init->buf_sz = (fp->rx_buf_size -
11338                         IP_HEADER_ALIGNMENT_PADDING);
11339 
11340     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11341     rxq_init->tpa_agg_sz      = tpa_agg_size;
11342     rxq_init->sge_buf_sz      = sge_sz;
11343     rxq_init->max_sges_pkt    = max_sge;
11344     rxq_init->rss_engine_id   = SC_FUNC(sc);
11345     rxq_init->mcast_engine_id = SC_FUNC(sc);
11346 
11347     /*
11348      * Maximum number or simultaneous TPA aggregation for this Queue.
11349      * For PF Clients it should be the maximum available number.
11350      * VF driver(s) may want to define it to a smaller value.
11351      */
11352     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11353 
11354     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11355     rxq_init->fw_sb_id = fp->fw_sb_id;
11356 
11357     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11358 
11359     /*
11360      * configure silent vlan removal
11361      * if multi function mode is afex, then mask default vlan
11362      */
11363     if (IS_MF_AFEX(sc)) {
11364         rxq_init->silent_removal_value =
11365             sc->devinfo.mf_info.afex_def_vlan_tag;
11366         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11367     }
11368 }
11369 
11370 static void
11371 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11372                  struct bxe_fastpath           *fp,
11373                  struct ecore_txq_setup_params *txq_init,
11374                  uint8_t                       cos)
11375 {
11376     /*
11377      * XXX If multiple CoS is ever supported then each fastpath structure
11378      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11379      * fp->txdata[cos]->tx_dma.paddr;
11380      */
11381     txq_init->dscr_map     = fp->tx_dma.paddr;
11382     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11383     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11384     txq_init->fw_sb_id     = fp->fw_sb_id;
11385 
11386     /*
11387      * set the TSS leading client id for TX classfication to the
11388      * leading RSS client id
11389      */
11390     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11391 }
11392 
11393 /*
11394  * This function performs 2 steps in a queue state machine:
11395  *   1) RESET->INIT
11396  *   2) INIT->SETUP
11397  */
11398 static int
11399 bxe_setup_queue(struct bxe_softc    *sc,
11400                 struct bxe_fastpath *fp,
11401                 uint8_t             leading)
11402 {
11403     struct ecore_queue_state_params q_params = { NULL };
11404     struct ecore_queue_setup_params *setup_params =
11405                         &q_params.params.setup;
11406     int rc;
11407 
11408     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11409 
11410     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11411 
11412     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11413 
11414     /* we want to wait for completion in this context */
11415     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11416 
11417     /* prepare the INIT parameters */
11418     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11419 
11420     /* Set the command */
11421     q_params.cmd = ECORE_Q_CMD_INIT;
11422 
11423     /* Change the state to INIT */
11424     rc = ecore_queue_state_change(sc, &q_params);
11425     if (rc) {
11426         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11427         return (rc);
11428     }
11429 
11430     BLOGD(sc, DBG_LOAD, "init complete\n");
11431 
11432     /* now move the Queue to the SETUP state */
11433     memset(setup_params, 0, sizeof(*setup_params));
11434 
11435     /* set Queue flags */
11436     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11437 
11438     /* set general SETUP parameters */
11439     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11440                           FIRST_TX_COS_INDEX);
11441 
11442     bxe_pf_rx_q_prep(sc, fp,
11443                      &setup_params->pause_params,
11444                      &setup_params->rxq_params);
11445 
11446     bxe_pf_tx_q_prep(sc, fp,
11447                      &setup_params->txq_params,
11448                      FIRST_TX_COS_INDEX);
11449 
11450     /* Set the command */
11451     q_params.cmd = ECORE_Q_CMD_SETUP;
11452 
11453     /* change the state to SETUP */
11454     rc = ecore_queue_state_change(sc, &q_params);
11455     if (rc) {
11456         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11457         return (rc);
11458     }
11459 
11460     return (rc);
11461 }
11462 
11463 static int
11464 bxe_setup_leading(struct bxe_softc *sc)
11465 {
11466     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11467 }
11468 
11469 static int
11470 bxe_config_rss_pf(struct bxe_softc            *sc,
11471                   struct ecore_rss_config_obj *rss_obj,
11472                   uint8_t                     config_hash)
11473 {
11474     struct ecore_config_rss_params params = { NULL };
11475     int i;
11476 
11477     /*
11478      * Although RSS is meaningless when there is a single HW queue we
11479      * still need it enabled in order to have HW Rx hash generated.
11480      */
11481 
11482     params.rss_obj = rss_obj;
11483 
11484     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11485 
11486     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11487 
11488     /* RSS configuration */
11489     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11490     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11491     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11492     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11493     if (rss_obj->udp_rss_v4) {
11494         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11495     }
11496     if (rss_obj->udp_rss_v6) {
11497         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11498     }
11499 
11500     /* Hash bits */
11501     params.rss_result_mask = MULTI_MASK;
11502 
11503     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11504 
11505     if (config_hash) {
11506         /* RSS keys */
11507         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11508             params.rss_key[i] = arc4random();
11509         }
11510 
11511         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11512     }
11513 
11514     return (ecore_config_rss(sc, &params));
11515 }
11516 
11517 static int
11518 bxe_config_rss_eth(struct bxe_softc *sc,
11519                    uint8_t          config_hash)
11520 {
11521     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11522 }
11523 
11524 static int
11525 bxe_init_rss_pf(struct bxe_softc *sc)
11526 {
11527     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11528     int i;
11529 
11530     /*
11531      * Prepare the initial contents of the indirection table if
11532      * RSS is enabled
11533      */
11534     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11535         sc->rss_conf_obj.ind_table[i] =
11536             (sc->fp->cl_id + (i % num_eth_queues));
11537     }
11538 
11539     if (sc->udp_rss) {
11540         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11541     }
11542 
11543     /*
11544      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11545      * per-port, so if explicit configuration is needed, do it only
11546      * for a PMF.
11547      *
11548      * For 57712 and newer it's a per-function configuration.
11549      */
11550     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11551 }
11552 
11553 static int
11554 bxe_set_mac_one(struct bxe_softc          *sc,
11555                 uint8_t                   *mac,
11556                 struct ecore_vlan_mac_obj *obj,
11557                 uint8_t                   set,
11558                 int                       mac_type,
11559                 unsigned long             *ramrod_flags)
11560 {
11561     struct ecore_vlan_mac_ramrod_params ramrod_param;
11562     int rc;
11563 
11564     memset(&ramrod_param, 0, sizeof(ramrod_param));
11565 
11566     /* fill in general parameters */
11567     ramrod_param.vlan_mac_obj = obj;
11568     ramrod_param.ramrod_flags = *ramrod_flags;
11569 
11570     /* fill a user request section if needed */
11571     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11572         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11573 
11574         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11575 
11576         /* Set the command: ADD or DEL */
11577         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11578                                             ECORE_VLAN_MAC_DEL;
11579     }
11580 
11581     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11582 
11583     if (rc == ECORE_EXISTS) {
11584         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11585         /* do not treat adding same MAC as error */
11586         rc = 0;
11587     } else if (rc < 0) {
11588         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11589     }
11590 
11591     return (rc);
11592 }
11593 
11594 static int
11595 bxe_set_eth_mac(struct bxe_softc *sc,
11596                 uint8_t          set)
11597 {
11598     unsigned long ramrod_flags = 0;
11599 
11600     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11601 
11602     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11603 
11604     /* Eth MAC is set on RSS leading client (fp[0]) */
11605     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11606                             &sc->sp_objs->mac_obj,
11607                             set, ECORE_ETH_MAC, &ramrod_flags));
11608 }
11609 
11610 static int
11611 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11612 {
11613     uint32_t sel_phy_idx = 0;
11614 
11615     if (sc->link_params.num_phys <= 1) {
11616         return (ELINK_INT_PHY);
11617     }
11618 
11619     if (sc->link_vars.link_up) {
11620         sel_phy_idx = ELINK_EXT_PHY1;
11621         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11622         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11623             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11624              ELINK_SUPPORTED_FIBRE))
11625             sel_phy_idx = ELINK_EXT_PHY2;
11626     } else {
11627         switch (elink_phy_selection(&sc->link_params)) {
11628         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11629         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11630         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11631                sel_phy_idx = ELINK_EXT_PHY1;
11632                break;
11633         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11634         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11635                sel_phy_idx = ELINK_EXT_PHY2;
11636                break;
11637         }
11638     }
11639 
11640     return (sel_phy_idx);
11641 }
11642 
11643 static int
11644 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11645 {
11646     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11647 
11648     /*
11649      * The selected activated PHY is always after swapping (in case PHY
11650      * swapping is enabled). So when swapping is enabled, we need to reverse
11651      * the configuration
11652      */
11653 
11654     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11655         if (sel_phy_idx == ELINK_EXT_PHY1)
11656             sel_phy_idx = ELINK_EXT_PHY2;
11657         else if (sel_phy_idx == ELINK_EXT_PHY2)
11658             sel_phy_idx = ELINK_EXT_PHY1;
11659     }
11660 
11661     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11662 }
11663 
11664 static void
11665 bxe_set_requested_fc(struct bxe_softc *sc)
11666 {
11667     /*
11668      * Initialize link parameters structure variables
11669      * It is recommended to turn off RX FC for jumbo frames
11670      * for better performance
11671      */
11672     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11673         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11674     } else {
11675         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11676     }
11677 }
11678 
11679 static void
11680 bxe_calc_fc_adv(struct bxe_softc *sc)
11681 {
11682     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11683 
11684 
11685     sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11686                                            ADVERTISED_Pause);
11687 
11688     switch (sc->link_vars.ieee_fc &
11689             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11690 
11691     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11692         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11693                                           ADVERTISED_Pause);
11694         break;
11695 
11696     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11697         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11698         break;
11699 
11700     default:
11701         break;
11702 
11703     }
11704 }
11705 
11706 static uint16_t
11707 bxe_get_mf_speed(struct bxe_softc *sc)
11708 {
11709     uint16_t line_speed = sc->link_vars.line_speed;
11710     if (IS_MF(sc)) {
11711         uint16_t maxCfg =
11712             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11713 
11714         /* calculate the current MAX line speed limit for the MF devices */
11715         if (IS_MF_SI(sc)) {
11716             line_speed = (line_speed * maxCfg) / 100;
11717         } else { /* SD mode */
11718             uint16_t vn_max_rate = maxCfg * 100;
11719 
11720             if (vn_max_rate < line_speed) {
11721                 line_speed = vn_max_rate;
11722             }
11723         }
11724     }
11725 
11726     return (line_speed);
11727 }
11728 
11729 static void
11730 bxe_fill_report_data(struct bxe_softc            *sc,
11731                      struct bxe_link_report_data *data)
11732 {
11733     uint16_t line_speed = bxe_get_mf_speed(sc);
11734 
11735     memset(data, 0, sizeof(*data));
11736 
11737     /* fill the report data with the effective line speed */
11738     data->line_speed = line_speed;
11739 
11740     /* Link is down */
11741     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11742         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11743     }
11744 
11745     /* Full DUPLEX */
11746     if (sc->link_vars.duplex == DUPLEX_FULL) {
11747         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11748     }
11749 
11750     /* Rx Flow Control is ON */
11751     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11752         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11753     }
11754 
11755     /* Tx Flow Control is ON */
11756     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11757         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11758     }
11759 }
11760 
11761 /* report link status to OS, should be called under phy_lock */
11762 static void
11763 bxe_link_report_locked(struct bxe_softc *sc)
11764 {
11765     struct bxe_link_report_data cur_data;
11766 
11767     /* reread mf_cfg */
11768     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11769         bxe_read_mf_cfg(sc);
11770     }
11771 
11772     /* Read the current link report info */
11773     bxe_fill_report_data(sc, &cur_data);
11774 
11775     /* Don't report link down or exactly the same link status twice */
11776     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11777         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11778                       &sc->last_reported_link.link_report_flags) &&
11779          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11780                       &cur_data.link_report_flags))) {
11781         return;
11782     }
11783 
11784 	ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11785 					cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11786     sc->link_cnt++;
11787 
11788 	ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11789     /* report new link params and remember the state for the next time */
11790     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11791 
11792     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11793                      &cur_data.link_report_flags)) {
11794         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11795     } else {
11796         const char *duplex;
11797         const char *flow;
11798 
11799         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11800                                    &cur_data.link_report_flags)) {
11801             duplex = "full";
11802 			ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11803         } else {
11804             duplex = "half";
11805 			ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11806         }
11807 
11808         /*
11809          * Handle the FC at the end so that only these flags would be
11810          * possibly set. This way we may easily check if there is no FC
11811          * enabled.
11812          */
11813         if (cur_data.link_report_flags) {
11814             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11815                              &cur_data.link_report_flags) &&
11816                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11817                              &cur_data.link_report_flags)) {
11818                 flow = "ON - receive & transmit";
11819             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11820                                     &cur_data.link_report_flags) &&
11821                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11822                                      &cur_data.link_report_flags)) {
11823                 flow = "ON - receive";
11824             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11825                                      &cur_data.link_report_flags) &&
11826                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11827                                     &cur_data.link_report_flags)) {
11828                 flow = "ON - transmit";
11829             } else {
11830                 flow = "none"; /* possible? */
11831             }
11832         } else {
11833             flow = "none";
11834         }
11835 
11836         if_link_state_change(sc->ifp, LINK_STATE_UP);
11837         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11838               cur_data.line_speed, duplex, flow);
11839     }
11840 }
11841 
11842 static void
11843 bxe_link_report(struct bxe_softc *sc)
11844 {
11845     bxe_acquire_phy_lock(sc);
11846     bxe_link_report_locked(sc);
11847     bxe_release_phy_lock(sc);
11848 }
11849 
11850 static void
11851 bxe_link_status_update(struct bxe_softc *sc)
11852 {
11853     if (sc->state != BXE_STATE_OPEN) {
11854         return;
11855     }
11856 
11857     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11858         elink_link_status_update(&sc->link_params, &sc->link_vars);
11859     } else {
11860         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11861                                   ELINK_SUPPORTED_10baseT_Full |
11862                                   ELINK_SUPPORTED_100baseT_Half |
11863                                   ELINK_SUPPORTED_100baseT_Full |
11864                                   ELINK_SUPPORTED_1000baseT_Full |
11865                                   ELINK_SUPPORTED_2500baseX_Full |
11866                                   ELINK_SUPPORTED_10000baseT_Full |
11867                                   ELINK_SUPPORTED_TP |
11868                                   ELINK_SUPPORTED_FIBRE |
11869                                   ELINK_SUPPORTED_Autoneg |
11870                                   ELINK_SUPPORTED_Pause |
11871                                   ELINK_SUPPORTED_Asym_Pause);
11872         sc->port.advertising[0] = sc->port.supported[0];
11873 
11874         sc->link_params.sc                = sc;
11875         sc->link_params.port              = SC_PORT(sc);
11876         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11877         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11878         sc->link_params.req_line_speed[0] = SPEED_10000;
11879         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11880         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11881 
11882         if (CHIP_REV_IS_FPGA(sc)) {
11883             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11884             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11885             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11886                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11887         } else {
11888             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11889             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11890             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11891                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11892         }
11893 
11894         sc->link_vars.link_up = 1;
11895 
11896         sc->link_vars.duplex    = DUPLEX_FULL;
11897         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11898 
11899         if (IS_PF(sc)) {
11900             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11901             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11902             bxe_link_report(sc);
11903         }
11904     }
11905 
11906     if (IS_PF(sc)) {
11907         if (sc->link_vars.link_up) {
11908             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11909         } else {
11910             bxe_stats_handle(sc, STATS_EVENT_STOP);
11911         }
11912         bxe_link_report(sc);
11913     } else {
11914         bxe_link_report(sc);
11915         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11916     }
11917 }
11918 
11919 static int
11920 bxe_initial_phy_init(struct bxe_softc *sc,
11921                      int              load_mode)
11922 {
11923     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11924     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11925     struct elink_params *lp = &sc->link_params;
11926 
11927     bxe_set_requested_fc(sc);
11928 
11929     if (CHIP_REV_IS_SLOW(sc)) {
11930         uint32_t bond = CHIP_BOND_ID(sc);
11931         uint32_t feat = 0;
11932 
11933         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11934             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11935         } else if (bond & 0x4) {
11936             if (CHIP_IS_E3(sc)) {
11937                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11938             } else {
11939                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11940             }
11941         } else if (bond & 0x8) {
11942             if (CHIP_IS_E3(sc)) {
11943                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11944             } else {
11945                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11946             }
11947         }
11948 
11949         /* disable EMAC for E3 and above */
11950         if (bond & 0x2) {
11951             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11952         }
11953 
11954         sc->link_params.feature_config_flags |= feat;
11955     }
11956 
11957     bxe_acquire_phy_lock(sc);
11958 
11959     if (load_mode == LOAD_DIAG) {
11960         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11961         /* Prefer doing PHY loopback at 10G speed, if possible */
11962         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11963             if (lp->speed_cap_mask[cfg_idx] &
11964                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11965                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11966             } else {
11967                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11968             }
11969         }
11970     }
11971 
11972     if (load_mode == LOAD_LOOPBACK_EXT) {
11973         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11974     }
11975 
11976     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11977 
11978     bxe_release_phy_lock(sc);
11979 
11980     bxe_calc_fc_adv(sc);
11981 
11982     if (sc->link_vars.link_up) {
11983         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11984         bxe_link_report(sc);
11985     }
11986 
11987     if (!CHIP_REV_IS_SLOW(sc)) {
11988         bxe_periodic_start(sc);
11989     }
11990 
11991     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11992     return (rc);
11993 }
11994 
11995 /* must be called under IF_ADDR_LOCK */
11996 
11997 static int
11998 bxe_set_mc_list(struct bxe_softc *sc)
11999 {
12000     struct ecore_mcast_ramrod_params rparam = { NULL };
12001     int rc = 0;
12002     int mc_count = 0;
12003     int mcnt, i;
12004     struct ecore_mcast_list_elem *mc_mac, *mc_mac_start;
12005     unsigned char *mta;
12006     if_t ifp = sc->ifp;
12007 
12008     mc_count = if_multiaddr_count(ifp, -1);/* XXX they don't have a limit */
12009     if (!mc_count)
12010         return (0);
12011 
12012     mta = malloc(sizeof(unsigned char) * ETHER_ADDR_LEN *
12013             mc_count, M_DEVBUF, M_NOWAIT);
12014 
12015     if(mta == NULL) {
12016         BLOGE(sc, "Failed to allocate temp mcast list\n");
12017         return (-1);
12018     }
12019     bzero(mta, (sizeof(unsigned char) * ETHER_ADDR_LEN * mc_count));
12020 
12021     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF, (M_NOWAIT | M_ZERO));
12022     mc_mac_start = mc_mac;
12023 
12024     if (!mc_mac) {
12025         free(mta, M_DEVBUF);
12026         BLOGE(sc, "Failed to allocate temp mcast list\n");
12027         return (-1);
12028     }
12029     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12030 
12031     /* mta and mcnt not expected to be  different */
12032     if_multiaddr_array(ifp, mta, &mcnt, mc_count);
12033 
12034 
12035     rparam.mcast_obj = &sc->mcast_obj;
12036     ECORE_LIST_INIT(&rparam.mcast_list);
12037 
12038     for(i=0; i< mcnt; i++) {
12039 
12040         mc_mac->mac = (uint8_t *)(mta + (i * ETHER_ADDR_LEN));
12041         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &rparam.mcast_list);
12042 
12043         BLOGD(sc, DBG_LOAD,
12044               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12045               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12046               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12047 
12048         mc_mac++;
12049     }
12050     rparam.mcast_list_len = mc_count;
12051 
12052     BXE_MCAST_LOCK(sc);
12053 
12054     /* first, clear all configured multicast MACs */
12055     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12056     if (rc < 0) {
12057         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12058         BXE_MCAST_UNLOCK(sc);
12059     	free(mc_mac_start, M_DEVBUF);
12060         free(mta, M_DEVBUF);
12061         return (rc);
12062     }
12063 
12064     /* Now add the new MACs */
12065     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12066     if (rc < 0) {
12067         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12068     }
12069 
12070     BXE_MCAST_UNLOCK(sc);
12071 
12072     free(mc_mac_start, M_DEVBUF);
12073     free(mta, M_DEVBUF);
12074 
12075     return (rc);
12076 }
12077 
12078 static int
12079 bxe_set_uc_list(struct bxe_softc *sc)
12080 {
12081     if_t ifp = sc->ifp;
12082     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12083     struct ifaddr *ifa;
12084     unsigned long ramrod_flags = 0;
12085     int rc;
12086 
12087 #if __FreeBSD_version < 800000
12088     IF_ADDR_LOCK(ifp);
12089 #else
12090     if_addr_rlock(ifp);
12091 #endif
12092 
12093     /* first schedule a cleanup up of old configuration */
12094     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12095     if (rc < 0) {
12096         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12097 #if __FreeBSD_version < 800000
12098         IF_ADDR_UNLOCK(ifp);
12099 #else
12100         if_addr_runlock(ifp);
12101 #endif
12102         return (rc);
12103     }
12104 
12105     ifa = if_getifaddr(ifp); /* XXX Is this structure */
12106     while (ifa) {
12107         if (ifa->ifa_addr->sa_family != AF_LINK) {
12108             ifa = TAILQ_NEXT(ifa, ifa_link);
12109             continue;
12110         }
12111 
12112         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12113                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12114         if (rc == -EEXIST) {
12115             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12116             /* do not treat adding same MAC as an error */
12117             rc = 0;
12118         } else if (rc < 0) {
12119             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12120 #if __FreeBSD_version < 800000
12121             IF_ADDR_UNLOCK(ifp);
12122 #else
12123             if_addr_runlock(ifp);
12124 #endif
12125             return (rc);
12126         }
12127 
12128         ifa = TAILQ_NEXT(ifa, ifa_link);
12129     }
12130 
12131 #if __FreeBSD_version < 800000
12132     IF_ADDR_UNLOCK(ifp);
12133 #else
12134     if_addr_runlock(ifp);
12135 #endif
12136 
12137     /* Execute the pending commands */
12138     bit_set(&ramrod_flags, RAMROD_CONT);
12139     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12140                             ECORE_UC_LIST_MAC, &ramrod_flags));
12141 }
12142 
12143 static void
12144 bxe_set_rx_mode(struct bxe_softc *sc)
12145 {
12146     if_t ifp = sc->ifp;
12147     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12148 
12149     if (sc->state != BXE_STATE_OPEN) {
12150         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12151         return;
12152     }
12153 
12154     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12155 
12156     if (if_getflags(ifp) & IFF_PROMISC) {
12157         rx_mode = BXE_RX_MODE_PROMISC;
12158     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12159                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12160                 CHIP_IS_E1(sc))) {
12161         rx_mode = BXE_RX_MODE_ALLMULTI;
12162     } else {
12163         if (IS_PF(sc)) {
12164             /* some multicasts */
12165             if (bxe_set_mc_list(sc) < 0) {
12166                 rx_mode = BXE_RX_MODE_ALLMULTI;
12167             }
12168             if (bxe_set_uc_list(sc) < 0) {
12169                 rx_mode = BXE_RX_MODE_PROMISC;
12170             }
12171         }
12172     }
12173 
12174     sc->rx_mode = rx_mode;
12175 
12176     /* schedule the rx_mode command */
12177     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12178         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12179         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12180         return;
12181     }
12182 
12183     if (IS_PF(sc)) {
12184         bxe_set_storm_rx_mode(sc);
12185     }
12186 }
12187 
12188 
12189 /* update flags in shmem */
12190 static void
12191 bxe_update_drv_flags(struct bxe_softc *sc,
12192                      uint32_t         flags,
12193                      uint32_t         set)
12194 {
12195     uint32_t drv_flags;
12196 
12197     if (SHMEM2_HAS(sc, drv_flags)) {
12198         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12199         drv_flags = SHMEM2_RD(sc, drv_flags);
12200 
12201         if (set) {
12202             SET_FLAGS(drv_flags, flags);
12203         } else {
12204             RESET_FLAGS(drv_flags, flags);
12205         }
12206 
12207         SHMEM2_WR(sc, drv_flags, drv_flags);
12208         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12209 
12210         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12211     }
12212 }
12213 
12214 /* periodic timer callout routine, only runs when the interface is up */
12215 
12216 static void
12217 bxe_periodic_callout_func(void *xsc)
12218 {
12219     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12220     int i;
12221 
12222     if (!BXE_CORE_TRYLOCK(sc)) {
12223         /* just bail and try again next time */
12224 
12225         if ((sc->state == BXE_STATE_OPEN) &&
12226             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12227             /* schedule the next periodic callout */
12228             callout_reset(&sc->periodic_callout, hz,
12229                           bxe_periodic_callout_func, sc);
12230         }
12231 
12232         return;
12233     }
12234 
12235     if ((sc->state != BXE_STATE_OPEN) ||
12236         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12237         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12238         BXE_CORE_UNLOCK(sc);
12239         return;
12240         }
12241 
12242 
12243     /* Check for TX timeouts on any fastpath. */
12244     FOR_EACH_QUEUE(sc, i) {
12245         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12246             /* Ruh-Roh, chip was reset! */
12247             break;
12248         }
12249     }
12250 
12251     if (!CHIP_REV_IS_SLOW(sc)) {
12252         /*
12253          * This barrier is needed to ensure the ordering between the writing
12254          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12255          * the reading here.
12256          */
12257         mb();
12258         if (sc->port.pmf) {
12259 	    bxe_acquire_phy_lock(sc);
12260             elink_period_func(&sc->link_params, &sc->link_vars);
12261 	    bxe_release_phy_lock(sc);
12262         }
12263     }
12264 
12265     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12266         int mb_idx = SC_FW_MB_IDX(sc);
12267         uint32_t drv_pulse;
12268         uint32_t mcp_pulse;
12269 
12270         ++sc->fw_drv_pulse_wr_seq;
12271         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12272 
12273         drv_pulse = sc->fw_drv_pulse_wr_seq;
12274         bxe_drv_pulse(sc);
12275 
12276         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12277                      MCP_PULSE_SEQ_MASK);
12278 
12279         /*
12280          * The delta between driver pulse and mcp response should
12281          * be 1 (before mcp response) or 0 (after mcp response).
12282          */
12283         if ((drv_pulse != mcp_pulse) &&
12284             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12285             /* someone lost a heartbeat... */
12286             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12287                   drv_pulse, mcp_pulse);
12288         }
12289     }
12290 
12291     /* state is BXE_STATE_OPEN */
12292     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12293 
12294     BXE_CORE_UNLOCK(sc);
12295 
12296     if ((sc->state == BXE_STATE_OPEN) &&
12297         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12298         /* schedule the next periodic callout */
12299         callout_reset(&sc->periodic_callout, hz,
12300                       bxe_periodic_callout_func, sc);
12301     }
12302 }
12303 
12304 static void
12305 bxe_periodic_start(struct bxe_softc *sc)
12306 {
12307     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12308     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12309 }
12310 
12311 static void
12312 bxe_periodic_stop(struct bxe_softc *sc)
12313 {
12314     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12315     callout_drain(&sc->periodic_callout);
12316 }
12317 
12318 /* start the controller */
12319 static __noinline int
12320 bxe_nic_load(struct bxe_softc *sc,
12321              int              load_mode)
12322 {
12323     uint32_t val;
12324     int load_code = 0;
12325     int i, rc = 0;
12326 
12327     BXE_CORE_LOCK_ASSERT(sc);
12328 
12329     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12330 
12331     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12332 
12333     if (IS_PF(sc)) {
12334         /* must be called before memory allocation and HW init */
12335         bxe_ilt_set_info(sc);
12336     }
12337 
12338     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12339 
12340     bxe_set_fp_rx_buf_size(sc);
12341 
12342     if (bxe_alloc_fp_buffers(sc) != 0) {
12343         BLOGE(sc, "Failed to allocate fastpath memory\n");
12344         sc->state = BXE_STATE_CLOSED;
12345         rc = ENOMEM;
12346         goto bxe_nic_load_error0;
12347     }
12348 
12349     if (bxe_alloc_mem(sc) != 0) {
12350         sc->state = BXE_STATE_CLOSED;
12351         rc = ENOMEM;
12352         goto bxe_nic_load_error0;
12353     }
12354 
12355     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12356         sc->state = BXE_STATE_CLOSED;
12357         rc = ENOMEM;
12358         goto bxe_nic_load_error0;
12359     }
12360 
12361     if (IS_PF(sc)) {
12362         /* set pf load just before approaching the MCP */
12363         bxe_set_pf_load(sc);
12364 
12365         /* if MCP exists send load request and analyze response */
12366         if (!BXE_NOMCP(sc)) {
12367             /* attempt to load pf */
12368             if (bxe_nic_load_request(sc, &load_code) != 0) {
12369                 sc->state = BXE_STATE_CLOSED;
12370                 rc = ENXIO;
12371                 goto bxe_nic_load_error1;
12372             }
12373 
12374             /* what did the MCP say? */
12375             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12376                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12377                 sc->state = BXE_STATE_CLOSED;
12378                 rc = ENXIO;
12379                 goto bxe_nic_load_error2;
12380             }
12381         } else {
12382             BLOGI(sc, "Device has no MCP!\n");
12383             load_code = bxe_nic_load_no_mcp(sc);
12384         }
12385 
12386         /* mark PMF if applicable */
12387         bxe_nic_load_pmf(sc, load_code);
12388 
12389         /* Init Function state controlling object */
12390         bxe_init_func_obj(sc);
12391 
12392         /* Initialize HW */
12393         if (bxe_init_hw(sc, load_code) != 0) {
12394             BLOGE(sc, "HW init failed\n");
12395             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12396             sc->state = BXE_STATE_CLOSED;
12397             rc = ENXIO;
12398             goto bxe_nic_load_error2;
12399         }
12400     }
12401 
12402     /* set ALWAYS_ALIVE bit in shmem */
12403     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12404     bxe_drv_pulse(sc);
12405     sc->flags |= BXE_NO_PULSE;
12406 
12407     /* attach interrupts */
12408     if (bxe_interrupt_attach(sc) != 0) {
12409         sc->state = BXE_STATE_CLOSED;
12410         rc = ENXIO;
12411         goto bxe_nic_load_error2;
12412     }
12413 
12414     bxe_nic_init(sc, load_code);
12415 
12416     /* Init per-function objects */
12417     if (IS_PF(sc)) {
12418         bxe_init_objs(sc);
12419         // XXX bxe_iov_nic_init(sc);
12420 
12421         /* set AFEX default VLAN tag to an invalid value */
12422         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12423         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12424 
12425         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12426         rc = bxe_func_start(sc);
12427         if (rc) {
12428             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12429             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12430             sc->state = BXE_STATE_ERROR;
12431             goto bxe_nic_load_error3;
12432         }
12433 
12434         /* send LOAD_DONE command to MCP */
12435         if (!BXE_NOMCP(sc)) {
12436             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12437             if (!load_code) {
12438                 BLOGE(sc, "MCP response failure, aborting\n");
12439                 sc->state = BXE_STATE_ERROR;
12440                 rc = ENXIO;
12441                 goto bxe_nic_load_error3;
12442             }
12443         }
12444 
12445         rc = bxe_setup_leading(sc);
12446         if (rc) {
12447             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12448             sc->state = BXE_STATE_ERROR;
12449             goto bxe_nic_load_error3;
12450         }
12451 
12452         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12453             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12454             if (rc) {
12455                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12456                 sc->state = BXE_STATE_ERROR;
12457                 goto bxe_nic_load_error3;
12458             }
12459         }
12460 
12461         rc = bxe_init_rss_pf(sc);
12462         if (rc) {
12463             BLOGE(sc, "PF RSS init failed\n");
12464             sc->state = BXE_STATE_ERROR;
12465             goto bxe_nic_load_error3;
12466         }
12467     }
12468     /* XXX VF */
12469 
12470     /* now when Clients are configured we are ready to work */
12471     sc->state = BXE_STATE_OPEN;
12472 
12473     /* Configure a ucast MAC */
12474     if (IS_PF(sc)) {
12475         rc = bxe_set_eth_mac(sc, TRUE);
12476     }
12477     if (rc) {
12478         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12479         sc->state = BXE_STATE_ERROR;
12480         goto bxe_nic_load_error3;
12481     }
12482 
12483     if (sc->port.pmf) {
12484         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12485         if (rc) {
12486             sc->state = BXE_STATE_ERROR;
12487             goto bxe_nic_load_error3;
12488         }
12489     }
12490 
12491     sc->link_params.feature_config_flags &=
12492         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12493 
12494     /* start fast path */
12495 
12496     /* Initialize Rx filter */
12497     bxe_set_rx_mode(sc);
12498 
12499     /* start the Tx */
12500     switch (/* XXX load_mode */LOAD_OPEN) {
12501     case LOAD_NORMAL:
12502     case LOAD_OPEN:
12503         break;
12504 
12505     case LOAD_DIAG:
12506     case LOAD_LOOPBACK_EXT:
12507         sc->state = BXE_STATE_DIAG;
12508         break;
12509 
12510     default:
12511         break;
12512     }
12513 
12514     if (sc->port.pmf) {
12515         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12516     } else {
12517         bxe_link_status_update(sc);
12518     }
12519 
12520     /* start the periodic timer callout */
12521     bxe_periodic_start(sc);
12522 
12523     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12524         /* mark driver is loaded in shmem2 */
12525         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12526         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12527                   (val |
12528                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12529                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12530     }
12531 
12532     /* wait for all pending SP commands to complete */
12533     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12534         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12535         bxe_periodic_stop(sc);
12536         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12537         return (ENXIO);
12538     }
12539 
12540     /* Tell the stack the driver is running! */
12541     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12542 
12543     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12544 
12545     return (0);
12546 
12547 bxe_nic_load_error3:
12548 
12549     if (IS_PF(sc)) {
12550         bxe_int_disable_sync(sc, 1);
12551 
12552         /* clean out queued objects */
12553         bxe_squeeze_objects(sc);
12554     }
12555 
12556     bxe_interrupt_detach(sc);
12557 
12558 bxe_nic_load_error2:
12559 
12560     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12561         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12562         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12563     }
12564 
12565     sc->port.pmf = 0;
12566 
12567 bxe_nic_load_error1:
12568 
12569     /* clear pf_load status, as it was already set */
12570     if (IS_PF(sc)) {
12571         bxe_clear_pf_load(sc);
12572     }
12573 
12574 bxe_nic_load_error0:
12575 
12576     bxe_free_fw_stats_mem(sc);
12577     bxe_free_fp_buffers(sc);
12578     bxe_free_mem(sc);
12579 
12580     return (rc);
12581 }
12582 
12583 static int
12584 bxe_init_locked(struct bxe_softc *sc)
12585 {
12586     int other_engine = SC_PATH(sc) ? 0 : 1;
12587     uint8_t other_load_status, load_status;
12588     uint8_t global = FALSE;
12589     int rc;
12590 
12591     BXE_CORE_LOCK_ASSERT(sc);
12592 
12593     /* check if the driver is already running */
12594     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12595         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12596         return (0);
12597     }
12598 
12599     bxe_set_power_state(sc, PCI_PM_D0);
12600 
12601     /*
12602      * If parity occurred during the unload, then attentions and/or
12603      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12604      * loaded on the current engine to complete the recovery. Parity recovery
12605      * is only relevant for PF driver.
12606      */
12607     if (IS_PF(sc)) {
12608         other_load_status = bxe_get_load_status(sc, other_engine);
12609         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12610 
12611         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12612             bxe_chk_parity_attn(sc, &global, TRUE)) {
12613             do {
12614                 /*
12615                  * If there are attentions and they are in global blocks, set
12616                  * the GLOBAL_RESET bit regardless whether it will be this
12617                  * function that will complete the recovery or not.
12618                  */
12619                 if (global) {
12620                     bxe_set_reset_global(sc);
12621                 }
12622 
12623                 /*
12624                  * Only the first function on the current engine should try
12625                  * to recover in open. In case of attentions in global blocks
12626                  * only the first in the chip should try to recover.
12627                  */
12628                 if ((!load_status && (!global || !other_load_status)) &&
12629                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12630                     BLOGI(sc, "Recovered during init\n");
12631                     break;
12632                 }
12633 
12634                 /* recovery has failed... */
12635                 bxe_set_power_state(sc, PCI_PM_D3hot);
12636                 sc->recovery_state = BXE_RECOVERY_FAILED;
12637 
12638                 BLOGE(sc, "Recovery flow hasn't properly "
12639                           "completed yet, try again later. "
12640                           "If you still see this message after a "
12641                           "few retries then power cycle is required.\n");
12642 
12643                 rc = ENXIO;
12644                 goto bxe_init_locked_done;
12645             } while (0);
12646         }
12647     }
12648 
12649     sc->recovery_state = BXE_RECOVERY_DONE;
12650 
12651     rc = bxe_nic_load(sc, LOAD_OPEN);
12652 
12653 bxe_init_locked_done:
12654 
12655     if (rc) {
12656         /* Tell the stack the driver is NOT running! */
12657         BLOGE(sc, "Initialization failed, "
12658                   "stack notified driver is NOT running!\n");
12659 	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
12660     }
12661 
12662     return (rc);
12663 }
12664 
12665 static int
12666 bxe_stop_locked(struct bxe_softc *sc)
12667 {
12668     BXE_CORE_LOCK_ASSERT(sc);
12669     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12670 }
12671 
12672 /*
12673  * Handles controller initialization when called from an unlocked routine.
12674  * ifconfig calls this function.
12675  *
12676  * Returns:
12677  *   void
12678  */
12679 static void
12680 bxe_init(void *xsc)
12681 {
12682     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12683 
12684     BXE_CORE_LOCK(sc);
12685     bxe_init_locked(sc);
12686     BXE_CORE_UNLOCK(sc);
12687 }
12688 
12689 static int
12690 bxe_init_ifnet(struct bxe_softc *sc)
12691 {
12692     if_t ifp;
12693     int capabilities;
12694 
12695     /* ifconfig entrypoint for media type/status reporting */
12696     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12697                  bxe_ifmedia_update,
12698                  bxe_ifmedia_status);
12699 
12700     /* set the default interface values */
12701     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12702     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12703     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12704 
12705     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12706 	BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
12707 
12708     /* allocate the ifnet structure */
12709     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
12710         BLOGE(sc, "Interface allocation failed!\n");
12711         return (ENXIO);
12712     }
12713 
12714     if_setsoftc(ifp, sc);
12715     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12716     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
12717     if_setioctlfn(ifp, bxe_ioctl);
12718     if_setstartfn(ifp, bxe_tx_start);
12719     if_setgetcounterfn(ifp, bxe_get_counter);
12720 #if __FreeBSD_version >= 901504
12721     if_settransmitfn(ifp, bxe_tx_mq_start);
12722     if_setqflushfn(ifp, bxe_mq_flush);
12723 #endif
12724 #ifdef FreeBSD8_0
12725     if_settimer(ifp, 0);
12726 #endif
12727     if_setinitfn(ifp, bxe_init);
12728     if_setmtu(ifp, sc->mtu);
12729     if_sethwassist(ifp, (CSUM_IP      |
12730                         CSUM_TCP      |
12731                         CSUM_UDP      |
12732                         CSUM_TSO      |
12733                         CSUM_TCP_IPV6 |
12734                         CSUM_UDP_IPV6));
12735 
12736     capabilities =
12737 #if __FreeBSD_version < 700000
12738         (IFCAP_VLAN_MTU       |
12739          IFCAP_VLAN_HWTAGGING |
12740          IFCAP_HWCSUM         |
12741          IFCAP_JUMBO_MTU      |
12742          IFCAP_LRO);
12743 #else
12744         (IFCAP_VLAN_MTU       |
12745          IFCAP_VLAN_HWTAGGING |
12746          IFCAP_VLAN_HWTSO     |
12747          IFCAP_VLAN_HWFILTER  |
12748          IFCAP_VLAN_HWCSUM    |
12749          IFCAP_HWCSUM         |
12750          IFCAP_JUMBO_MTU      |
12751          IFCAP_LRO            |
12752          IFCAP_TSO4           |
12753          IFCAP_TSO6           |
12754          IFCAP_WOL_MAGIC);
12755 #endif
12756     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
12757     if_setcapenable(ifp, if_getcapabilities(ifp));
12758     if_setbaudrate(ifp, IF_Gbps(10));
12759 /* XXX */
12760     if_setsendqlen(ifp, sc->tx_ring_size);
12761     if_setsendqready(ifp);
12762 /* XXX */
12763 
12764     sc->ifp = ifp;
12765 
12766     /* attach to the Ethernet interface list */
12767     ether_ifattach(ifp, sc->link_params.mac_addr);
12768 
12769     return (0);
12770 }
12771 
12772 static void
12773 bxe_deallocate_bars(struct bxe_softc *sc)
12774 {
12775     int i;
12776 
12777     for (i = 0; i < MAX_BARS; i++) {
12778         if (sc->bar[i].resource != NULL) {
12779             bus_release_resource(sc->dev,
12780                                  SYS_RES_MEMORY,
12781                                  sc->bar[i].rid,
12782                                  sc->bar[i].resource);
12783             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12784                   i, PCIR_BAR(i));
12785         }
12786     }
12787 }
12788 
12789 static int
12790 bxe_allocate_bars(struct bxe_softc *sc)
12791 {
12792     u_int flags;
12793     int i;
12794 
12795     memset(sc->bar, 0, sizeof(sc->bar));
12796 
12797     for (i = 0; i < MAX_BARS; i++) {
12798 
12799         /* memory resources reside at BARs 0, 2, 4 */
12800         /* Run `pciconf -lb` to see mappings */
12801         if ((i != 0) && (i != 2) && (i != 4)) {
12802             continue;
12803         }
12804 
12805         sc->bar[i].rid = PCIR_BAR(i);
12806 
12807         flags = RF_ACTIVE;
12808         if (i == 0) {
12809             flags |= RF_SHAREABLE;
12810         }
12811 
12812         if ((sc->bar[i].resource =
12813              bus_alloc_resource_any(sc->dev,
12814                                     SYS_RES_MEMORY,
12815                                     &sc->bar[i].rid,
12816                                     flags)) == NULL) {
12817             return (0);
12818         }
12819 
12820         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12821         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12822         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12823 
12824         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%jd) -> %p\n",
12825               i, PCIR_BAR(i),
12826               (void *)rman_get_start(sc->bar[i].resource),
12827               (void *)rman_get_end(sc->bar[i].resource),
12828               rman_get_size(sc->bar[i].resource),
12829               (void *)sc->bar[i].kva);
12830     }
12831 
12832     return (0);
12833 }
12834 
12835 static void
12836 bxe_get_function_num(struct bxe_softc *sc)
12837 {
12838     uint32_t val = 0;
12839 
12840     /*
12841      * Read the ME register to get the function number. The ME register
12842      * holds the relative-function number and absolute-function number. The
12843      * absolute-function number appears only in E2 and above. Before that
12844      * these bits always contained zero, therefore we cannot blindly use them.
12845      */
12846 
12847     val = REG_RD(sc, BAR_ME_REGISTER);
12848 
12849     sc->pfunc_rel =
12850         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12851     sc->path_id =
12852         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12853 
12854     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12855         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12856     } else {
12857         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12858     }
12859 
12860     BLOGD(sc, DBG_LOAD,
12861           "Relative function %d, Absolute function %d, Path %d\n",
12862           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12863 }
12864 
12865 static uint32_t
12866 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12867 {
12868     uint32_t shmem2_size;
12869     uint32_t offset;
12870     uint32_t mf_cfg_offset_value;
12871 
12872     /* Non 57712 */
12873     offset = (SHMEM_RD(sc, func_mb) +
12874               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12875 
12876     /* 57712 plus */
12877     if (sc->devinfo.shmem2_base != 0) {
12878         shmem2_size = SHMEM2_RD(sc, size);
12879         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12880             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12881             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12882                 offset = mf_cfg_offset_value;
12883             }
12884         }
12885     }
12886 
12887     return (offset);
12888 }
12889 
12890 static uint32_t
12891 bxe_pcie_capability_read(struct bxe_softc *sc,
12892                          int    reg,
12893                          int    width)
12894 {
12895     int pcie_reg;
12896 
12897     /* ensure PCIe capability is enabled */
12898     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12899         if (pcie_reg != 0) {
12900             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12901             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12902         }
12903     }
12904 
12905     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12906 
12907     return (0);
12908 }
12909 
12910 static uint8_t
12911 bxe_is_pcie_pending(struct bxe_softc *sc)
12912 {
12913     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12914             PCIM_EXP_STA_TRANSACTION_PND);
12915 }
12916 
12917 /*
12918  * Walk the PCI capabiites list for the device to find what features are
12919  * supported. These capabilites may be enabled/disabled by firmware so it's
12920  * best to walk the list rather than make assumptions.
12921  */
12922 static void
12923 bxe_probe_pci_caps(struct bxe_softc *sc)
12924 {
12925     uint16_t link_status;
12926     int reg;
12927 
12928     /* check if PCI Power Management is enabled */
12929     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12930         if (reg != 0) {
12931             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12932 
12933             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12934             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12935         }
12936     }
12937 
12938     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12939 
12940     /* handle PCIe 2.0 workarounds for 57710 */
12941     if (CHIP_IS_E1(sc)) {
12942         /* workaround for 57710 errata E4_57710_27462 */
12943         sc->devinfo.pcie_link_speed =
12944             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12945 
12946         /* workaround for 57710 errata E4_57710_27488 */
12947         sc->devinfo.pcie_link_width =
12948             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12949         if (sc->devinfo.pcie_link_speed > 1) {
12950             sc->devinfo.pcie_link_width =
12951                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12952         }
12953     } else {
12954         sc->devinfo.pcie_link_speed =
12955             (link_status & PCIM_LINK_STA_SPEED);
12956         sc->devinfo.pcie_link_width =
12957             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12958     }
12959 
12960     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12961           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12962 
12963     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12964     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12965 
12966     /* check if MSI capability is enabled */
12967     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12968         if (reg != 0) {
12969             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
12970 
12971             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
12972             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
12973         }
12974     }
12975 
12976     /* check if MSI-X capability is enabled */
12977     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
12978         if (reg != 0) {
12979             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
12980 
12981             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
12982             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
12983         }
12984     }
12985 }
12986 
12987 static int
12988 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
12989 {
12990     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12991     uint32_t val;
12992 
12993     /* get the outer vlan if we're in switch-dependent mode */
12994 
12995     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
12996     mf_info->ext_id = (uint16_t)val;
12997 
12998     mf_info->multi_vnics_mode = 1;
12999 
13000     if (!VALID_OVLAN(mf_info->ext_id)) {
13001         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13002         return (1);
13003     }
13004 
13005     /* get the capabilities */
13006     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13007         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13008         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13009     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13010                FUNC_MF_CFG_PROTOCOL_FCOE) {
13011         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13012     } else {
13013         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13014     }
13015 
13016     mf_info->vnics_per_port =
13017         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13018 
13019     return (0);
13020 }
13021 
13022 static uint32_t
13023 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13024 {
13025     uint32_t retval = 0;
13026     uint32_t val;
13027 
13028     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13029 
13030     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13031         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13032             retval |= MF_PROTO_SUPPORT_ETHERNET;
13033         }
13034         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13035             retval |= MF_PROTO_SUPPORT_ISCSI;
13036         }
13037         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13038             retval |= MF_PROTO_SUPPORT_FCOE;
13039         }
13040     }
13041 
13042     return (retval);
13043 }
13044 
13045 static int
13046 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13047 {
13048     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13049     uint32_t val;
13050 
13051     /*
13052      * There is no outer vlan if we're in switch-independent mode.
13053      * If the mac is valid then assume multi-function.
13054      */
13055 
13056     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13057 
13058     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13059 
13060     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13061 
13062     mf_info->vnics_per_port =
13063         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13064 
13065     return (0);
13066 }
13067 
13068 static int
13069 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13070 {
13071     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13072     uint32_t e1hov_tag;
13073     uint32_t func_config;
13074     uint32_t niv_config;
13075 
13076     mf_info->multi_vnics_mode = 1;
13077 
13078     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13079     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13080     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13081 
13082     mf_info->ext_id =
13083         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13084                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13085 
13086     mf_info->default_vlan =
13087         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13088                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13089 
13090     mf_info->niv_allowed_priorities =
13091         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13092                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13093 
13094     mf_info->niv_default_cos =
13095         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13096                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13097 
13098     mf_info->afex_vlan_mode =
13099         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13100          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13101 
13102     mf_info->niv_mba_enabled =
13103         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13104          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13105 
13106     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13107 
13108     mf_info->vnics_per_port =
13109         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13110 
13111     return (0);
13112 }
13113 
13114 static int
13115 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13116 {
13117     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13118     uint32_t mf_cfg1;
13119     uint32_t mf_cfg2;
13120     uint32_t ovlan1;
13121     uint32_t ovlan2;
13122     uint8_t i, j;
13123 
13124     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13125           SC_PORT(sc));
13126     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13127           mf_info->mf_config[SC_VN(sc)]);
13128     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13129           mf_info->multi_vnics_mode);
13130     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13131           mf_info->vnics_per_port);
13132     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13133           mf_info->ext_id);
13134     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13135           mf_info->min_bw[0], mf_info->min_bw[1],
13136           mf_info->min_bw[2], mf_info->min_bw[3]);
13137     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13138           mf_info->max_bw[0], mf_info->max_bw[1],
13139           mf_info->max_bw[2], mf_info->max_bw[3]);
13140     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13141           sc->mac_addr_str);
13142 
13143     /* various MF mode sanity checks... */
13144 
13145     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13146         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13147               SC_PORT(sc));
13148         return (1);
13149     }
13150 
13151     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13152         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13153               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13154         return (1);
13155     }
13156 
13157     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13158         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13159         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13160             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13161                   SC_VN(sc), OVLAN(sc));
13162             return (1);
13163         }
13164 
13165         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13166             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13167                   mf_info->multi_vnics_mode, OVLAN(sc));
13168             return (1);
13169         }
13170 
13171         /*
13172          * Verify all functions are either MF or SF mode. If MF, make sure
13173          * sure that all non-hidden functions have a valid ovlan. If SF,
13174          * make sure that all non-hidden functions have an invalid ovlan.
13175          */
13176         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13177             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13178             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13179             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13180                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13181                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13182                 BLOGE(sc, "mf_mode=SD function %d MF config "
13183                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13184                       i, mf_info->multi_vnics_mode, ovlan1);
13185                 return (1);
13186             }
13187         }
13188 
13189         /* Verify all funcs on the same port each have a different ovlan. */
13190         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13191             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13192             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13193             /* iterate from the next function on the port to the max func */
13194             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13195                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13196                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13197                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13198                     VALID_OVLAN(ovlan1) &&
13199                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13200                     VALID_OVLAN(ovlan2) &&
13201                     (ovlan1 == ovlan2)) {
13202                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13203                               "have the same ovlan (%d)\n",
13204                           i, j, ovlan1);
13205                     return (1);
13206                 }
13207             }
13208         }
13209     } /* MULTI_FUNCTION_SD */
13210 
13211     return (0);
13212 }
13213 
13214 static int
13215 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13216 {
13217     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13218     uint32_t val, mac_upper;
13219     uint8_t i, vnic;
13220 
13221     /* initialize mf_info defaults */
13222     mf_info->vnics_per_port   = 1;
13223     mf_info->multi_vnics_mode = FALSE;
13224     mf_info->path_has_ovlan   = FALSE;
13225     mf_info->mf_mode          = SINGLE_FUNCTION;
13226 
13227     if (!CHIP_IS_MF_CAP(sc)) {
13228         return (0);
13229     }
13230 
13231     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13232         BLOGE(sc, "Invalid mf_cfg_base!\n");
13233         return (1);
13234     }
13235 
13236     /* get the MF mode (switch dependent / independent / single-function) */
13237 
13238     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13239 
13240     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13241     {
13242     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13243 
13244         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13245 
13246         /* check for legal upper mac bytes */
13247         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13248             mf_info->mf_mode = MULTI_FUNCTION_SI;
13249         } else {
13250             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13251         }
13252 
13253         break;
13254 
13255     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13256     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13257 
13258         /* get outer vlan configuration */
13259         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13260 
13261         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13262             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13263             mf_info->mf_mode = MULTI_FUNCTION_SD;
13264         } else {
13265             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13266         }
13267 
13268         break;
13269 
13270     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13271 
13272         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13273         return (0);
13274 
13275     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13276 
13277         /*
13278          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13279          * and the MAC address is valid.
13280          */
13281         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13282 
13283         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13284             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13285             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13286         } else {
13287             BLOGE(sc, "Invalid config for AFEX mode\n");
13288         }
13289 
13290         break;
13291 
13292     default:
13293 
13294         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13295               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13296 
13297         return (1);
13298     }
13299 
13300     /* set path mf_mode (which could be different than function mf_mode) */
13301     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13302         mf_info->path_has_ovlan = TRUE;
13303     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13304         /*
13305          * Decide on path multi vnics mode. If we're not in MF mode and in
13306          * 4-port mode, this is good enough to check vnic-0 of the other port
13307          * on the same path
13308          */
13309         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13310             uint8_t other_port = !(PORT_ID(sc) & 1);
13311             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13312 
13313             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13314 
13315             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13316         }
13317     }
13318 
13319     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13320         /* invalid MF config */
13321         if (SC_VN(sc) >= 1) {
13322             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13323             return (1);
13324         }
13325 
13326         return (0);
13327     }
13328 
13329     /* get the MF configuration */
13330     mf_info->mf_config[SC_VN(sc)] =
13331         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13332 
13333     switch(mf_info->mf_mode)
13334     {
13335     case MULTI_FUNCTION_SD:
13336 
13337         bxe_get_shmem_mf_cfg_info_sd(sc);
13338         break;
13339 
13340     case MULTI_FUNCTION_SI:
13341 
13342         bxe_get_shmem_mf_cfg_info_si(sc);
13343         break;
13344 
13345     case MULTI_FUNCTION_AFEX:
13346 
13347         bxe_get_shmem_mf_cfg_info_niv(sc);
13348         break;
13349 
13350     default:
13351 
13352         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13353               mf_info->mf_mode);
13354         return (1);
13355     }
13356 
13357     /* get the congestion management parameters */
13358 
13359     vnic = 0;
13360     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13361         /* get min/max bw */
13362         val = MFCFG_RD(sc, func_mf_config[i].config);
13363         mf_info->min_bw[vnic] =
13364             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13365         mf_info->max_bw[vnic] =
13366             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13367         vnic++;
13368     }
13369 
13370     return (bxe_check_valid_mf_cfg(sc));
13371 }
13372 
13373 static int
13374 bxe_get_shmem_info(struct bxe_softc *sc)
13375 {
13376     int port;
13377     uint32_t mac_hi, mac_lo, val;
13378 
13379     port = SC_PORT(sc);
13380     mac_hi = mac_lo = 0;
13381 
13382     sc->link_params.sc   = sc;
13383     sc->link_params.port = port;
13384 
13385     /* get the hardware config info */
13386     sc->devinfo.hw_config =
13387         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13388     sc->devinfo.hw_config2 =
13389         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13390 
13391     sc->link_params.hw_led_mode =
13392         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13393          SHARED_HW_CFG_LED_MODE_SHIFT);
13394 
13395     /* get the port feature config */
13396     sc->port.config =
13397         SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13398 
13399     /* get the link params */
13400     sc->link_params.speed_cap_mask[0] =
13401         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13402     sc->link_params.speed_cap_mask[1] =
13403         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13404 
13405     /* get the lane config */
13406     sc->link_params.lane_config =
13407         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13408 
13409     /* get the link config */
13410     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13411     sc->port.link_config[ELINK_INT_PHY] = val;
13412     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13413     sc->port.link_config[ELINK_EXT_PHY1] =
13414         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13415 
13416     /* get the override preemphasis flag and enable it or turn it off */
13417     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13418     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13419         sc->link_params.feature_config_flags |=
13420             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13421     } else {
13422         sc->link_params.feature_config_flags &=
13423             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13424     }
13425 
13426     /* get the initial value of the link params */
13427     sc->link_params.multi_phy_config =
13428         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13429 
13430     /* get external phy info */
13431     sc->port.ext_phy_config =
13432         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13433 
13434     /* get the multifunction configuration */
13435     bxe_get_mf_cfg_info(sc);
13436 
13437     /* get the mac address */
13438     if (IS_MF(sc)) {
13439         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13440         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13441     } else {
13442         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13443         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13444     }
13445 
13446     if ((mac_lo == 0) && (mac_hi == 0)) {
13447         *sc->mac_addr_str = 0;
13448         BLOGE(sc, "No Ethernet address programmed!\n");
13449     } else {
13450         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13451         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13452         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13453         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13454         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13455         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13456         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13457                  "%02x:%02x:%02x:%02x:%02x:%02x",
13458                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13459                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13460                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13461         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13462     }
13463 
13464     return (0);
13465 }
13466 
13467 static void
13468 bxe_get_tunable_params(struct bxe_softc *sc)
13469 {
13470     /* sanity checks */
13471 
13472     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13473         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13474         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13475         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13476         bxe_interrupt_mode = INTR_MODE_MSIX;
13477     }
13478 
13479     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13480         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13481         bxe_queue_count = 0;
13482     }
13483 
13484     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13485         if (bxe_max_rx_bufs == 0) {
13486             bxe_max_rx_bufs = RX_BD_USABLE;
13487         } else {
13488             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13489             bxe_max_rx_bufs = 2048;
13490         }
13491     }
13492 
13493     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13494         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13495         bxe_hc_rx_ticks = 25;
13496     }
13497 
13498     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13499         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13500         bxe_hc_tx_ticks = 50;
13501     }
13502 
13503     if (bxe_max_aggregation_size == 0) {
13504         bxe_max_aggregation_size = TPA_AGG_SIZE;
13505     }
13506 
13507     if (bxe_max_aggregation_size > 0xffff) {
13508         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13509               bxe_max_aggregation_size);
13510         bxe_max_aggregation_size = TPA_AGG_SIZE;
13511     }
13512 
13513     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13514         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13515         bxe_mrrs = -1;
13516     }
13517 
13518     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13519         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13520         bxe_autogreeen = 0;
13521     }
13522 
13523     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13524         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13525         bxe_udp_rss = 0;
13526     }
13527 
13528     /* pull in user settings */
13529 
13530     sc->interrupt_mode       = bxe_interrupt_mode;
13531     sc->max_rx_bufs          = bxe_max_rx_bufs;
13532     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13533     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13534     sc->max_aggregation_size = bxe_max_aggregation_size;
13535     sc->mrrs                 = bxe_mrrs;
13536     sc->autogreeen           = bxe_autogreeen;
13537     sc->udp_rss              = bxe_udp_rss;
13538 
13539     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13540         sc->num_queues = 1;
13541     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13542         sc->num_queues =
13543             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13544                 MAX_RSS_CHAINS);
13545         if (sc->num_queues > mp_ncpus) {
13546             sc->num_queues = mp_ncpus;
13547         }
13548     }
13549 
13550     BLOGD(sc, DBG_LOAD,
13551           "User Config: "
13552           "debug=0x%lx "
13553           "interrupt_mode=%d "
13554           "queue_count=%d "
13555           "hc_rx_ticks=%d "
13556           "hc_tx_ticks=%d "
13557           "rx_budget=%d "
13558           "max_aggregation_size=%d "
13559           "mrrs=%d "
13560           "autogreeen=%d "
13561           "udp_rss=%d\n",
13562           bxe_debug,
13563           sc->interrupt_mode,
13564           sc->num_queues,
13565           sc->hc_rx_ticks,
13566           sc->hc_tx_ticks,
13567           bxe_rx_budget,
13568           sc->max_aggregation_size,
13569           sc->mrrs,
13570           sc->autogreeen,
13571           sc->udp_rss);
13572 }
13573 
13574 static int
13575 bxe_media_detect(struct bxe_softc *sc)
13576 {
13577     int port_type;
13578     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13579 
13580     switch (sc->link_params.phy[phy_idx].media_type) {
13581     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13582     case ELINK_ETH_PHY_XFP_FIBER:
13583         BLOGI(sc, "Found 10Gb Fiber media.\n");
13584         sc->media = IFM_10G_SR;
13585         port_type = PORT_FIBRE;
13586         break;
13587     case ELINK_ETH_PHY_SFP_1G_FIBER:
13588         BLOGI(sc, "Found 1Gb Fiber media.\n");
13589         sc->media = IFM_1000_SX;
13590         port_type = PORT_FIBRE;
13591         break;
13592     case ELINK_ETH_PHY_KR:
13593     case ELINK_ETH_PHY_CX4:
13594         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13595         sc->media = IFM_10G_CX4;
13596         port_type = PORT_FIBRE;
13597         break;
13598     case ELINK_ETH_PHY_DA_TWINAX:
13599         BLOGI(sc, "Found 10Gb Twinax media.\n");
13600         sc->media = IFM_10G_TWINAX;
13601         port_type = PORT_DA;
13602         break;
13603     case ELINK_ETH_PHY_BASE_T:
13604         if (sc->link_params.speed_cap_mask[0] &
13605             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13606             BLOGI(sc, "Found 10GBase-T media.\n");
13607             sc->media = IFM_10G_T;
13608             port_type = PORT_TP;
13609         } else {
13610             BLOGI(sc, "Found 1000Base-T media.\n");
13611             sc->media = IFM_1000_T;
13612             port_type = PORT_TP;
13613         }
13614         break;
13615     case ELINK_ETH_PHY_NOT_PRESENT:
13616         BLOGI(sc, "Media not present.\n");
13617         sc->media = 0;
13618         port_type = PORT_OTHER;
13619         break;
13620     case ELINK_ETH_PHY_UNSPECIFIED:
13621     default:
13622         BLOGI(sc, "Unknown media!\n");
13623         sc->media = 0;
13624         port_type = PORT_OTHER;
13625         break;
13626     }
13627     return port_type;
13628 }
13629 
13630 #define GET_FIELD(value, fname)                     \
13631     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13632 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13633 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13634 
13635 static int
13636 bxe_get_igu_cam_info(struct bxe_softc *sc)
13637 {
13638     int pfid = SC_FUNC(sc);
13639     int igu_sb_id;
13640     uint32_t val;
13641     uint8_t fid, igu_sb_cnt = 0;
13642 
13643     sc->igu_base_sb = 0xff;
13644 
13645     if (CHIP_INT_MODE_IS_BC(sc)) {
13646         int vn = SC_VN(sc);
13647         igu_sb_cnt = sc->igu_sb_cnt;
13648         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13649                            FP_SB_MAX_E1x);
13650         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13651                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13652         return (0);
13653     }
13654 
13655     /* IGU in normal mode - read CAM */
13656     for (igu_sb_id = 0;
13657          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13658          igu_sb_id++) {
13659         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13660         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13661             continue;
13662         }
13663         fid = IGU_FID(val);
13664         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13665             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13666                 continue;
13667             }
13668             if (IGU_VEC(val) == 0) {
13669                 /* default status block */
13670                 sc->igu_dsb_id = igu_sb_id;
13671             } else {
13672                 if (sc->igu_base_sb == 0xff) {
13673                     sc->igu_base_sb = igu_sb_id;
13674                 }
13675                 igu_sb_cnt++;
13676             }
13677         }
13678     }
13679 
13680     /*
13681      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13682      * that number of CAM entries will not be equal to the value advertised in
13683      * PCI. Driver should use the minimal value of both as the actual status
13684      * block count
13685      */
13686     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13687 
13688     if (igu_sb_cnt == 0) {
13689         BLOGE(sc, "CAM configuration error\n");
13690         return (-1);
13691     }
13692 
13693     return (0);
13694 }
13695 
13696 /*
13697  * Gather various information from the device config space, the device itself,
13698  * shmem, and the user input.
13699  */
13700 static int
13701 bxe_get_device_info(struct bxe_softc *sc)
13702 {
13703     uint32_t val;
13704     int rc;
13705 
13706     /* Get the data for the device */
13707     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13708     sc->devinfo.device_id    = pci_get_device(sc->dev);
13709     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13710     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13711 
13712     /* get the chip revision (chip metal comes from pci config space) */
13713     sc->devinfo.chip_id     =
13714     sc->link_params.chip_id =
13715         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13716          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13717          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13718          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13719 
13720     /* force 57811 according to MISC register */
13721     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13722         if (CHIP_IS_57810(sc)) {
13723             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13724                                    (sc->devinfo.chip_id & 0x0000ffff));
13725         } else if (CHIP_IS_57810_MF(sc)) {
13726             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13727                                    (sc->devinfo.chip_id & 0x0000ffff));
13728         }
13729         sc->devinfo.chip_id |= 0x1;
13730     }
13731 
13732     BLOGD(sc, DBG_LOAD,
13733           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13734           sc->devinfo.chip_id,
13735           ((sc->devinfo.chip_id >> 16) & 0xffff),
13736           ((sc->devinfo.chip_id >> 12) & 0xf),
13737           ((sc->devinfo.chip_id >>  4) & 0xff),
13738           ((sc->devinfo.chip_id >>  0) & 0xf));
13739 
13740     val = (REG_RD(sc, 0x2874) & 0x55);
13741     if ((sc->devinfo.chip_id & 0x1) ||
13742         (CHIP_IS_E1(sc) && val) ||
13743         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13744         sc->flags |= BXE_ONE_PORT_FLAG;
13745         BLOGD(sc, DBG_LOAD, "single port device\n");
13746     }
13747 
13748     /* set the doorbell size */
13749     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13750 
13751     /* determine whether the device is in 2 port or 4 port mode */
13752     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13753     if (CHIP_IS_E2E3(sc)) {
13754         /*
13755          * Read port4mode_en_ovwr[0]:
13756          *   If 1, four port mode is in port4mode_en_ovwr[1].
13757          *   If 0, four port mode is in port4mode_en[0].
13758          */
13759         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13760         if (val & 1) {
13761             val = ((val >> 1) & 1);
13762         } else {
13763             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13764         }
13765 
13766         sc->devinfo.chip_port_mode =
13767             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13768 
13769         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13770     }
13771 
13772     /* get the function and path info for the device */
13773     bxe_get_function_num(sc);
13774 
13775     /* get the shared memory base address */
13776     sc->devinfo.shmem_base     =
13777     sc->link_params.shmem_base =
13778         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13779     sc->devinfo.shmem2_base =
13780         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13781                                   MISC_REG_GENERIC_CR_0));
13782 
13783     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13784           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13785 
13786     if (!sc->devinfo.shmem_base) {
13787         /* this should ONLY prevent upcoming shmem reads */
13788         BLOGI(sc, "MCP not active\n");
13789         sc->flags |= BXE_NO_MCP_FLAG;
13790         return (0);
13791     }
13792 
13793     /* make sure the shared memory contents are valid */
13794     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13795     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13796         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13797         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13798         return (0);
13799     }
13800     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13801 
13802     /* get the bootcode version */
13803     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13804     snprintf(sc->devinfo.bc_ver_str,
13805              sizeof(sc->devinfo.bc_ver_str),
13806              "%d.%d.%d",
13807              ((sc->devinfo.bc_ver >> 24) & 0xff),
13808              ((sc->devinfo.bc_ver >> 16) & 0xff),
13809              ((sc->devinfo.bc_ver >>  8) & 0xff));
13810     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13811 
13812     /* get the bootcode shmem address */
13813     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13814     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13815 
13816     /* clean indirect addresses as they're not used */
13817     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13818     if (IS_PF(sc)) {
13819         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13820         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13821         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13822         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13823         if (CHIP_IS_E1x(sc)) {
13824             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13825             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13826             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13827             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13828         }
13829 
13830         /*
13831          * Enable internal target-read (in case we are probed after PF
13832          * FLR). Must be done prior to any BAR read access. Only for
13833          * 57712 and up
13834          */
13835         if (!CHIP_IS_E1x(sc)) {
13836             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13837         }
13838     }
13839 
13840     /* get the nvram size */
13841     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13842     sc->devinfo.flash_size =
13843         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13844     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13845 
13846     /* get PCI capabilites */
13847     bxe_probe_pci_caps(sc);
13848 
13849     bxe_set_power_state(sc, PCI_PM_D0);
13850 
13851     /* get various configuration parameters from shmem */
13852     bxe_get_shmem_info(sc);
13853 
13854     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13855         val = pci_read_config(sc->dev,
13856                               (sc->devinfo.pcie_msix_cap_reg +
13857                                PCIR_MSIX_CTRL),
13858                               2);
13859         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13860     } else {
13861         sc->igu_sb_cnt = 1;
13862     }
13863 
13864     sc->igu_base_addr = BAR_IGU_INTMEM;
13865 
13866     /* initialize IGU parameters */
13867     if (CHIP_IS_E1x(sc)) {
13868         sc->devinfo.int_block = INT_BLOCK_HC;
13869         sc->igu_dsb_id = DEF_SB_IGU_ID;
13870         sc->igu_base_sb = 0;
13871     } else {
13872         sc->devinfo.int_block = INT_BLOCK_IGU;
13873 
13874         /* do not allow device reset during IGU info preocessing */
13875         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13876 
13877         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13878 
13879         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13880             int tout = 5000;
13881 
13882             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13883 
13884             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13885             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13886             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13887 
13888             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13889                 tout--;
13890                 DELAY(1000);
13891             }
13892 
13893             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13894                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13895                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13896                 return (-1);
13897             }
13898         }
13899 
13900         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13901             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13902             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13903         } else {
13904             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13905         }
13906 
13907         rc = bxe_get_igu_cam_info(sc);
13908 
13909         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13910 
13911         if (rc) {
13912             return (rc);
13913         }
13914     }
13915 
13916     /*
13917      * Get base FW non-default (fast path) status block ID. This value is
13918      * used to initialize the fw_sb_id saved on the fp/queue structure to
13919      * determine the id used by the FW.
13920      */
13921     if (CHIP_IS_E1x(sc)) {
13922         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13923     } else {
13924         /*
13925          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13926          * the same queue are indicated on the same IGU SB). So we prefer
13927          * FW and IGU SBs to be the same value.
13928          */
13929         sc->base_fw_ndsb = sc->igu_base_sb;
13930     }
13931 
13932     BLOGD(sc, DBG_LOAD,
13933           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13934           sc->igu_dsb_id, sc->igu_base_sb,
13935           sc->igu_sb_cnt, sc->base_fw_ndsb);
13936 
13937     elink_phy_probe(&sc->link_params);
13938 
13939     return (0);
13940 }
13941 
13942 static void
13943 bxe_link_settings_supported(struct bxe_softc *sc,
13944                             uint32_t         switch_cfg)
13945 {
13946     uint32_t cfg_size = 0;
13947     uint32_t idx;
13948     uint8_t port = SC_PORT(sc);
13949 
13950     /* aggregation of supported attributes of all external phys */
13951     sc->port.supported[0] = 0;
13952     sc->port.supported[1] = 0;
13953 
13954     switch (sc->link_params.num_phys) {
13955     case 1:
13956         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13957         cfg_size = 1;
13958         break;
13959     case 2:
13960         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13961         cfg_size = 1;
13962         break;
13963     case 3:
13964         if (sc->link_params.multi_phy_config &
13965             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13966             sc->port.supported[1] =
13967                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13968             sc->port.supported[0] =
13969                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13970         } else {
13971             sc->port.supported[0] =
13972                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13973             sc->port.supported[1] =
13974                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13975         }
13976         cfg_size = 2;
13977         break;
13978     }
13979 
13980     if (!(sc->port.supported[0] || sc->port.supported[1])) {
13981         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
13982               SHMEM_RD(sc,
13983                        dev_info.port_hw_config[port].external_phy_config),
13984               SHMEM_RD(sc,
13985                        dev_info.port_hw_config[port].external_phy_config2));
13986         return;
13987     }
13988 
13989     if (CHIP_IS_E3(sc))
13990         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
13991     else {
13992         switch (switch_cfg) {
13993         case ELINK_SWITCH_CFG_1G:
13994             sc->port.phy_addr =
13995                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
13996             break;
13997         case ELINK_SWITCH_CFG_10G:
13998             sc->port.phy_addr =
13999                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14000             break;
14001         default:
14002             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14003                   sc->port.link_config[0]);
14004             return;
14005         }
14006     }
14007 
14008     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14009 
14010     /* mask what we support according to speed_cap_mask per configuration */
14011     for (idx = 0; idx < cfg_size; idx++) {
14012         if (!(sc->link_params.speed_cap_mask[idx] &
14013               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14014             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14015         }
14016 
14017         if (!(sc->link_params.speed_cap_mask[idx] &
14018               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14019             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14020         }
14021 
14022         if (!(sc->link_params.speed_cap_mask[idx] &
14023               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14024             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14025         }
14026 
14027         if (!(sc->link_params.speed_cap_mask[idx] &
14028               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14029             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14030         }
14031 
14032         if (!(sc->link_params.speed_cap_mask[idx] &
14033               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14034             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14035         }
14036 
14037         if (!(sc->link_params.speed_cap_mask[idx] &
14038               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14039             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14040         }
14041 
14042         if (!(sc->link_params.speed_cap_mask[idx] &
14043               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14044             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14045         }
14046 
14047         if (!(sc->link_params.speed_cap_mask[idx] &
14048               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14049             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14050         }
14051     }
14052 
14053     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14054           sc->port.supported[0], sc->port.supported[1]);
14055 	ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14056 					sc->port.supported[0], sc->port.supported[1]);
14057 }
14058 
14059 static void
14060 bxe_link_settings_requested(struct bxe_softc *sc)
14061 {
14062     uint32_t link_config;
14063     uint32_t idx;
14064     uint32_t cfg_size = 0;
14065 
14066     sc->port.advertising[0] = 0;
14067     sc->port.advertising[1] = 0;
14068 
14069     switch (sc->link_params.num_phys) {
14070     case 1:
14071     case 2:
14072         cfg_size = 1;
14073         break;
14074     case 3:
14075         cfg_size = 2;
14076         break;
14077     }
14078 
14079     for (idx = 0; idx < cfg_size; idx++) {
14080         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14081         link_config = sc->port.link_config[idx];
14082 
14083         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14084         case PORT_FEATURE_LINK_SPEED_AUTO:
14085             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14086                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14087                 sc->port.advertising[idx] |= sc->port.supported[idx];
14088                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14089                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14090                     sc->port.advertising[idx] |=
14091                         (ELINK_SUPPORTED_100baseT_Half |
14092                          ELINK_SUPPORTED_100baseT_Full);
14093             } else {
14094                 /* force 10G, no AN */
14095                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14096                 sc->port.advertising[idx] |=
14097                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14098                 continue;
14099             }
14100             break;
14101 
14102         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14103             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14104                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14105                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14106                                               ADVERTISED_TP);
14107             } else {
14108                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14109                           "speed_cap_mask=0x%08x\n",
14110                       link_config, sc->link_params.speed_cap_mask[idx]);
14111                 return;
14112             }
14113             break;
14114 
14115         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14116             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14117                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14118                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14119                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14120                                               ADVERTISED_TP);
14121 				ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14122 								sc->link_params.req_duplex[idx]);
14123             } else {
14124                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14125                           "speed_cap_mask=0x%08x\n",
14126                       link_config, sc->link_params.speed_cap_mask[idx]);
14127                 return;
14128             }
14129             break;
14130 
14131         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14132             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14133                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14134                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14135                                               ADVERTISED_TP);
14136             } else {
14137                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14138                           "speed_cap_mask=0x%08x\n",
14139                       link_config, sc->link_params.speed_cap_mask[idx]);
14140                 return;
14141             }
14142             break;
14143 
14144         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14145             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14146                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14147                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14148                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14149                                               ADVERTISED_TP);
14150             } else {
14151                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14152                           "speed_cap_mask=0x%08x\n",
14153                       link_config, sc->link_params.speed_cap_mask[idx]);
14154                 return;
14155             }
14156             break;
14157 
14158         case PORT_FEATURE_LINK_SPEED_1G:
14159             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14160                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14161                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14162                                               ADVERTISED_TP);
14163             } else {
14164                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14165                           "speed_cap_mask=0x%08x\n",
14166                       link_config, sc->link_params.speed_cap_mask[idx]);
14167                 return;
14168             }
14169             break;
14170 
14171         case PORT_FEATURE_LINK_SPEED_2_5G:
14172             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14173                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14174                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14175                                               ADVERTISED_TP);
14176             } else {
14177                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14178                           "speed_cap_mask=0x%08x\n",
14179                       link_config, sc->link_params.speed_cap_mask[idx]);
14180                 return;
14181             }
14182             break;
14183 
14184         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14185             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14186                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14187                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14188                                               ADVERTISED_FIBRE);
14189             } else {
14190                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14191                           "speed_cap_mask=0x%08x\n",
14192                       link_config, sc->link_params.speed_cap_mask[idx]);
14193                 return;
14194             }
14195             break;
14196 
14197         case PORT_FEATURE_LINK_SPEED_20G:
14198             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14199             break;
14200 
14201         default:
14202             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14203                       "speed_cap_mask=0x%08x\n",
14204                   link_config, sc->link_params.speed_cap_mask[idx]);
14205             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14206             sc->port.advertising[idx] = sc->port.supported[idx];
14207             break;
14208         }
14209 
14210         sc->link_params.req_flow_ctrl[idx] =
14211             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14212 
14213         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14214             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14215                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14216             } else {
14217                 bxe_set_requested_fc(sc);
14218             }
14219         }
14220 
14221         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14222                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14223               sc->link_params.req_line_speed[idx],
14224               sc->link_params.req_duplex[idx],
14225               sc->link_params.req_flow_ctrl[idx],
14226               sc->port.advertising[idx]);
14227 		ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14228 						"advertising=0x%x\n",
14229 						sc->link_params.req_line_speed[idx],
14230 						sc->link_params.req_duplex[idx],
14231 						sc->port.advertising[idx]);
14232     }
14233 }
14234 
14235 static void
14236 bxe_get_phy_info(struct bxe_softc *sc)
14237 {
14238     uint8_t port = SC_PORT(sc);
14239     uint32_t config = sc->port.config;
14240     uint32_t eee_mode;
14241 
14242     /* shmem data already read in bxe_get_shmem_info() */
14243 
14244     ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14245                         "link_config0=0x%08x\n",
14246                sc->link_params.lane_config,
14247                sc->link_params.speed_cap_mask[0],
14248                sc->port.link_config[0]);
14249 
14250 
14251     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14252     bxe_link_settings_requested(sc);
14253 
14254     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14255         sc->link_params.feature_config_flags |=
14256             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14257     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14258         sc->link_params.feature_config_flags &=
14259             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14260     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14261         sc->link_params.feature_config_flags |=
14262             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14263     }
14264 
14265     /* configure link feature according to nvram value */
14266     eee_mode =
14267         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14268           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14269          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14270     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14271         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14272                                     ELINK_EEE_MODE_ENABLE_LPI |
14273                                     ELINK_EEE_MODE_OUTPUT_TIME);
14274     } else {
14275         sc->link_params.eee_mode = 0;
14276     }
14277 
14278     /* get the media type */
14279     bxe_media_detect(sc);
14280 	ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14281 }
14282 
14283 static void
14284 bxe_get_params(struct bxe_softc *sc)
14285 {
14286     /* get user tunable params */
14287     bxe_get_tunable_params(sc);
14288 
14289     /* select the RX and TX ring sizes */
14290     sc->tx_ring_size = TX_BD_USABLE;
14291     sc->rx_ring_size = RX_BD_USABLE;
14292 
14293     /* XXX disable WoL */
14294     sc->wol = 0;
14295 }
14296 
14297 static void
14298 bxe_set_modes_bitmap(struct bxe_softc *sc)
14299 {
14300     uint32_t flags = 0;
14301 
14302     if (CHIP_REV_IS_FPGA(sc)) {
14303         SET_FLAGS(flags, MODE_FPGA);
14304     } else if (CHIP_REV_IS_EMUL(sc)) {
14305         SET_FLAGS(flags, MODE_EMUL);
14306     } else {
14307         SET_FLAGS(flags, MODE_ASIC);
14308     }
14309 
14310     if (CHIP_IS_MODE_4_PORT(sc)) {
14311         SET_FLAGS(flags, MODE_PORT4);
14312     } else {
14313         SET_FLAGS(flags, MODE_PORT2);
14314     }
14315 
14316     if (CHIP_IS_E2(sc)) {
14317         SET_FLAGS(flags, MODE_E2);
14318     } else if (CHIP_IS_E3(sc)) {
14319         SET_FLAGS(flags, MODE_E3);
14320         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14321             SET_FLAGS(flags, MODE_E3_A0);
14322         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14323             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14324         }
14325     }
14326 
14327     if (IS_MF(sc)) {
14328         SET_FLAGS(flags, MODE_MF);
14329         switch (sc->devinfo.mf_info.mf_mode) {
14330         case MULTI_FUNCTION_SD:
14331             SET_FLAGS(flags, MODE_MF_SD);
14332             break;
14333         case MULTI_FUNCTION_SI:
14334             SET_FLAGS(flags, MODE_MF_SI);
14335             break;
14336         case MULTI_FUNCTION_AFEX:
14337             SET_FLAGS(flags, MODE_MF_AFEX);
14338             break;
14339         }
14340     } else {
14341         SET_FLAGS(flags, MODE_SF);
14342     }
14343 
14344 #if defined(__LITTLE_ENDIAN)
14345     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14346 #else /* __BIG_ENDIAN */
14347     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14348 #endif
14349 
14350     INIT_MODE_FLAGS(sc) = flags;
14351 }
14352 
14353 static int
14354 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14355 {
14356     struct bxe_fastpath *fp;
14357     bus_addr_t busaddr;
14358     int max_agg_queues;
14359     int max_segments;
14360     bus_size_t max_size;
14361     bus_size_t max_seg_size;
14362     char buf[32];
14363     int rc;
14364     int i, j;
14365 
14366     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14367 
14368     /* allocate the parent bus DMA tag */
14369     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14370                             1,                        /* alignment */
14371                             0,                        /* boundary limit */
14372                             BUS_SPACE_MAXADDR,        /* restricted low */
14373                             BUS_SPACE_MAXADDR,        /* restricted hi */
14374                             NULL,                     /* addr filter() */
14375                             NULL,                     /* addr filter() arg */
14376                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14377                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14378                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14379                             0,                        /* flags */
14380                             NULL,                     /* lock() */
14381                             NULL,                     /* lock() arg */
14382                             &sc->parent_dma_tag);     /* returned dma tag */
14383     if (rc != 0) {
14384         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14385         return (1);
14386     }
14387 
14388     /************************/
14389     /* DEFAULT STATUS BLOCK */
14390     /************************/
14391 
14392     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14393                       &sc->def_sb_dma, "default status block") != 0) {
14394         /* XXX */
14395         bus_dma_tag_destroy(sc->parent_dma_tag);
14396         return (1);
14397     }
14398 
14399     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14400 
14401     /***************/
14402     /* EVENT QUEUE */
14403     /***************/
14404 
14405     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14406                       &sc->eq_dma, "event queue") != 0) {
14407         /* XXX */
14408         bxe_dma_free(sc, &sc->def_sb_dma);
14409         sc->def_sb = NULL;
14410         bus_dma_tag_destroy(sc->parent_dma_tag);
14411         return (1);
14412     }
14413 
14414     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14415 
14416     /*************/
14417     /* SLOW PATH */
14418     /*************/
14419 
14420     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14421                       &sc->sp_dma, "slow path") != 0) {
14422         /* XXX */
14423         bxe_dma_free(sc, &sc->eq_dma);
14424         sc->eq = NULL;
14425         bxe_dma_free(sc, &sc->def_sb_dma);
14426         sc->def_sb = NULL;
14427         bus_dma_tag_destroy(sc->parent_dma_tag);
14428         return (1);
14429     }
14430 
14431     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14432 
14433     /*******************/
14434     /* SLOW PATH QUEUE */
14435     /*******************/
14436 
14437     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14438                       &sc->spq_dma, "slow path queue") != 0) {
14439         /* XXX */
14440         bxe_dma_free(sc, &sc->sp_dma);
14441         sc->sp = NULL;
14442         bxe_dma_free(sc, &sc->eq_dma);
14443         sc->eq = NULL;
14444         bxe_dma_free(sc, &sc->def_sb_dma);
14445         sc->def_sb = NULL;
14446         bus_dma_tag_destroy(sc->parent_dma_tag);
14447         return (1);
14448     }
14449 
14450     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14451 
14452     /***************************/
14453     /* FW DECOMPRESSION BUFFER */
14454     /***************************/
14455 
14456     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14457                       "fw decompression buffer") != 0) {
14458         /* XXX */
14459         bxe_dma_free(sc, &sc->spq_dma);
14460         sc->spq = NULL;
14461         bxe_dma_free(sc, &sc->sp_dma);
14462         sc->sp = NULL;
14463         bxe_dma_free(sc, &sc->eq_dma);
14464         sc->eq = NULL;
14465         bxe_dma_free(sc, &sc->def_sb_dma);
14466         sc->def_sb = NULL;
14467         bus_dma_tag_destroy(sc->parent_dma_tag);
14468         return (1);
14469     }
14470 
14471     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14472 
14473     if ((sc->gz_strm =
14474          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14475         /* XXX */
14476         bxe_dma_free(sc, &sc->gz_buf_dma);
14477         sc->gz_buf = NULL;
14478         bxe_dma_free(sc, &sc->spq_dma);
14479         sc->spq = NULL;
14480         bxe_dma_free(sc, &sc->sp_dma);
14481         sc->sp = NULL;
14482         bxe_dma_free(sc, &sc->eq_dma);
14483         sc->eq = NULL;
14484         bxe_dma_free(sc, &sc->def_sb_dma);
14485         sc->def_sb = NULL;
14486         bus_dma_tag_destroy(sc->parent_dma_tag);
14487         return (1);
14488     }
14489 
14490     /*************/
14491     /* FASTPATHS */
14492     /*************/
14493 
14494     /* allocate DMA memory for each fastpath structure */
14495     for (i = 0; i < sc->num_queues; i++) {
14496         fp = &sc->fp[i];
14497         fp->sc    = sc;
14498         fp->index = i;
14499 
14500         /*******************/
14501         /* FP STATUS BLOCK */
14502         /*******************/
14503 
14504         snprintf(buf, sizeof(buf), "fp %d status block", i);
14505         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14506                           &fp->sb_dma, buf) != 0) {
14507             /* XXX unwind and free previous fastpath allocations */
14508             BLOGE(sc, "Failed to alloc %s\n", buf);
14509             return (1);
14510         } else {
14511             if (CHIP_IS_E2E3(sc)) {
14512                 fp->status_block.e2_sb =
14513                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14514             } else {
14515                 fp->status_block.e1x_sb =
14516                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14517             }
14518         }
14519 
14520         /******************/
14521         /* FP TX BD CHAIN */
14522         /******************/
14523 
14524         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14525         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14526                           &fp->tx_dma, buf) != 0) {
14527             /* XXX unwind and free previous fastpath allocations */
14528             BLOGE(sc, "Failed to alloc %s\n", buf);
14529             return (1);
14530         } else {
14531             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14532         }
14533 
14534         /* link together the tx bd chain pages */
14535         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14536             /* index into the tx bd chain array to last entry per page */
14537             struct eth_tx_next_bd *tx_next_bd =
14538                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14539             /* point to the next page and wrap from last page */
14540             busaddr = (fp->tx_dma.paddr +
14541                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14542             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14543             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14544         }
14545 
14546         /******************/
14547         /* FP RX BD CHAIN */
14548         /******************/
14549 
14550         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14551         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14552                           &fp->rx_dma, buf) != 0) {
14553             /* XXX unwind and free previous fastpath allocations */
14554             BLOGE(sc, "Failed to alloc %s\n", buf);
14555             return (1);
14556         } else {
14557             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14558         }
14559 
14560         /* link together the rx bd chain pages */
14561         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14562             /* index into the rx bd chain array to last entry per page */
14563             struct eth_rx_bd *rx_bd =
14564                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14565             /* point to the next page and wrap from last page */
14566             busaddr = (fp->rx_dma.paddr +
14567                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14568             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14569             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14570         }
14571 
14572         /*******************/
14573         /* FP RX RCQ CHAIN */
14574         /*******************/
14575 
14576         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14577         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14578                           &fp->rcq_dma, buf) != 0) {
14579             /* XXX unwind and free previous fastpath allocations */
14580             BLOGE(sc, "Failed to alloc %s\n", buf);
14581             return (1);
14582         } else {
14583             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14584         }
14585 
14586         /* link together the rcq chain pages */
14587         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14588             /* index into the rcq chain array to last entry per page */
14589             struct eth_rx_cqe_next_page *rx_cqe_next =
14590                 (struct eth_rx_cqe_next_page *)
14591                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14592             /* point to the next page and wrap from last page */
14593             busaddr = (fp->rcq_dma.paddr +
14594                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14595             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14596             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14597         }
14598 
14599         /*******************/
14600         /* FP RX SGE CHAIN */
14601         /*******************/
14602 
14603         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14604         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14605                           &fp->rx_sge_dma, buf) != 0) {
14606             /* XXX unwind and free previous fastpath allocations */
14607             BLOGE(sc, "Failed to alloc %s\n", buf);
14608             return (1);
14609         } else {
14610             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14611         }
14612 
14613         /* link together the sge chain pages */
14614         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14615             /* index into the rcq chain array to last entry per page */
14616             struct eth_rx_sge *rx_sge =
14617                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14618             /* point to the next page and wrap from last page */
14619             busaddr = (fp->rx_sge_dma.paddr +
14620                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14621             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14622             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14623         }
14624 
14625         /***********************/
14626         /* FP TX MBUF DMA MAPS */
14627         /***********************/
14628 
14629         /* set required sizes before mapping to conserve resources */
14630         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14631             max_size     = BXE_TSO_MAX_SIZE;
14632             max_segments = BXE_TSO_MAX_SEGMENTS;
14633             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14634         } else {
14635             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14636             max_segments = BXE_MAX_SEGMENTS;
14637             max_seg_size = MCLBYTES;
14638         }
14639 
14640         /* create a dma tag for the tx mbufs */
14641         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14642                                 1,                  /* alignment */
14643                                 0,                  /* boundary limit */
14644                                 BUS_SPACE_MAXADDR,  /* restricted low */
14645                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14646                                 NULL,               /* addr filter() */
14647                                 NULL,               /* addr filter() arg */
14648                                 max_size,           /* max map size */
14649                                 max_segments,       /* num discontinuous */
14650                                 max_seg_size,       /* max seg size */
14651                                 0,                  /* flags */
14652                                 NULL,               /* lock() */
14653                                 NULL,               /* lock() arg */
14654                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14655         if (rc != 0) {
14656             /* XXX unwind and free previous fastpath allocations */
14657             BLOGE(sc, "Failed to create dma tag for "
14658                       "'fp %d tx mbufs' (%d)\n", i, rc);
14659             return (1);
14660         }
14661 
14662         /* create dma maps for each of the tx mbuf clusters */
14663         for (j = 0; j < TX_BD_TOTAL; j++) {
14664             if (bus_dmamap_create(fp->tx_mbuf_tag,
14665                                   BUS_DMA_NOWAIT,
14666                                   &fp->tx_mbuf_chain[j].m_map)) {
14667                 /* XXX unwind and free previous fastpath allocations */
14668                 BLOGE(sc, "Failed to create dma map for "
14669                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14670                 return (1);
14671             }
14672         }
14673 
14674         /***********************/
14675         /* FP RX MBUF DMA MAPS */
14676         /***********************/
14677 
14678         /* create a dma tag for the rx mbufs */
14679         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14680                                 1,                  /* alignment */
14681                                 0,                  /* boundary limit */
14682                                 BUS_SPACE_MAXADDR,  /* restricted low */
14683                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14684                                 NULL,               /* addr filter() */
14685                                 NULL,               /* addr filter() arg */
14686                                 MJUM9BYTES,         /* max map size */
14687                                 1,                  /* num discontinuous */
14688                                 MJUM9BYTES,         /* max seg size */
14689                                 0,                  /* flags */
14690                                 NULL,               /* lock() */
14691                                 NULL,               /* lock() arg */
14692                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14693         if (rc != 0) {
14694             /* XXX unwind and free previous fastpath allocations */
14695             BLOGE(sc, "Failed to create dma tag for "
14696                       "'fp %d rx mbufs' (%d)\n", i, rc);
14697             return (1);
14698         }
14699 
14700         /* create dma maps for each of the rx mbuf clusters */
14701         for (j = 0; j < RX_BD_TOTAL; j++) {
14702             if (bus_dmamap_create(fp->rx_mbuf_tag,
14703                                   BUS_DMA_NOWAIT,
14704                                   &fp->rx_mbuf_chain[j].m_map)) {
14705                 /* XXX unwind and free previous fastpath allocations */
14706                 BLOGE(sc, "Failed to create dma map for "
14707                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14708                 return (1);
14709             }
14710         }
14711 
14712         /* create dma map for the spare rx mbuf cluster */
14713         if (bus_dmamap_create(fp->rx_mbuf_tag,
14714                               BUS_DMA_NOWAIT,
14715                               &fp->rx_mbuf_spare_map)) {
14716             /* XXX unwind and free previous fastpath allocations */
14717             BLOGE(sc, "Failed to create dma map for "
14718                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14719             return (1);
14720         }
14721 
14722         /***************************/
14723         /* FP RX SGE MBUF DMA MAPS */
14724         /***************************/
14725 
14726         /* create a dma tag for the rx sge mbufs */
14727         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14728                                 1,                  /* alignment */
14729                                 0,                  /* boundary limit */
14730                                 BUS_SPACE_MAXADDR,  /* restricted low */
14731                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14732                                 NULL,               /* addr filter() */
14733                                 NULL,               /* addr filter() arg */
14734                                 BCM_PAGE_SIZE,      /* max map size */
14735                                 1,                  /* num discontinuous */
14736                                 BCM_PAGE_SIZE,      /* max seg size */
14737                                 0,                  /* flags */
14738                                 NULL,               /* lock() */
14739                                 NULL,               /* lock() arg */
14740                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14741         if (rc != 0) {
14742             /* XXX unwind and free previous fastpath allocations */
14743             BLOGE(sc, "Failed to create dma tag for "
14744                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14745             return (1);
14746         }
14747 
14748         /* create dma maps for the rx sge mbuf clusters */
14749         for (j = 0; j < RX_SGE_TOTAL; j++) {
14750             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14751                                   BUS_DMA_NOWAIT,
14752                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14753                 /* XXX unwind and free previous fastpath allocations */
14754                 BLOGE(sc, "Failed to create dma map for "
14755                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14756                 return (1);
14757             }
14758         }
14759 
14760         /* create dma map for the spare rx sge mbuf cluster */
14761         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14762                               BUS_DMA_NOWAIT,
14763                               &fp->rx_sge_mbuf_spare_map)) {
14764             /* XXX unwind and free previous fastpath allocations */
14765             BLOGE(sc, "Failed to create dma map for "
14766                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14767             return (1);
14768         }
14769 
14770         /***************************/
14771         /* FP RX TPA MBUF DMA MAPS */
14772         /***************************/
14773 
14774         /* create dma maps for the rx tpa mbuf clusters */
14775         max_agg_queues = MAX_AGG_QS(sc);
14776 
14777         for (j = 0; j < max_agg_queues; j++) {
14778             if (bus_dmamap_create(fp->rx_mbuf_tag,
14779                                   BUS_DMA_NOWAIT,
14780                                   &fp->rx_tpa_info[j].bd.m_map)) {
14781                 /* XXX unwind and free previous fastpath allocations */
14782                 BLOGE(sc, "Failed to create dma map for "
14783                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14784                 return (1);
14785             }
14786         }
14787 
14788         /* create dma map for the spare rx tpa mbuf cluster */
14789         if (bus_dmamap_create(fp->rx_mbuf_tag,
14790                               BUS_DMA_NOWAIT,
14791                               &fp->rx_tpa_info_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 tpa mbuf' (%d)\n", i, rc);
14795             return (1);
14796         }
14797 
14798         bxe_init_sge_ring_bit_mask(fp);
14799     }
14800 
14801     return (0);
14802 }
14803 
14804 static void
14805 bxe_free_hsi_mem(struct bxe_softc *sc)
14806 {
14807     struct bxe_fastpath *fp;
14808     int max_agg_queues;
14809     int i, j;
14810 
14811     if (sc->parent_dma_tag == NULL) {
14812         return; /* assume nothing was allocated */
14813     }
14814 
14815     for (i = 0; i < sc->num_queues; i++) {
14816         fp = &sc->fp[i];
14817 
14818         /*******************/
14819         /* FP STATUS BLOCK */
14820         /*******************/
14821 
14822         bxe_dma_free(sc, &fp->sb_dma);
14823         memset(&fp->status_block, 0, sizeof(fp->status_block));
14824 
14825         /******************/
14826         /* FP TX BD CHAIN */
14827         /******************/
14828 
14829         bxe_dma_free(sc, &fp->tx_dma);
14830         fp->tx_chain = NULL;
14831 
14832         /******************/
14833         /* FP RX BD CHAIN */
14834         /******************/
14835 
14836         bxe_dma_free(sc, &fp->rx_dma);
14837         fp->rx_chain = NULL;
14838 
14839         /*******************/
14840         /* FP RX RCQ CHAIN */
14841         /*******************/
14842 
14843         bxe_dma_free(sc, &fp->rcq_dma);
14844         fp->rcq_chain = NULL;
14845 
14846         /*******************/
14847         /* FP RX SGE CHAIN */
14848         /*******************/
14849 
14850         bxe_dma_free(sc, &fp->rx_sge_dma);
14851         fp->rx_sge_chain = NULL;
14852 
14853         /***********************/
14854         /* FP TX MBUF DMA MAPS */
14855         /***********************/
14856 
14857         if (fp->tx_mbuf_tag != NULL) {
14858             for (j = 0; j < TX_BD_TOTAL; j++) {
14859                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14860                     bus_dmamap_unload(fp->tx_mbuf_tag,
14861                                       fp->tx_mbuf_chain[j].m_map);
14862                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14863                                        fp->tx_mbuf_chain[j].m_map);
14864                 }
14865             }
14866 
14867             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14868             fp->tx_mbuf_tag = NULL;
14869         }
14870 
14871         /***********************/
14872         /* FP RX MBUF DMA MAPS */
14873         /***********************/
14874 
14875         if (fp->rx_mbuf_tag != NULL) {
14876             for (j = 0; j < RX_BD_TOTAL; j++) {
14877                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14878                     bus_dmamap_unload(fp->rx_mbuf_tag,
14879                                       fp->rx_mbuf_chain[j].m_map);
14880                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14881                                        fp->rx_mbuf_chain[j].m_map);
14882                 }
14883             }
14884 
14885             if (fp->rx_mbuf_spare_map != NULL) {
14886                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14887                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14888             }
14889 
14890             /***************************/
14891             /* FP RX TPA MBUF DMA MAPS */
14892             /***************************/
14893 
14894             max_agg_queues = MAX_AGG_QS(sc);
14895 
14896             for (j = 0; j < max_agg_queues; j++) {
14897                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14898                     bus_dmamap_unload(fp->rx_mbuf_tag,
14899                                       fp->rx_tpa_info[j].bd.m_map);
14900                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14901                                        fp->rx_tpa_info[j].bd.m_map);
14902                 }
14903             }
14904 
14905             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14906                 bus_dmamap_unload(fp->rx_mbuf_tag,
14907                                   fp->rx_tpa_info_mbuf_spare_map);
14908                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14909                                    fp->rx_tpa_info_mbuf_spare_map);
14910             }
14911 
14912             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14913             fp->rx_mbuf_tag = NULL;
14914         }
14915 
14916         /***************************/
14917         /* FP RX SGE MBUF DMA MAPS */
14918         /***************************/
14919 
14920         if (fp->rx_sge_mbuf_tag != NULL) {
14921             for (j = 0; j < RX_SGE_TOTAL; j++) {
14922                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14923                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14924                                       fp->rx_sge_mbuf_chain[j].m_map);
14925                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14926                                        fp->rx_sge_mbuf_chain[j].m_map);
14927                 }
14928             }
14929 
14930             if (fp->rx_sge_mbuf_spare_map != NULL) {
14931                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14932                                   fp->rx_sge_mbuf_spare_map);
14933                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14934                                    fp->rx_sge_mbuf_spare_map);
14935             }
14936 
14937             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14938             fp->rx_sge_mbuf_tag = NULL;
14939         }
14940     }
14941 
14942     /***************************/
14943     /* FW DECOMPRESSION BUFFER */
14944     /***************************/
14945 
14946     bxe_dma_free(sc, &sc->gz_buf_dma);
14947     sc->gz_buf = NULL;
14948     free(sc->gz_strm, M_DEVBUF);
14949     sc->gz_strm = NULL;
14950 
14951     /*******************/
14952     /* SLOW PATH QUEUE */
14953     /*******************/
14954 
14955     bxe_dma_free(sc, &sc->spq_dma);
14956     sc->spq = NULL;
14957 
14958     /*************/
14959     /* SLOW PATH */
14960     /*************/
14961 
14962     bxe_dma_free(sc, &sc->sp_dma);
14963     sc->sp = NULL;
14964 
14965     /***************/
14966     /* EVENT QUEUE */
14967     /***************/
14968 
14969     bxe_dma_free(sc, &sc->eq_dma);
14970     sc->eq = NULL;
14971 
14972     /************************/
14973     /* DEFAULT STATUS BLOCK */
14974     /************************/
14975 
14976     bxe_dma_free(sc, &sc->def_sb_dma);
14977     sc->def_sb = NULL;
14978 
14979     bus_dma_tag_destroy(sc->parent_dma_tag);
14980     sc->parent_dma_tag = NULL;
14981 }
14982 
14983 /*
14984  * Previous driver DMAE transaction may have occurred when pre-boot stage
14985  * ended and boot began. This would invalidate the addresses of the
14986  * transaction, resulting in was-error bit set in the PCI causing all
14987  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
14988  * the interrupt which detected this from the pglueb and the was-done bit
14989  */
14990 static void
14991 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
14992 {
14993     uint32_t val;
14994 
14995     if (!CHIP_IS_E1x(sc)) {
14996         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
14997         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
14998             BLOGD(sc, DBG_LOAD,
14999                   "Clearing 'was-error' bit that was set in pglueb");
15000             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15001         }
15002     }
15003 }
15004 
15005 static int
15006 bxe_prev_mcp_done(struct bxe_softc *sc)
15007 {
15008     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15009                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15010     if (!rc) {
15011         BLOGE(sc, "MCP response failure, aborting\n");
15012         return (-1);
15013     }
15014 
15015     return (0);
15016 }
15017 
15018 static struct bxe_prev_list_node *
15019 bxe_prev_path_get_entry(struct bxe_softc *sc)
15020 {
15021     struct bxe_prev_list_node *tmp;
15022 
15023     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15024         if ((sc->pcie_bus == tmp->bus) &&
15025             (sc->pcie_device == tmp->slot) &&
15026             (SC_PATH(sc) == tmp->path)) {
15027             return (tmp);
15028         }
15029     }
15030 
15031     return (NULL);
15032 }
15033 
15034 static uint8_t
15035 bxe_prev_is_path_marked(struct bxe_softc *sc)
15036 {
15037     struct bxe_prev_list_node *tmp;
15038     int rc = FALSE;
15039 
15040     mtx_lock(&bxe_prev_mtx);
15041 
15042     tmp = bxe_prev_path_get_entry(sc);
15043     if (tmp) {
15044         if (tmp->aer) {
15045             BLOGD(sc, DBG_LOAD,
15046                   "Path %d/%d/%d was marked by AER\n",
15047                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15048         } else {
15049             rc = TRUE;
15050             BLOGD(sc, DBG_LOAD,
15051                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15052                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15053         }
15054     }
15055 
15056     mtx_unlock(&bxe_prev_mtx);
15057 
15058     return (rc);
15059 }
15060 
15061 static int
15062 bxe_prev_mark_path(struct bxe_softc *sc,
15063                    uint8_t          after_undi)
15064 {
15065     struct bxe_prev_list_node *tmp;
15066 
15067     mtx_lock(&bxe_prev_mtx);
15068 
15069     /* Check whether the entry for this path already exists */
15070     tmp = bxe_prev_path_get_entry(sc);
15071     if (tmp) {
15072         if (!tmp->aer) {
15073             BLOGD(sc, DBG_LOAD,
15074                   "Re-marking AER in path %d/%d/%d\n",
15075                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15076         } else {
15077             BLOGD(sc, DBG_LOAD,
15078                   "Removing AER indication from path %d/%d/%d\n",
15079                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15080             tmp->aer = 0;
15081         }
15082 
15083         mtx_unlock(&bxe_prev_mtx);
15084         return (0);
15085     }
15086 
15087     mtx_unlock(&bxe_prev_mtx);
15088 
15089     /* Create an entry for this path and add it */
15090     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15091                  (M_NOWAIT | M_ZERO));
15092     if (!tmp) {
15093         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15094         return (-1);
15095     }
15096 
15097     tmp->bus  = sc->pcie_bus;
15098     tmp->slot = sc->pcie_device;
15099     tmp->path = SC_PATH(sc);
15100     tmp->aer  = 0;
15101     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15102 
15103     mtx_lock(&bxe_prev_mtx);
15104 
15105     BLOGD(sc, DBG_LOAD,
15106           "Marked path %d/%d/%d - finished previous unload\n",
15107           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15108     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15109 
15110     mtx_unlock(&bxe_prev_mtx);
15111 
15112     return (0);
15113 }
15114 
15115 static int
15116 bxe_do_flr(struct bxe_softc *sc)
15117 {
15118     int i;
15119 
15120     /* only E2 and onwards support FLR */
15121     if (CHIP_IS_E1x(sc)) {
15122         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15123         return (-1);
15124     }
15125 
15126     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15127     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15128         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15129               sc->devinfo.bc_ver);
15130         return (-1);
15131     }
15132 
15133     /* Wait for Transaction Pending bit clean */
15134     for (i = 0; i < 4; i++) {
15135         if (i) {
15136             DELAY(((1 << (i - 1)) * 100) * 1000);
15137         }
15138 
15139         if (!bxe_is_pcie_pending(sc)) {
15140             goto clear;
15141         }
15142     }
15143 
15144     BLOGE(sc, "PCIE transaction is not cleared, "
15145               "proceeding with reset anyway\n");
15146 
15147 clear:
15148 
15149     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15150     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15151 
15152     return (0);
15153 }
15154 
15155 struct bxe_mac_vals {
15156     uint32_t xmac_addr;
15157     uint32_t xmac_val;
15158     uint32_t emac_addr;
15159     uint32_t emac_val;
15160     uint32_t umac_addr;
15161     uint32_t umac_val;
15162     uint32_t bmac_addr;
15163     uint32_t bmac_val[2];
15164 };
15165 
15166 static void
15167 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15168                           struct bxe_mac_vals *vals)
15169 {
15170     uint32_t val, base_addr, offset, mask, reset_reg;
15171     uint8_t mac_stopped = FALSE;
15172     uint8_t port = SC_PORT(sc);
15173     uint32_t wb_data[2];
15174 
15175     /* reset addresses as they also mark which values were changed */
15176     vals->bmac_addr = 0;
15177     vals->umac_addr = 0;
15178     vals->xmac_addr = 0;
15179     vals->emac_addr = 0;
15180 
15181     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15182 
15183     if (!CHIP_IS_E3(sc)) {
15184         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15185         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15186         if ((mask & reset_reg) && val) {
15187             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15188             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15189                                     : NIG_REG_INGRESS_BMAC0_MEM;
15190             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15191                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15192 
15193             /*
15194              * use rd/wr since we cannot use dmae. This is safe
15195              * since MCP won't access the bus due to the request
15196              * to unload, and no function on the path can be
15197              * loaded at this time.
15198              */
15199             wb_data[0] = REG_RD(sc, base_addr + offset);
15200             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15201             vals->bmac_addr = base_addr + offset;
15202             vals->bmac_val[0] = wb_data[0];
15203             vals->bmac_val[1] = wb_data[1];
15204             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15205             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15206             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15207         }
15208 
15209         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15210         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15211         vals->emac_val = REG_RD(sc, vals->emac_addr);
15212         REG_WR(sc, vals->emac_addr, 0);
15213         mac_stopped = TRUE;
15214     } else {
15215         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15216             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15217             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15218             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15219             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15220             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15221             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15222             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15223             REG_WR(sc, vals->xmac_addr, 0);
15224             mac_stopped = TRUE;
15225         }
15226 
15227         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15228         if (mask & reset_reg) {
15229             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15230             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15231             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15232             vals->umac_val = REG_RD(sc, vals->umac_addr);
15233             REG_WR(sc, vals->umac_addr, 0);
15234             mac_stopped = TRUE;
15235         }
15236     }
15237 
15238     if (mac_stopped) {
15239         DELAY(20000);
15240     }
15241 }
15242 
15243 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15244 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15245 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15246 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15247 
15248 static void
15249 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15250                          uint8_t          port,
15251                          uint8_t          inc)
15252 {
15253     uint16_t rcq, bd;
15254     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15255 
15256     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15257     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15258 
15259     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15260     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15261 
15262     BLOGD(sc, DBG_LOAD,
15263           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15264           port, bd, rcq);
15265 }
15266 
15267 static int
15268 bxe_prev_unload_common(struct bxe_softc *sc)
15269 {
15270     uint32_t reset_reg, tmp_reg = 0, rc;
15271     uint8_t prev_undi = FALSE;
15272     struct bxe_mac_vals mac_vals;
15273     uint32_t timer_count = 1000;
15274     uint32_t prev_brb;
15275 
15276     /*
15277      * It is possible a previous function received 'common' answer,
15278      * but hasn't loaded yet, therefore creating a scenario of
15279      * multiple functions receiving 'common' on the same path.
15280      */
15281     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15282 
15283     memset(&mac_vals, 0, sizeof(mac_vals));
15284 
15285     if (bxe_prev_is_path_marked(sc)) {
15286         return (bxe_prev_mcp_done(sc));
15287     }
15288 
15289     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15290 
15291     /* Reset should be performed after BRB is emptied */
15292     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15293         /* Close the MAC Rx to prevent BRB from filling up */
15294         bxe_prev_unload_close_mac(sc, &mac_vals);
15295 
15296         /* close LLH filters towards the BRB */
15297         elink_set_rx_filter(&sc->link_params, 0);
15298 
15299         /*
15300          * Check if the UNDI driver was previously loaded.
15301          * UNDI driver initializes CID offset for normal bell to 0x7
15302          */
15303         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15304             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15305             if (tmp_reg == 0x7) {
15306                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15307                 prev_undi = TRUE;
15308                 /* clear the UNDI indication */
15309                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15310                 /* clear possible idle check errors */
15311                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15312             }
15313         }
15314 
15315         /* wait until BRB is empty */
15316         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15317         while (timer_count) {
15318             prev_brb = tmp_reg;
15319 
15320             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15321             if (!tmp_reg) {
15322                 break;
15323             }
15324 
15325             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15326 
15327             /* reset timer as long as BRB actually gets emptied */
15328             if (prev_brb > tmp_reg) {
15329                 timer_count = 1000;
15330             } else {
15331                 timer_count--;
15332             }
15333 
15334             /* If UNDI resides in memory, manually increment it */
15335             if (prev_undi) {
15336                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15337             }
15338 
15339             DELAY(10);
15340         }
15341 
15342         if (!timer_count) {
15343             BLOGE(sc, "Failed to empty BRB\n");
15344         }
15345     }
15346 
15347     /* No packets are in the pipeline, path is ready for reset */
15348     bxe_reset_common(sc);
15349 
15350     if (mac_vals.xmac_addr) {
15351         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15352     }
15353     if (mac_vals.umac_addr) {
15354         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15355     }
15356     if (mac_vals.emac_addr) {
15357         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15358     }
15359     if (mac_vals.bmac_addr) {
15360         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15361         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15362     }
15363 
15364     rc = bxe_prev_mark_path(sc, prev_undi);
15365     if (rc) {
15366         bxe_prev_mcp_done(sc);
15367         return (rc);
15368     }
15369 
15370     return (bxe_prev_mcp_done(sc));
15371 }
15372 
15373 static int
15374 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15375 {
15376     int rc;
15377 
15378     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15379 
15380     /* Test if previous unload process was already finished for this path */
15381     if (bxe_prev_is_path_marked(sc)) {
15382         return (bxe_prev_mcp_done(sc));
15383     }
15384 
15385     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15386 
15387     /*
15388      * If function has FLR capabilities, and existing FW version matches
15389      * the one required, then FLR will be sufficient to clean any residue
15390      * left by previous driver
15391      */
15392     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15393     if (!rc) {
15394         /* fw version is good */
15395         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15396         rc = bxe_do_flr(sc);
15397     }
15398 
15399     if (!rc) {
15400         /* FLR was performed */
15401         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15402         return (0);
15403     }
15404 
15405     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15406 
15407     /* Close the MCP request, return failure*/
15408     rc = bxe_prev_mcp_done(sc);
15409     if (!rc) {
15410         rc = BXE_PREV_WAIT_NEEDED;
15411     }
15412 
15413     return (rc);
15414 }
15415 
15416 static int
15417 bxe_prev_unload(struct bxe_softc *sc)
15418 {
15419     int time_counter = 10;
15420     uint32_t fw, hw_lock_reg, hw_lock_val;
15421     uint32_t rc = 0;
15422 
15423     /*
15424      * Clear HW from errors which may have resulted from an interrupted
15425      * DMAE transaction.
15426      */
15427     bxe_prev_interrupted_dmae(sc);
15428 
15429     /* Release previously held locks */
15430     hw_lock_reg =
15431         (SC_FUNC(sc) <= 5) ?
15432             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15433             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15434 
15435     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15436     if (hw_lock_val) {
15437         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15438             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15439             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15440                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15441         }
15442         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15443         REG_WR(sc, hw_lock_reg, 0xffffffff);
15444     } else {
15445         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15446     }
15447 
15448     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15449         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15450         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15451     }
15452 
15453     do {
15454         /* Lock MCP using an unload request */
15455         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15456         if (!fw) {
15457             BLOGE(sc, "MCP response failure, aborting\n");
15458             rc = -1;
15459             break;
15460         }
15461 
15462         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15463             rc = bxe_prev_unload_common(sc);
15464             break;
15465         }
15466 
15467         /* non-common reply from MCP night require looping */
15468         rc = bxe_prev_unload_uncommon(sc);
15469         if (rc != BXE_PREV_WAIT_NEEDED) {
15470             break;
15471         }
15472 
15473         DELAY(20000);
15474     } while (--time_counter);
15475 
15476     if (!time_counter || rc) {
15477         BLOGE(sc, "Failed to unload previous driver!"
15478             " time_counter %d rc %d\n", time_counter, rc);
15479         rc = -1;
15480     }
15481 
15482     return (rc);
15483 }
15484 
15485 void
15486 bxe_dcbx_set_state(struct bxe_softc *sc,
15487                    uint8_t          dcb_on,
15488                    uint32_t         dcbx_enabled)
15489 {
15490     if (!CHIP_IS_E1x(sc)) {
15491         sc->dcb_state = dcb_on;
15492         sc->dcbx_enabled = dcbx_enabled;
15493     } else {
15494         sc->dcb_state = FALSE;
15495         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15496     }
15497     BLOGD(sc, DBG_LOAD,
15498           "DCB state [%s:%s]\n",
15499           dcb_on ? "ON" : "OFF",
15500           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15501           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15502           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15503           "on-chip with negotiation" : "invalid");
15504 }
15505 
15506 /* must be called after sriov-enable */
15507 static int
15508 bxe_set_qm_cid_count(struct bxe_softc *sc)
15509 {
15510     int cid_count = BXE_L2_MAX_CID(sc);
15511 
15512     if (IS_SRIOV(sc)) {
15513         cid_count += BXE_VF_CIDS;
15514     }
15515 
15516     if (CNIC_SUPPORT(sc)) {
15517         cid_count += CNIC_CID_MAX;
15518     }
15519 
15520     return (roundup(cid_count, QM_CID_ROUND));
15521 }
15522 
15523 static void
15524 bxe_init_multi_cos(struct bxe_softc *sc)
15525 {
15526     int pri, cos;
15527 
15528     uint32_t pri_map = 0; /* XXX change to user config */
15529 
15530     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15531         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15532         if (cos < sc->max_cos) {
15533             sc->prio_to_cos[pri] = cos;
15534         } else {
15535             BLOGW(sc, "Invalid COS %d for priority %d "
15536                       "(max COS is %d), setting to 0\n",
15537                   cos, pri, (sc->max_cos - 1));
15538             sc->prio_to_cos[pri] = 0;
15539         }
15540     }
15541 }
15542 
15543 static int
15544 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15545 {
15546     struct bxe_softc *sc;
15547     int error, result;
15548 
15549     result = 0;
15550     error = sysctl_handle_int(oidp, &result, 0, req);
15551 
15552     if (error || !req->newptr) {
15553         return (error);
15554     }
15555 
15556     if (result == 1) {
15557         uint32_t  temp;
15558         sc = (struct bxe_softc *)arg1;
15559 
15560         BLOGI(sc, "... dumping driver state ...\n");
15561         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15562         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15563     }
15564 
15565     return (error);
15566 }
15567 
15568 static int
15569 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15570 {
15571     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15572     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15573     uint32_t *offset;
15574     uint64_t value = 0;
15575     int index = (int)arg2;
15576 
15577     if (index >= BXE_NUM_ETH_STATS) {
15578         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15579         return (-1);
15580     }
15581 
15582     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15583 
15584     switch (bxe_eth_stats_arr[index].size) {
15585     case 4:
15586         value = (uint64_t)*offset;
15587         break;
15588     case 8:
15589         value = HILO_U64(*offset, *(offset + 1));
15590         break;
15591     default:
15592         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15593               index, bxe_eth_stats_arr[index].size);
15594         return (-1);
15595     }
15596 
15597     return (sysctl_handle_64(oidp, &value, 0, req));
15598 }
15599 
15600 static int
15601 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15602 {
15603     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15604     uint32_t *eth_stats;
15605     uint32_t *offset;
15606     uint64_t value = 0;
15607     uint32_t q_stat = (uint32_t)arg2;
15608     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15609     uint32_t index = (q_stat & 0xffff);
15610 
15611     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15612 
15613     if (index >= BXE_NUM_ETH_Q_STATS) {
15614         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15615         return (-1);
15616     }
15617 
15618     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15619 
15620     switch (bxe_eth_q_stats_arr[index].size) {
15621     case 4:
15622         value = (uint64_t)*offset;
15623         break;
15624     case 8:
15625         value = HILO_U64(*offset, *(offset + 1));
15626         break;
15627     default:
15628         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15629               index, bxe_eth_q_stats_arr[index].size);
15630         return (-1);
15631     }
15632 
15633     return (sysctl_handle_64(oidp, &value, 0, req));
15634 }
15635 
15636 static void bxe_force_link_reset(struct bxe_softc *sc)
15637 {
15638 
15639         bxe_acquire_phy_lock(sc);
15640         elink_link_reset(&sc->link_params, &sc->link_vars, 1);
15641         bxe_release_phy_lock(sc);
15642 }
15643 
15644 static int
15645 bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
15646 {
15647         struct bxe_softc *sc = (struct bxe_softc *)arg1;;
15648         uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
15649         int rc = 0;
15650         int error;
15651         int result;
15652 
15653 
15654         error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
15655 
15656         if (error || !req->newptr) {
15657                 return (error);
15658         }
15659         if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
15660                 BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
15661                 sc->bxe_pause_param = 8;
15662         }
15663 
15664         result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
15665 
15666 
15667         if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
15668                         BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
15669                         return -EINVAL;
15670         }
15671 
15672         if(IS_MF(sc))
15673                 return 0;
15674        sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
15675         if(result & ELINK_FLOW_CTRL_RX)
15676                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
15677 
15678         if(result & ELINK_FLOW_CTRL_TX)
15679                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
15680         if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
15681                 sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
15682 
15683         if(result & 0x400) {
15684                 if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
15685                         sc->link_params.req_flow_ctrl[cfg_idx] =
15686                                 ELINK_FLOW_CTRL_AUTO;
15687                 }
15688                 sc->link_params.req_fc_auto_adv = 0;
15689                 if (result & ELINK_FLOW_CTRL_RX)
15690                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
15691 
15692                 if (result & ELINK_FLOW_CTRL_TX)
15693                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
15694                 if (!sc->link_params.req_fc_auto_adv)
15695                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
15696         }
15697          if (IS_PF(sc)) {
15698                         if (sc->link_vars.link_up) {
15699                                 bxe_stats_handle(sc, STATS_EVENT_STOP);
15700                         }
15701 			if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
15702                         bxe_force_link_reset(sc);
15703                         bxe_acquire_phy_lock(sc);
15704 
15705                         rc = elink_phy_init(&sc->link_params, &sc->link_vars);
15706 
15707                         bxe_release_phy_lock(sc);
15708 
15709                         bxe_calc_fc_adv(sc);
15710                         }
15711         }
15712         return rc;
15713 }
15714 
15715 
15716 static void
15717 bxe_add_sysctls(struct bxe_softc *sc)
15718 {
15719     struct sysctl_ctx_list *ctx;
15720     struct sysctl_oid_list *children;
15721     struct sysctl_oid *queue_top, *queue;
15722     struct sysctl_oid_list *queue_top_children, *queue_children;
15723     char queue_num_buf[32];
15724     uint32_t q_stat;
15725     int i, j;
15726 
15727     ctx = device_get_sysctl_ctx(sc->dev);
15728     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15729 
15730     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15731                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15732                       "version");
15733 
15734     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15735              BCM_5710_FW_MAJOR_VERSION,
15736              BCM_5710_FW_MINOR_VERSION,
15737              BCM_5710_FW_REVISION_VERSION,
15738              BCM_5710_FW_ENGINEERING_VERSION);
15739 
15740     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15741         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15742          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15743          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15744          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15745                                                                 "Unknown"));
15746     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15747                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15748                     "multifunction vnics per port");
15749 
15750     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15751         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15752          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15753          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15754                                               "???GT/s"),
15755         sc->devinfo.pcie_link_width);
15756 
15757     sc->debug = bxe_debug;
15758 
15759 #if __FreeBSD_version >= 900000
15760     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15761                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15762                       "bootcode version");
15763     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15764                       CTLFLAG_RD, sc->fw_ver_str, 0,
15765                       "firmware version");
15766     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15767                       CTLFLAG_RD, sc->mf_mode_str, 0,
15768                       "multifunction mode");
15769     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15770                       CTLFLAG_RD, sc->mac_addr_str, 0,
15771                       "mac address");
15772     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15773                       CTLFLAG_RD, sc->pci_link_str, 0,
15774                       "pci link status");
15775     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15776                     CTLFLAG_RW, &sc->debug,
15777                     "debug logging mode");
15778 #else
15779     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15780                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15781                       "bootcode version");
15782     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15783                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15784                       "firmware version");
15785     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15786                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15787                       "multifunction mode");
15788     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15789                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15790                       "mac address");
15791     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15792                       CTLFLAG_RD, &sc->pci_link_str, 0,
15793                       "pci link status");
15794     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15795                     CTLFLAG_RW, &sc->debug, 0,
15796                     "debug logging mode");
15797 #endif /* #if __FreeBSD_version >= 900000 */
15798 
15799     sc->trigger_grcdump = 0;
15800     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15801                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15802                    "trigger grcdump should be invoked"
15803                    "  before collecting grcdump");
15804 
15805     sc->grcdump_started = 0;
15806     sc->grcdump_done = 0;
15807     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15808                    CTLFLAG_RD, &sc->grcdump_done, 0,
15809                    "set by driver when grcdump is done");
15810 
15811     sc->rx_budget = bxe_rx_budget;
15812     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15813                     CTLFLAG_RW, &sc->rx_budget, 0,
15814                     "rx processing budget");
15815 
15816    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
15817                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15818                     bxe_sysctl_pauseparam, "IU",
15819                     "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
15820 
15821 
15822     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15823                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15824                     bxe_sysctl_state, "IU", "dump driver state");
15825 
15826     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15827         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15828                         bxe_eth_stats_arr[i].string,
15829                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15830                         bxe_sysctl_eth_stat, "LU",
15831                         bxe_eth_stats_arr[i].string);
15832     }
15833 
15834     /* add a new parent node for all queues "dev.bxe.#.queue" */
15835     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15836                                 CTLFLAG_RD, NULL, "queue");
15837     queue_top_children = SYSCTL_CHILDREN(queue_top);
15838 
15839     for (i = 0; i < sc->num_queues; i++) {
15840         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15841         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15842         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15843                                 queue_num_buf, CTLFLAG_RD, NULL,
15844                                 "single queue");
15845         queue_children = SYSCTL_CHILDREN(queue);
15846 
15847         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15848             q_stat = ((i << 16) | j);
15849             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15850                             bxe_eth_q_stats_arr[j].string,
15851                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15852                             bxe_sysctl_eth_q_stat, "LU",
15853                             bxe_eth_q_stats_arr[j].string);
15854         }
15855     }
15856 }
15857 
15858 static int
15859 bxe_alloc_buf_rings(struct bxe_softc *sc)
15860 {
15861 #if __FreeBSD_version >= 901504
15862 
15863     int i;
15864     struct bxe_fastpath *fp;
15865 
15866     for (i = 0; i < sc->num_queues; i++) {
15867 
15868         fp = &sc->fp[i];
15869 
15870         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15871                                    M_NOWAIT, &fp->tx_mtx);
15872         if (fp->tx_br == NULL)
15873             return (-1);
15874     }
15875 #endif
15876     return (0);
15877 }
15878 
15879 static void
15880 bxe_free_buf_rings(struct bxe_softc *sc)
15881 {
15882 #if __FreeBSD_version >= 901504
15883 
15884     int i;
15885     struct bxe_fastpath *fp;
15886 
15887     for (i = 0; i < sc->num_queues; i++) {
15888 
15889         fp = &sc->fp[i];
15890 
15891         if (fp->tx_br) {
15892             buf_ring_free(fp->tx_br, M_DEVBUF);
15893             fp->tx_br = NULL;
15894         }
15895     }
15896 
15897 #endif
15898 }
15899 
15900 static void
15901 bxe_init_fp_mutexs(struct bxe_softc *sc)
15902 {
15903     int i;
15904     struct bxe_fastpath *fp;
15905 
15906     for (i = 0; i < sc->num_queues; i++) {
15907 
15908         fp = &sc->fp[i];
15909 
15910         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15911             "bxe%d_fp%d_tx_lock", sc->unit, i);
15912         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15913 
15914         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15915             "bxe%d_fp%d_rx_lock", sc->unit, i);
15916         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15917     }
15918 }
15919 
15920 static void
15921 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15922 {
15923     int i;
15924     struct bxe_fastpath *fp;
15925 
15926     for (i = 0; i < sc->num_queues; i++) {
15927 
15928         fp = &sc->fp[i];
15929 
15930         if (mtx_initialized(&fp->tx_mtx)) {
15931             mtx_destroy(&fp->tx_mtx);
15932         }
15933 
15934         if (mtx_initialized(&fp->rx_mtx)) {
15935             mtx_destroy(&fp->rx_mtx);
15936         }
15937     }
15938 }
15939 
15940 
15941 /*
15942  * Device attach function.
15943  *
15944  * Allocates device resources, performs secondary chip identification, and
15945  * initializes driver instance variables. This function is called from driver
15946  * load after a successful probe.
15947  *
15948  * Returns:
15949  *   0 = Success, >0 = Failure
15950  */
15951 static int
15952 bxe_attach(device_t dev)
15953 {
15954     struct bxe_softc *sc;
15955 
15956     sc = device_get_softc(dev);
15957 
15958     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15959 
15960     sc->state = BXE_STATE_CLOSED;
15961 
15962     sc->dev  = dev;
15963     sc->unit = device_get_unit(dev);
15964 
15965     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15966 
15967     sc->pcie_bus    = pci_get_bus(dev);
15968     sc->pcie_device = pci_get_slot(dev);
15969     sc->pcie_func   = pci_get_function(dev);
15970 
15971     /* enable bus master capability */
15972     pci_enable_busmaster(dev);
15973 
15974     /* get the BARs */
15975     if (bxe_allocate_bars(sc) != 0) {
15976         return (ENXIO);
15977     }
15978 
15979     /* initialize the mutexes */
15980     bxe_init_mutexes(sc);
15981 
15982     /* prepare the periodic callout */
15983     callout_init(&sc->periodic_callout, 0);
15984 
15985     /* prepare the chip taskqueue */
15986     sc->chip_tq_flags = CHIP_TQ_NONE;
15987     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15988              "bxe%d_chip_tq", sc->unit);
15989     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15990     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15991                                    taskqueue_thread_enqueue,
15992                                    &sc->chip_tq);
15993     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15994                             "%s", sc->chip_tq_name);
15995 
15996     /* get device info and set params */
15997     if (bxe_get_device_info(sc) != 0) {
15998         BLOGE(sc, "getting device info\n");
15999         bxe_deallocate_bars(sc);
16000         pci_disable_busmaster(dev);
16001         return (ENXIO);
16002     }
16003 
16004     /* get final misc params */
16005     bxe_get_params(sc);
16006 
16007     /* set the default MTU (changed via ifconfig) */
16008     sc->mtu = ETHERMTU;
16009 
16010     bxe_set_modes_bitmap(sc);
16011 
16012     /* XXX
16013      * If in AFEX mode and the function is configured for FCoE
16014      * then bail... no L2 allowed.
16015      */
16016 
16017     /* get phy settings from shmem and 'and' against admin settings */
16018     bxe_get_phy_info(sc);
16019 
16020     /* initialize the FreeBSD ifnet interface */
16021     if (bxe_init_ifnet(sc) != 0) {
16022         bxe_release_mutexes(sc);
16023         bxe_deallocate_bars(sc);
16024         pci_disable_busmaster(dev);
16025         return (ENXIO);
16026     }
16027 
16028     if (bxe_add_cdev(sc) != 0) {
16029         if (sc->ifp != NULL) {
16030             ether_ifdetach(sc->ifp);
16031         }
16032         ifmedia_removeall(&sc->ifmedia);
16033         bxe_release_mutexes(sc);
16034         bxe_deallocate_bars(sc);
16035         pci_disable_busmaster(dev);
16036         return (ENXIO);
16037     }
16038 
16039     /* allocate device interrupts */
16040     if (bxe_interrupt_alloc(sc) != 0) {
16041         bxe_del_cdev(sc);
16042         if (sc->ifp != NULL) {
16043             ether_ifdetach(sc->ifp);
16044         }
16045         ifmedia_removeall(&sc->ifmedia);
16046         bxe_release_mutexes(sc);
16047         bxe_deallocate_bars(sc);
16048         pci_disable_busmaster(dev);
16049         return (ENXIO);
16050     }
16051 
16052     bxe_init_fp_mutexs(sc);
16053 
16054     if (bxe_alloc_buf_rings(sc) != 0) {
16055 	bxe_free_buf_rings(sc);
16056         bxe_interrupt_free(sc);
16057         bxe_del_cdev(sc);
16058         if (sc->ifp != NULL) {
16059             ether_ifdetach(sc->ifp);
16060         }
16061         ifmedia_removeall(&sc->ifmedia);
16062         bxe_release_mutexes(sc);
16063         bxe_deallocate_bars(sc);
16064         pci_disable_busmaster(dev);
16065         return (ENXIO);
16066     }
16067 
16068     /* allocate ilt */
16069     if (bxe_alloc_ilt_mem(sc) != 0) {
16070 	bxe_free_buf_rings(sc);
16071         bxe_interrupt_free(sc);
16072         bxe_del_cdev(sc);
16073         if (sc->ifp != NULL) {
16074             ether_ifdetach(sc->ifp);
16075         }
16076         ifmedia_removeall(&sc->ifmedia);
16077         bxe_release_mutexes(sc);
16078         bxe_deallocate_bars(sc);
16079         pci_disable_busmaster(dev);
16080         return (ENXIO);
16081     }
16082 
16083     /* allocate the host hardware/software hsi structures */
16084     if (bxe_alloc_hsi_mem(sc) != 0) {
16085         bxe_free_ilt_mem(sc);
16086 	bxe_free_buf_rings(sc);
16087         bxe_interrupt_free(sc);
16088         bxe_del_cdev(sc);
16089         if (sc->ifp != NULL) {
16090             ether_ifdetach(sc->ifp);
16091         }
16092         ifmedia_removeall(&sc->ifmedia);
16093         bxe_release_mutexes(sc);
16094         bxe_deallocate_bars(sc);
16095         pci_disable_busmaster(dev);
16096         return (ENXIO);
16097     }
16098 
16099     /* need to reset chip if UNDI was active */
16100     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16101         /* init fw_seq */
16102         sc->fw_seq =
16103             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16104              DRV_MSG_SEQ_NUMBER_MASK);
16105         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16106         bxe_prev_unload(sc);
16107     }
16108 
16109 #if 1
16110     /* XXX */
16111     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16112 #else
16113     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16114         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16115         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16116         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16117         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16118         bxe_dcbx_init_params(sc);
16119     } else {
16120         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16121     }
16122 #endif
16123 
16124     /* calculate qm_cid_count */
16125     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16126     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16127 
16128     sc->max_cos = 1;
16129     bxe_init_multi_cos(sc);
16130 
16131     bxe_add_sysctls(sc);
16132 
16133     return (0);
16134 }
16135 
16136 /*
16137  * Device detach function.
16138  *
16139  * Stops the controller, resets the controller, and releases resources.
16140  *
16141  * Returns:
16142  *   0 = Success, >0 = Failure
16143  */
16144 static int
16145 bxe_detach(device_t dev)
16146 {
16147     struct bxe_softc *sc;
16148     if_t ifp;
16149 
16150     sc = device_get_softc(dev);
16151 
16152     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16153 
16154     ifp = sc->ifp;
16155     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16156         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16157         return(EBUSY);
16158     }
16159 
16160     bxe_del_cdev(sc);
16161 
16162     /* stop the periodic callout */
16163     bxe_periodic_stop(sc);
16164 
16165     /* stop the chip taskqueue */
16166     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16167     if (sc->chip_tq) {
16168         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16169         taskqueue_free(sc->chip_tq);
16170         sc->chip_tq = NULL;
16171     }
16172 
16173     /* stop and reset the controller if it was open */
16174     if (sc->state != BXE_STATE_CLOSED) {
16175         BXE_CORE_LOCK(sc);
16176         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16177         sc->state = BXE_STATE_DISABLED;
16178         BXE_CORE_UNLOCK(sc);
16179     }
16180 
16181     /* release the network interface */
16182     if (ifp != NULL) {
16183         ether_ifdetach(ifp);
16184     }
16185     ifmedia_removeall(&sc->ifmedia);
16186 
16187     /* XXX do the following based on driver state... */
16188 
16189     /* free the host hardware/software hsi structures */
16190     bxe_free_hsi_mem(sc);
16191 
16192     /* free ilt */
16193     bxe_free_ilt_mem(sc);
16194 
16195     bxe_free_buf_rings(sc);
16196 
16197     /* release the interrupts */
16198     bxe_interrupt_free(sc);
16199 
16200     /* Release the mutexes*/
16201     bxe_destroy_fp_mutexs(sc);
16202     bxe_release_mutexes(sc);
16203 
16204 
16205     /* Release the PCIe BAR mapped memory */
16206     bxe_deallocate_bars(sc);
16207 
16208     /* Release the FreeBSD interface. */
16209     if (sc->ifp != NULL) {
16210         if_free(sc->ifp);
16211     }
16212 
16213     pci_disable_busmaster(dev);
16214 
16215     return (0);
16216 }
16217 
16218 /*
16219  * Device shutdown function.
16220  *
16221  * Stops and resets the controller.
16222  *
16223  * Returns:
16224  *   Nothing
16225  */
16226 static int
16227 bxe_shutdown(device_t dev)
16228 {
16229     struct bxe_softc *sc;
16230 
16231     sc = device_get_softc(dev);
16232 
16233     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16234 
16235     /* stop the periodic callout */
16236     bxe_periodic_stop(sc);
16237 
16238     BXE_CORE_LOCK(sc);
16239     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16240     BXE_CORE_UNLOCK(sc);
16241 
16242     return (0);
16243 }
16244 
16245 void
16246 bxe_igu_ack_sb(struct bxe_softc *sc,
16247                uint8_t          igu_sb_id,
16248                uint8_t          segment,
16249                uint16_t         index,
16250                uint8_t          op,
16251                uint8_t          update)
16252 {
16253     uint32_t igu_addr = sc->igu_base_addr;
16254     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16255     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16256 }
16257 
16258 static void
16259 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16260                      uint8_t          func,
16261                      uint8_t          idu_sb_id,
16262                      uint8_t          is_pf)
16263 {
16264     uint32_t data, ctl, cnt = 100;
16265     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16266     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16267     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16268     uint32_t sb_bit =  1 << (idu_sb_id%32);
16269     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16270     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16271 
16272     /* Not supported in BC mode */
16273     if (CHIP_INT_MODE_IS_BC(sc)) {
16274         return;
16275     }
16276 
16277     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16278              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16279             IGU_REGULAR_CLEANUP_SET |
16280             IGU_REGULAR_BCLEANUP);
16281 
16282     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16283            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16284            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16285 
16286     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16287             data, igu_addr_data);
16288     REG_WR(sc, igu_addr_data, data);
16289 
16290     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16291                       BUS_SPACE_BARRIER_WRITE);
16292     mb();
16293 
16294     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16295             ctl, igu_addr_ctl);
16296     REG_WR(sc, igu_addr_ctl, ctl);
16297 
16298     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16299                       BUS_SPACE_BARRIER_WRITE);
16300     mb();
16301 
16302     /* wait for clean up to finish */
16303     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16304         DELAY(20000);
16305     }
16306 
16307     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16308         BLOGD(sc, DBG_LOAD,
16309               "Unable to finish IGU cleanup: "
16310               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16311               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16312     }
16313 }
16314 
16315 static void
16316 bxe_igu_clear_sb(struct bxe_softc *sc,
16317                  uint8_t          idu_sb_id)
16318 {
16319     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16320 }
16321 
16322 
16323 
16324 
16325 
16326 
16327 
16328 /*******************/
16329 /* ECORE CALLBACKS */
16330 /*******************/
16331 
16332 static void
16333 bxe_reset_common(struct bxe_softc *sc)
16334 {
16335     uint32_t val = 0x1400;
16336 
16337     /* reset_common */
16338     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16339 
16340     if (CHIP_IS_E3(sc)) {
16341         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16342         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16343     }
16344 
16345     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16346 }
16347 
16348 static void
16349 bxe_common_init_phy(struct bxe_softc *sc)
16350 {
16351     uint32_t shmem_base[2];
16352     uint32_t shmem2_base[2];
16353 
16354     /* Avoid common init in case MFW supports LFA */
16355     if (SHMEM2_RD(sc, size) >
16356         (uint32_t)offsetof(struct shmem2_region,
16357                            lfa_host_addr[SC_PORT(sc)])) {
16358         return;
16359     }
16360 
16361     shmem_base[0]  = sc->devinfo.shmem_base;
16362     shmem2_base[0] = sc->devinfo.shmem2_base;
16363 
16364     if (!CHIP_IS_E1x(sc)) {
16365         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16366         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16367     }
16368 
16369     bxe_acquire_phy_lock(sc);
16370     elink_common_init_phy(sc, shmem_base, shmem2_base,
16371                           sc->devinfo.chip_id, 0);
16372     bxe_release_phy_lock(sc);
16373 }
16374 
16375 static void
16376 bxe_pf_disable(struct bxe_softc *sc)
16377 {
16378     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16379 
16380     val &= ~IGU_PF_CONF_FUNC_EN;
16381 
16382     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16383     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16384     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16385 }
16386 
16387 static void
16388 bxe_init_pxp(struct bxe_softc *sc)
16389 {
16390     uint16_t devctl;
16391     int r_order, w_order;
16392 
16393     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16394 
16395     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16396 
16397     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16398 
16399     if (sc->mrrs == -1) {
16400         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16401     } else {
16402         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16403         r_order = sc->mrrs;
16404     }
16405 
16406     ecore_init_pxp_arb(sc, r_order, w_order);
16407 }
16408 
16409 static uint32_t
16410 bxe_get_pretend_reg(struct bxe_softc *sc)
16411 {
16412     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16413     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16414     return (base + (SC_ABS_FUNC(sc)) * stride);
16415 }
16416 
16417 /*
16418  * Called only on E1H or E2.
16419  * When pretending to be PF, the pretend value is the function number 0..7.
16420  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16421  * combination.
16422  */
16423 static int
16424 bxe_pretend_func(struct bxe_softc *sc,
16425                  uint16_t         pretend_func_val)
16426 {
16427     uint32_t pretend_reg;
16428 
16429     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16430         return (-1);
16431     }
16432 
16433     /* get my own pretend register */
16434     pretend_reg = bxe_get_pretend_reg(sc);
16435     REG_WR(sc, pretend_reg, pretend_func_val);
16436     REG_RD(sc, pretend_reg);
16437     return (0);
16438 }
16439 
16440 static void
16441 bxe_iov_init_dmae(struct bxe_softc *sc)
16442 {
16443     return;
16444 }
16445 
16446 static void
16447 bxe_iov_init_dq(struct bxe_softc *sc)
16448 {
16449     return;
16450 }
16451 
16452 /* send a NIG loopback debug packet */
16453 static void
16454 bxe_lb_pckt(struct bxe_softc *sc)
16455 {
16456     uint32_t wb_write[3];
16457 
16458     /* Ethernet source and destination addresses */
16459     wb_write[0] = 0x55555555;
16460     wb_write[1] = 0x55555555;
16461     wb_write[2] = 0x20;     /* SOP */
16462     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16463 
16464     /* NON-IP protocol */
16465     wb_write[0] = 0x09000000;
16466     wb_write[1] = 0x55555555;
16467     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16468     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16469 }
16470 
16471 /*
16472  * Some of the internal memories are not directly readable from the driver.
16473  * To test them we send debug packets.
16474  */
16475 static int
16476 bxe_int_mem_test(struct bxe_softc *sc)
16477 {
16478     int factor;
16479     int count, i;
16480     uint32_t val = 0;
16481 
16482     if (CHIP_REV_IS_FPGA(sc)) {
16483         factor = 120;
16484     } else if (CHIP_REV_IS_EMUL(sc)) {
16485         factor = 200;
16486     } else {
16487         factor = 1;
16488     }
16489 
16490     /* disable inputs of parser neighbor blocks */
16491     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16492     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16493     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16494     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16495 
16496     /*  write 0 to parser credits for CFC search request */
16497     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16498 
16499     /* send Ethernet packet */
16500     bxe_lb_pckt(sc);
16501 
16502     /* TODO do i reset NIG statistic? */
16503     /* Wait until NIG register shows 1 packet of size 0x10 */
16504     count = 1000 * factor;
16505     while (count) {
16506         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16507         val = *BXE_SP(sc, wb_data[0]);
16508         if (val == 0x10) {
16509             break;
16510         }
16511 
16512         DELAY(10000);
16513         count--;
16514     }
16515 
16516     if (val != 0x10) {
16517         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16518         return (-1);
16519     }
16520 
16521     /* wait until PRS register shows 1 packet */
16522     count = (1000 * factor);
16523     while (count) {
16524         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16525         if (val == 1) {
16526             break;
16527         }
16528 
16529         DELAY(10000);
16530         count--;
16531     }
16532 
16533     if (val != 0x1) {
16534         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16535         return (-2);
16536     }
16537 
16538     /* Reset and init BRB, PRS */
16539     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16540     DELAY(50000);
16541     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16542     DELAY(50000);
16543     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16544     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16545 
16546     /* Disable inputs of parser neighbor blocks */
16547     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16548     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16549     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16550     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16551 
16552     /* Write 0 to parser credits for CFC search request */
16553     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16554 
16555     /* send 10 Ethernet packets */
16556     for (i = 0; i < 10; i++) {
16557         bxe_lb_pckt(sc);
16558     }
16559 
16560     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16561     count = (1000 * factor);
16562     while (count) {
16563         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16564         val = *BXE_SP(sc, wb_data[0]);
16565         if (val == 0xb0) {
16566             break;
16567         }
16568 
16569         DELAY(10000);
16570         count--;
16571     }
16572 
16573     if (val != 0xb0) {
16574         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16575         return (-3);
16576     }
16577 
16578     /* Wait until PRS register shows 2 packets */
16579     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16580     if (val != 2) {
16581         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16582     }
16583 
16584     /* Write 1 to parser credits for CFC search request */
16585     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16586 
16587     /* Wait until PRS register shows 3 packets */
16588     DELAY(10000 * factor);
16589 
16590     /* Wait until NIG register shows 1 packet of size 0x10 */
16591     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16592     if (val != 3) {
16593         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16594     }
16595 
16596     /* clear NIG EOP FIFO */
16597     for (i = 0; i < 11; i++) {
16598         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16599     }
16600 
16601     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16602     if (val != 1) {
16603         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16604         return (-4);
16605     }
16606 
16607     /* Reset and init BRB, PRS, NIG */
16608     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16609     DELAY(50000);
16610     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16611     DELAY(50000);
16612     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16613     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16614     if (!CNIC_SUPPORT(sc)) {
16615         /* set NIC mode */
16616         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16617     }
16618 
16619     /* Enable inputs of parser neighbor blocks */
16620     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16621     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16622     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16623     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16624 
16625     return (0);
16626 }
16627 
16628 static void
16629 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16630 {
16631     int is_required;
16632     uint32_t val;
16633     int port;
16634 
16635     is_required = 0;
16636     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16637            SHARED_HW_CFG_FAN_FAILURE_MASK);
16638 
16639     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16640         is_required = 1;
16641     }
16642     /*
16643      * The fan failure mechanism is usually related to the PHY type since
16644      * the power consumption of the board is affected by the PHY. Currently,
16645      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16646      */
16647     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16648         for (port = PORT_0; port < PORT_MAX; port++) {
16649             is_required |= elink_fan_failure_det_req(sc,
16650                                                      sc->devinfo.shmem_base,
16651                                                      sc->devinfo.shmem2_base,
16652                                                      port);
16653         }
16654     }
16655 
16656     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16657 
16658     if (is_required == 0) {
16659         return;
16660     }
16661 
16662     /* Fan failure is indicated by SPIO 5 */
16663     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16664 
16665     /* set to active low mode */
16666     val = REG_RD(sc, MISC_REG_SPIO_INT);
16667     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16668     REG_WR(sc, MISC_REG_SPIO_INT, val);
16669 
16670     /* enable interrupt to signal the IGU */
16671     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16672     val |= MISC_SPIO_SPIO5;
16673     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16674 }
16675 
16676 static void
16677 bxe_enable_blocks_attention(struct bxe_softc *sc)
16678 {
16679     uint32_t val;
16680 
16681     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16682     if (!CHIP_IS_E1x(sc)) {
16683         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16684     } else {
16685         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16686     }
16687     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16688     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16689     /*
16690      * mask read length error interrupts in brb for parser
16691      * (parsing unit and 'checksum and crc' unit)
16692      * these errors are legal (PU reads fixed length and CAC can cause
16693      * read length error on truncated packets)
16694      */
16695     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16696     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16697     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16698     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16699     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16700     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16701 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16702 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16703     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16704     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16705     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16706 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16707 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16708     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16709     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16710     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16711     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16712 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16713 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16714 
16715     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16716            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16717            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16718     if (!CHIP_IS_E1x(sc)) {
16719         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16720                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16721     }
16722     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16723 
16724     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16725     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16726     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16727 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16728 
16729     if (!CHIP_IS_E1x(sc)) {
16730         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16731         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16732     }
16733 
16734     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16735     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16736 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16737     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16738 }
16739 
16740 /**
16741  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16742  *
16743  * @sc:     driver handle
16744  */
16745 static int
16746 bxe_init_hw_common(struct bxe_softc *sc)
16747 {
16748     uint8_t abs_func_id;
16749     uint32_t val;
16750 
16751     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16752           SC_ABS_FUNC(sc));
16753 
16754     /*
16755      * take the RESET lock to protect undi_unload flow from accessing
16756      * registers while we are resetting the chip
16757      */
16758     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16759 
16760     bxe_reset_common(sc);
16761 
16762     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16763 
16764     val = 0xfffc;
16765     if (CHIP_IS_E3(sc)) {
16766         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16767         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16768     }
16769 
16770     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16771 
16772     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16773 
16774     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16775     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16776 
16777     if (!CHIP_IS_E1x(sc)) {
16778         /*
16779          * 4-port mode or 2-port mode we need to turn off master-enable for
16780          * everyone. After that we turn it back on for self. So, we disregard
16781          * multi-function, and always disable all functions on the given path,
16782          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16783          */
16784         for (abs_func_id = SC_PATH(sc);
16785              abs_func_id < (E2_FUNC_MAX * 2);
16786              abs_func_id += 2) {
16787             if (abs_func_id == SC_ABS_FUNC(sc)) {
16788                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16789                 continue;
16790             }
16791 
16792             bxe_pretend_func(sc, abs_func_id);
16793 
16794             /* clear pf enable */
16795             bxe_pf_disable(sc);
16796 
16797             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16798         }
16799     }
16800 
16801     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16802 
16803     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16804 
16805     if (CHIP_IS_E1(sc)) {
16806         /*
16807          * enable HW interrupt from PXP on USDM overflow
16808          * bit 16 on INT_MASK_0
16809          */
16810         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16811     }
16812 
16813     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16814     bxe_init_pxp(sc);
16815 
16816 #ifdef __BIG_ENDIAN
16817     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16818     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16819     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16820     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16821     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16822     /* make sure this value is 0 */
16823     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16824 
16825     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16826     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16827     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16828     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16829     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16830 #endif
16831 
16832     ecore_ilt_init_page_size(sc, INITOP_SET);
16833 
16834     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16835         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16836     }
16837 
16838     /* let the HW do it's magic... */
16839     DELAY(100000);
16840 
16841     /* finish PXP init */
16842     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16843     if (val != 1) {
16844         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16845             val);
16846         return (-1);
16847     }
16848     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16849     if (val != 1) {
16850         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16851         return (-1);
16852     }
16853 
16854     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16855 
16856     /*
16857      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16858      * entries with value "0" and valid bit on. This needs to be done by the
16859      * first PF that is loaded in a path (i.e. common phase)
16860      */
16861     if (!CHIP_IS_E1x(sc)) {
16862 /*
16863  * In E2 there is a bug in the timers block that can cause function 6 / 7
16864  * (i.e. vnic3) to start even if it is marked as "scan-off".
16865  * This occurs when a different function (func2,3) is being marked
16866  * as "scan-off". Real-life scenario for example: if a driver is being
16867  * load-unloaded while func6,7 are down. This will cause the timer to access
16868  * the ilt, translate to a logical address and send a request to read/write.
16869  * Since the ilt for the function that is down is not valid, this will cause
16870  * a translation error which is unrecoverable.
16871  * The Workaround is intended to make sure that when this happens nothing
16872  * fatal will occur. The workaround:
16873  *  1.  First PF driver which loads on a path will:
16874  *      a.  After taking the chip out of reset, by using pretend,
16875  *          it will write "0" to the following registers of
16876  *          the other vnics.
16877  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16878  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16879  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16880  *          And for itself it will write '1' to
16881  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16882  *          dmae-operations (writing to pram for example.)
16883  *          note: can be done for only function 6,7 but cleaner this
16884  *            way.
16885  *      b.  Write zero+valid to the entire ILT.
16886  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16887  *          VNIC3 (of that port). The range allocated will be the
16888  *          entire ILT. This is needed to prevent  ILT range error.
16889  *  2.  Any PF driver load flow:
16890  *      a.  ILT update with the physical addresses of the allocated
16891  *          logical pages.
16892  *      b.  Wait 20msec. - note that this timeout is needed to make
16893  *          sure there are no requests in one of the PXP internal
16894  *          queues with "old" ILT addresses.
16895  *      c.  PF enable in the PGLC.
16896  *      d.  Clear the was_error of the PF in the PGLC. (could have
16897  *          occurred while driver was down)
16898  *      e.  PF enable in the CFC (WEAK + STRONG)
16899  *      f.  Timers scan enable
16900  *  3.  PF driver unload flow:
16901  *      a.  Clear the Timers scan_en.
16902  *      b.  Polling for scan_on=0 for that PF.
16903  *      c.  Clear the PF enable bit in the PXP.
16904  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16905  *      e.  Write zero+valid to all ILT entries (The valid bit must
16906  *          stay set)
16907  *      f.  If this is VNIC 3 of a port then also init
16908  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16909  *          to the last enrty in the ILT.
16910  *
16911  *      Notes:
16912  *      Currently the PF error in the PGLC is non recoverable.
16913  *      In the future the there will be a recovery routine for this error.
16914  *      Currently attention is masked.
16915  *      Having an MCP lock on the load/unload process does not guarantee that
16916  *      there is no Timer disable during Func6/7 enable. This is because the
16917  *      Timers scan is currently being cleared by the MCP on FLR.
16918  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16919  *      there is error before clearing it. But the flow above is simpler and
16920  *      more general.
16921  *      All ILT entries are written by zero+valid and not just PF6/7
16922  *      ILT entries since in the future the ILT entries allocation for
16923  *      PF-s might be dynamic.
16924  */
16925         struct ilt_client_info ilt_cli;
16926         struct ecore_ilt ilt;
16927 
16928         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16929         memset(&ilt, 0, sizeof(struct ecore_ilt));
16930 
16931         /* initialize dummy TM client */
16932         ilt_cli.start      = 0;
16933         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16934         ilt_cli.client_num = ILT_CLIENT_TM;
16935 
16936         /*
16937          * Step 1: set zeroes to all ilt page entries with valid bit on
16938          * Step 2: set the timers first/last ilt entry to point
16939          * to the entire range to prevent ILT range error for 3rd/4th
16940          * vnic (this code assumes existence of the vnic)
16941          *
16942          * both steps performed by call to ecore_ilt_client_init_op()
16943          * with dummy TM client
16944          *
16945          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16946          * and his brother are split registers
16947          */
16948 
16949         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16950         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16951         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16952 
16953         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16954         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16955         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16956     }
16957 
16958     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16959     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16960 
16961     if (!CHIP_IS_E1x(sc)) {
16962         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16963                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16964 
16965         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16966         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16967 
16968         /* let the HW do it's magic... */
16969         do {
16970             DELAY(200000);
16971             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16972         } while (factor-- && (val != 1));
16973 
16974         if (val != 1) {
16975             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16976             return (-1);
16977         }
16978     }
16979 
16980     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16981 
16982     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16983 
16984     bxe_iov_init_dmae(sc);
16985 
16986     /* clean the DMAE memory */
16987     sc->dmae_ready = 1;
16988     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16989 
16990     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16991 
16992     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16993 
16994     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16995 
16996     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16997 
16998     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16999     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17000     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17001     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17002 
17003     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17004 
17005     /* QM queues pointers table */
17006     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17007 
17008     /* soft reset pulse */
17009     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17010     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17011 
17012     if (CNIC_SUPPORT(sc))
17013         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17014 
17015     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17016     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17017     if (!CHIP_REV_IS_SLOW(sc)) {
17018         /* enable hw interrupt from doorbell Q */
17019         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17020     }
17021 
17022     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17023 
17024     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17025     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17026 
17027     if (!CHIP_IS_E1(sc)) {
17028         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17029     }
17030 
17031     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17032         if (IS_MF_AFEX(sc)) {
17033             /*
17034              * configure that AFEX and VLAN headers must be
17035              * received in AFEX mode
17036              */
17037             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17038             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17039             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17040             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17041             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17042         } else {
17043             /*
17044              * Bit-map indicating which L2 hdrs may appear
17045              * after the basic Ethernet header
17046              */
17047             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17048                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17049         }
17050     }
17051 
17052     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17053     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17054     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17055     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17056 
17057     if (!CHIP_IS_E1x(sc)) {
17058         /* reset VFC memories */
17059         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17060                VFC_MEMORIES_RST_REG_CAM_RST |
17061                VFC_MEMORIES_RST_REG_RAM_RST);
17062         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17063                VFC_MEMORIES_RST_REG_CAM_RST |
17064                VFC_MEMORIES_RST_REG_RAM_RST);
17065 
17066         DELAY(20000);
17067     }
17068 
17069     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17070     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17071     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17072     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17073 
17074     /* sync semi rtc */
17075     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17076            0x80000000);
17077     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17078            0x80000000);
17079 
17080     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17081     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17082     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17083 
17084     if (!CHIP_IS_E1x(sc)) {
17085         if (IS_MF_AFEX(sc)) {
17086             /*
17087              * configure that AFEX and VLAN headers must be
17088              * sent in AFEX mode
17089              */
17090             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17091             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17092             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17093             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17094             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17095         } else {
17096             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17097                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17098         }
17099     }
17100 
17101     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17102 
17103     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17104 
17105     if (CNIC_SUPPORT(sc)) {
17106         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17107         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17108         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17109         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17110         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17111         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17112         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17113         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17114         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17115         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17116     }
17117     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17118 
17119     if (sizeof(union cdu_context) != 1024) {
17120         /* we currently assume that a context is 1024 bytes */
17121         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17122               (long)sizeof(union cdu_context));
17123     }
17124 
17125     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17126     val = (4 << 24) + (0 << 12) + 1024;
17127     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17128 
17129     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17130 
17131     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17132     /* enable context validation interrupt from CFC */
17133     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17134 
17135     /* set the thresholds to prevent CFC/CDU race */
17136     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17137     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17138 
17139     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17140         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17141     }
17142 
17143     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17144     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17145 
17146     /* Reset PCIE errors for debug */
17147     REG_WR(sc, 0x2814, 0xffffffff);
17148     REG_WR(sc, 0x3820, 0xffffffff);
17149 
17150     if (!CHIP_IS_E1x(sc)) {
17151         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17152                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17153                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17154         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17155                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17156                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17157                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17158         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17159                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17160                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17161                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17162     }
17163 
17164     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17165 
17166     if (!CHIP_IS_E1(sc)) {
17167         /* in E3 this done in per-port section */
17168         if (!CHIP_IS_E3(sc))
17169             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17170     }
17171 
17172     if (CHIP_IS_E1H(sc)) {
17173         /* not applicable for E2 (and above ...) */
17174         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17175     }
17176 
17177     if (CHIP_REV_IS_SLOW(sc)) {
17178         DELAY(200000);
17179     }
17180 
17181     /* finish CFC init */
17182     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17183     if (val != 1) {
17184         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17185         return (-1);
17186     }
17187     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17188     if (val != 1) {
17189         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17190         return (-1);
17191     }
17192     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17193     if (val != 1) {
17194         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17195         return (-1);
17196     }
17197     REG_WR(sc, CFC_REG_DEBUG0, 0);
17198 
17199     if (CHIP_IS_E1(sc)) {
17200         /* read NIG statistic to see if this is our first up since powerup */
17201         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17202         val = *BXE_SP(sc, wb_data[0]);
17203 
17204         /* do internal memory self test */
17205         if ((val == 0) && bxe_int_mem_test(sc)) {
17206             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17207             return (-1);
17208         }
17209     }
17210 
17211     bxe_setup_fan_failure_detection(sc);
17212 
17213     /* clear PXP2 attentions */
17214     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17215 
17216     bxe_enable_blocks_attention(sc);
17217 
17218     if (!CHIP_REV_IS_SLOW(sc)) {
17219         ecore_enable_blocks_parity(sc);
17220     }
17221 
17222     if (!BXE_NOMCP(sc)) {
17223         if (CHIP_IS_E1x(sc)) {
17224             bxe_common_init_phy(sc);
17225         }
17226     }
17227 
17228     return (0);
17229 }
17230 
17231 /**
17232  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17233  *
17234  * @sc:     driver handle
17235  */
17236 static int
17237 bxe_init_hw_common_chip(struct bxe_softc *sc)
17238 {
17239     int rc = bxe_init_hw_common(sc);
17240 
17241     if (rc) {
17242         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17243         return (rc);
17244     }
17245 
17246     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17247     if (!BXE_NOMCP(sc)) {
17248         bxe_common_init_phy(sc);
17249     }
17250 
17251     return (0);
17252 }
17253 
17254 static int
17255 bxe_init_hw_port(struct bxe_softc *sc)
17256 {
17257     int port = SC_PORT(sc);
17258     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17259     uint32_t low, high;
17260     uint32_t val;
17261 
17262     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17263 
17264     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17265 
17266     ecore_init_block(sc, BLOCK_MISC, init_phase);
17267     ecore_init_block(sc, BLOCK_PXP, init_phase);
17268     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17269 
17270     /*
17271      * Timers bug workaround: disables the pf_master bit in pglue at
17272      * common phase, we need to enable it here before any dmae access are
17273      * attempted. Therefore we manually added the enable-master to the
17274      * port phase (it also happens in the function phase)
17275      */
17276     if (!CHIP_IS_E1x(sc)) {
17277         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17278     }
17279 
17280     ecore_init_block(sc, BLOCK_ATC, init_phase);
17281     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17282     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17283     ecore_init_block(sc, BLOCK_QM, init_phase);
17284 
17285     ecore_init_block(sc, BLOCK_TCM, init_phase);
17286     ecore_init_block(sc, BLOCK_UCM, init_phase);
17287     ecore_init_block(sc, BLOCK_CCM, init_phase);
17288     ecore_init_block(sc, BLOCK_XCM, init_phase);
17289 
17290     /* QM cid (connection) count */
17291     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17292 
17293     if (CNIC_SUPPORT(sc)) {
17294         ecore_init_block(sc, BLOCK_TM, init_phase);
17295         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17296         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17297     }
17298 
17299     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17300 
17301     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17302 
17303     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17304         if (IS_MF(sc)) {
17305             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17306         } else if (sc->mtu > 4096) {
17307             if (BXE_ONE_PORT(sc)) {
17308                 low = 160;
17309             } else {
17310                 val = sc->mtu;
17311                 /* (24*1024 + val*4)/256 */
17312                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17313             }
17314         } else {
17315             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17316         }
17317         high = (low + 56); /* 14*1024/256 */
17318         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17319         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17320     }
17321 
17322     if (CHIP_IS_MODE_4_PORT(sc)) {
17323         REG_WR(sc, SC_PORT(sc) ?
17324                BRB1_REG_MAC_GUARANTIED_1 :
17325                BRB1_REG_MAC_GUARANTIED_0, 40);
17326     }
17327 
17328     ecore_init_block(sc, BLOCK_PRS, init_phase);
17329     if (CHIP_IS_E3B0(sc)) {
17330         if (IS_MF_AFEX(sc)) {
17331             /* configure headers for AFEX mode */
17332             REG_WR(sc, SC_PORT(sc) ?
17333                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17334                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17335             REG_WR(sc, SC_PORT(sc) ?
17336                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17337                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17338             REG_WR(sc, SC_PORT(sc) ?
17339                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17340                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17341         } else {
17342             /* Ovlan exists only if we are in multi-function +
17343              * switch-dependent mode, in switch-independent there
17344              * is no ovlan headers
17345              */
17346             REG_WR(sc, SC_PORT(sc) ?
17347                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17348                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17349                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17350         }
17351     }
17352 
17353     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17354     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17355     ecore_init_block(sc, BLOCK_USDM, init_phase);
17356     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17357 
17358     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17359     ecore_init_block(sc, BLOCK_USEM, init_phase);
17360     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17361     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17362 
17363     ecore_init_block(sc, BLOCK_UPB, init_phase);
17364     ecore_init_block(sc, BLOCK_XPB, init_phase);
17365 
17366     ecore_init_block(sc, BLOCK_PBF, init_phase);
17367 
17368     if (CHIP_IS_E1x(sc)) {
17369         /* configure PBF to work without PAUSE mtu 9000 */
17370         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17371 
17372         /* update threshold */
17373         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17374         /* update init credit */
17375         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17376 
17377         /* probe changes */
17378         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17379         DELAY(50);
17380         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17381     }
17382 
17383     if (CNIC_SUPPORT(sc)) {
17384         ecore_init_block(sc, BLOCK_SRC, init_phase);
17385     }
17386 
17387     ecore_init_block(sc, BLOCK_CDU, init_phase);
17388     ecore_init_block(sc, BLOCK_CFC, init_phase);
17389 
17390     if (CHIP_IS_E1(sc)) {
17391         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17392         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17393     }
17394     ecore_init_block(sc, BLOCK_HC, init_phase);
17395 
17396     ecore_init_block(sc, BLOCK_IGU, init_phase);
17397 
17398     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17399     /* init aeu_mask_attn_func_0/1:
17400      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17401      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17402      *             bits 4-7 are used for "per vn group attention" */
17403     val = IS_MF(sc) ? 0xF7 : 0x7;
17404     /* Enable DCBX attention for all but E1 */
17405     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17406     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17407 
17408     ecore_init_block(sc, BLOCK_NIG, init_phase);
17409 
17410     if (!CHIP_IS_E1x(sc)) {
17411         /* Bit-map indicating which L2 hdrs may appear after the
17412          * basic Ethernet header
17413          */
17414         if (IS_MF_AFEX(sc)) {
17415             REG_WR(sc, SC_PORT(sc) ?
17416                    NIG_REG_P1_HDRS_AFTER_BASIC :
17417                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17418         } else {
17419             REG_WR(sc, SC_PORT(sc) ?
17420                    NIG_REG_P1_HDRS_AFTER_BASIC :
17421                    NIG_REG_P0_HDRS_AFTER_BASIC,
17422                    IS_MF_SD(sc) ? 7 : 6);
17423         }
17424 
17425         if (CHIP_IS_E3(sc)) {
17426             REG_WR(sc, SC_PORT(sc) ?
17427                    NIG_REG_LLH1_MF_MODE :
17428                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17429         }
17430     }
17431     if (!CHIP_IS_E3(sc)) {
17432         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17433     }
17434 
17435     if (!CHIP_IS_E1(sc)) {
17436         /* 0x2 disable mf_ov, 0x1 enable */
17437         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17438                (IS_MF_SD(sc) ? 0x1 : 0x2));
17439 
17440         if (!CHIP_IS_E1x(sc)) {
17441             val = 0;
17442             switch (sc->devinfo.mf_info.mf_mode) {
17443             case MULTI_FUNCTION_SD:
17444                 val = 1;
17445                 break;
17446             case MULTI_FUNCTION_SI:
17447             case MULTI_FUNCTION_AFEX:
17448                 val = 2;
17449                 break;
17450             }
17451 
17452             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17453                         NIG_REG_LLH0_CLS_TYPE), val);
17454         }
17455         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17456         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17457         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17458     }
17459 
17460     /* If SPIO5 is set to generate interrupts, enable it for this port */
17461     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17462     if (val & MISC_SPIO_SPIO5) {
17463         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17464                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17465         val = REG_RD(sc, reg_addr);
17466         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17467         REG_WR(sc, reg_addr, val);
17468     }
17469 
17470     return (0);
17471 }
17472 
17473 static uint32_t
17474 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17475                        uint32_t         reg,
17476                        uint32_t         expected,
17477                        uint32_t         poll_count)
17478 {
17479     uint32_t cur_cnt = poll_count;
17480     uint32_t val;
17481 
17482     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17483         DELAY(FLR_WAIT_INTERVAL);
17484     }
17485 
17486     return (val);
17487 }
17488 
17489 static int
17490 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17491                               uint32_t         reg,
17492                               char             *msg,
17493                               uint32_t         poll_cnt)
17494 {
17495     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17496 
17497     if (val != 0) {
17498         BLOGE(sc, "%s usage count=%d\n", msg, val);
17499         return (1);
17500     }
17501 
17502     return (0);
17503 }
17504 
17505 /* Common routines with VF FLR cleanup */
17506 static uint32_t
17507 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17508 {
17509     /* adjust polling timeout */
17510     if (CHIP_REV_IS_EMUL(sc)) {
17511         return (FLR_POLL_CNT * 2000);
17512     }
17513 
17514     if (CHIP_REV_IS_FPGA(sc)) {
17515         return (FLR_POLL_CNT * 120);
17516     }
17517 
17518     return (FLR_POLL_CNT);
17519 }
17520 
17521 static int
17522 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17523                            uint32_t         poll_cnt)
17524 {
17525     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17526     if (bxe_flr_clnup_poll_hw_counter(sc,
17527                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17528                                       "CFC PF usage counter timed out",
17529                                       poll_cnt)) {
17530         return (1);
17531     }
17532 
17533     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17534     if (bxe_flr_clnup_poll_hw_counter(sc,
17535                                       DORQ_REG_PF_USAGE_CNT,
17536                                       "DQ PF usage counter timed out",
17537                                       poll_cnt)) {
17538         return (1);
17539     }
17540 
17541     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17542     if (bxe_flr_clnup_poll_hw_counter(sc,
17543                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17544                                       "QM PF usage counter timed out",
17545                                       poll_cnt)) {
17546         return (1);
17547     }
17548 
17549     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17550     if (bxe_flr_clnup_poll_hw_counter(sc,
17551                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17552                                       "Timers VNIC usage counter timed out",
17553                                       poll_cnt)) {
17554         return (1);
17555     }
17556 
17557     if (bxe_flr_clnup_poll_hw_counter(sc,
17558                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17559                                       "Timers NUM_SCANS usage counter timed out",
17560                                       poll_cnt)) {
17561         return (1);
17562     }
17563 
17564     /* Wait DMAE PF usage counter to zero */
17565     if (bxe_flr_clnup_poll_hw_counter(sc,
17566                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17567                                       "DMAE dommand register timed out",
17568                                       poll_cnt)) {
17569         return (1);
17570     }
17571 
17572     return (0);
17573 }
17574 
17575 #define OP_GEN_PARAM(param)                                            \
17576     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17577 #define OP_GEN_TYPE(type)                                           \
17578     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17579 #define OP_GEN_AGG_VECT(index)                                             \
17580     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17581 
17582 static int
17583 bxe_send_final_clnup(struct bxe_softc *sc,
17584                      uint8_t          clnup_func,
17585                      uint32_t         poll_cnt)
17586 {
17587     uint32_t op_gen_command = 0;
17588     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17589                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17590     int ret = 0;
17591 
17592     if (REG_RD(sc, comp_addr)) {
17593         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17594         return (1);
17595     }
17596 
17597     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17598     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17599     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17600     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17601 
17602     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17603     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17604 
17605     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17606         BLOGE(sc, "FW final cleanup did not succeed\n");
17607         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17608               (REG_RD(sc, comp_addr)));
17609         bxe_panic(sc, ("FLR cleanup failed\n"));
17610         return (1);
17611     }
17612 
17613     /* Zero completion for nxt FLR */
17614     REG_WR(sc, comp_addr, 0);
17615 
17616     return (ret);
17617 }
17618 
17619 static void
17620 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17621                        struct pbf_pN_buf_regs *regs,
17622                        uint32_t               poll_count)
17623 {
17624     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17625     uint32_t cur_cnt = poll_count;
17626 
17627     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17628     crd = crd_start = REG_RD(sc, regs->crd);
17629     init_crd = REG_RD(sc, regs->init_crd);
17630 
17631     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17632     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17633     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17634 
17635     while ((crd != init_crd) &&
17636            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17637             (init_crd - crd_start))) {
17638         if (cur_cnt--) {
17639             DELAY(FLR_WAIT_INTERVAL);
17640             crd = REG_RD(sc, regs->crd);
17641             crd_freed = REG_RD(sc, regs->crd_freed);
17642         } else {
17643             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17644             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17645             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17646             break;
17647         }
17648     }
17649 
17650     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17651           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17652 }
17653 
17654 static void
17655 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17656                        struct pbf_pN_cmd_regs *regs,
17657                        uint32_t               poll_count)
17658 {
17659     uint32_t occup, to_free, freed, freed_start;
17660     uint32_t cur_cnt = poll_count;
17661 
17662     occup = to_free = REG_RD(sc, regs->lines_occup);
17663     freed = freed_start = REG_RD(sc, regs->lines_freed);
17664 
17665     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17666     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17667 
17668     while (occup &&
17669            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17670         if (cur_cnt--) {
17671             DELAY(FLR_WAIT_INTERVAL);
17672             occup = REG_RD(sc, regs->lines_occup);
17673             freed = REG_RD(sc, regs->lines_freed);
17674         } else {
17675             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17676             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17677             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17678             break;
17679         }
17680     }
17681 
17682     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17683           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17684 }
17685 
17686 static void
17687 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17688 {
17689     struct pbf_pN_cmd_regs cmd_regs[] = {
17690         {0, (CHIP_IS_E3B0(sc)) ?
17691             PBF_REG_TQ_OCCUPANCY_Q0 :
17692             PBF_REG_P0_TQ_OCCUPANCY,
17693             (CHIP_IS_E3B0(sc)) ?
17694             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17695             PBF_REG_P0_TQ_LINES_FREED_CNT},
17696         {1, (CHIP_IS_E3B0(sc)) ?
17697             PBF_REG_TQ_OCCUPANCY_Q1 :
17698             PBF_REG_P1_TQ_OCCUPANCY,
17699             (CHIP_IS_E3B0(sc)) ?
17700             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17701             PBF_REG_P1_TQ_LINES_FREED_CNT},
17702         {4, (CHIP_IS_E3B0(sc)) ?
17703             PBF_REG_TQ_OCCUPANCY_LB_Q :
17704             PBF_REG_P4_TQ_OCCUPANCY,
17705             (CHIP_IS_E3B0(sc)) ?
17706             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17707             PBF_REG_P4_TQ_LINES_FREED_CNT}
17708     };
17709 
17710     struct pbf_pN_buf_regs buf_regs[] = {
17711         {0, (CHIP_IS_E3B0(sc)) ?
17712             PBF_REG_INIT_CRD_Q0 :
17713             PBF_REG_P0_INIT_CRD ,
17714             (CHIP_IS_E3B0(sc)) ?
17715             PBF_REG_CREDIT_Q0 :
17716             PBF_REG_P0_CREDIT,
17717             (CHIP_IS_E3B0(sc)) ?
17718             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17719             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17720         {1, (CHIP_IS_E3B0(sc)) ?
17721             PBF_REG_INIT_CRD_Q1 :
17722             PBF_REG_P1_INIT_CRD,
17723             (CHIP_IS_E3B0(sc)) ?
17724             PBF_REG_CREDIT_Q1 :
17725             PBF_REG_P1_CREDIT,
17726             (CHIP_IS_E3B0(sc)) ?
17727             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17728             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17729         {4, (CHIP_IS_E3B0(sc)) ?
17730             PBF_REG_INIT_CRD_LB_Q :
17731             PBF_REG_P4_INIT_CRD,
17732             (CHIP_IS_E3B0(sc)) ?
17733             PBF_REG_CREDIT_LB_Q :
17734             PBF_REG_P4_CREDIT,
17735             (CHIP_IS_E3B0(sc)) ?
17736             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17737             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17738     };
17739 
17740     int i;
17741 
17742     /* Verify the command queues are flushed P0, P1, P4 */
17743     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17744         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17745     }
17746 
17747     /* Verify the transmission buffers are flushed P0, P1, P4 */
17748     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17749         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17750     }
17751 }
17752 
17753 static void
17754 bxe_hw_enable_status(struct bxe_softc *sc)
17755 {
17756     uint32_t val;
17757 
17758     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17759     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17760 
17761     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17762     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17763 
17764     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17765     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17766 
17767     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17768     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17769 
17770     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17771     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17772 
17773     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17774     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17775 
17776     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17777     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17778 
17779     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17780     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17781 }
17782 
17783 static int
17784 bxe_pf_flr_clnup(struct bxe_softc *sc)
17785 {
17786     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17787 
17788     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17789 
17790     /* Re-enable PF target read access */
17791     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17792 
17793     /* Poll HW usage counters */
17794     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17795     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17796         return (-1);
17797     }
17798 
17799     /* Zero the igu 'trailing edge' and 'leading edge' */
17800 
17801     /* Send the FW cleanup command */
17802     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17803         return (-1);
17804     }
17805 
17806     /* ATC cleanup */
17807 
17808     /* Verify TX hw is flushed */
17809     bxe_tx_hw_flushed(sc, poll_cnt);
17810 
17811     /* Wait 100ms (not adjusted according to platform) */
17812     DELAY(100000);
17813 
17814     /* Verify no pending pci transactions */
17815     if (bxe_is_pcie_pending(sc)) {
17816         BLOGE(sc, "PCIE Transactions still pending\n");
17817     }
17818 
17819     /* Debug */
17820     bxe_hw_enable_status(sc);
17821 
17822     /*
17823      * Master enable - Due to WB DMAE writes performed before this
17824      * register is re-initialized as part of the regular function init
17825      */
17826     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17827 
17828     return (0);
17829 }
17830 
17831 static int
17832 bxe_init_hw_func(struct bxe_softc *sc)
17833 {
17834     int port = SC_PORT(sc);
17835     int func = SC_FUNC(sc);
17836     int init_phase = PHASE_PF0 + func;
17837     struct ecore_ilt *ilt = sc->ilt;
17838     uint16_t cdu_ilt_start;
17839     uint32_t addr, val;
17840     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17841     int i, main_mem_width, rc;
17842 
17843     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17844 
17845     /* FLR cleanup */
17846     if (!CHIP_IS_E1x(sc)) {
17847         rc = bxe_pf_flr_clnup(sc);
17848         if (rc) {
17849             BLOGE(sc, "FLR cleanup failed!\n");
17850             // XXX bxe_fw_dump(sc);
17851             // XXX bxe_idle_chk(sc);
17852             return (rc);
17853         }
17854     }
17855 
17856     /* set MSI reconfigure capability */
17857     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17858         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17859         val = REG_RD(sc, addr);
17860         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17861         REG_WR(sc, addr, val);
17862     }
17863 
17864     ecore_init_block(sc, BLOCK_PXP, init_phase);
17865     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17866 
17867     ilt = sc->ilt;
17868     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17869 
17870     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17871         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17872         ilt->lines[cdu_ilt_start + i].page_mapping =
17873             sc->context[i].vcxt_dma.paddr;
17874         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17875     }
17876     ecore_ilt_init_op(sc, INITOP_SET);
17877 
17878     /* Set NIC mode */
17879     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17880     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17881 
17882     if (!CHIP_IS_E1x(sc)) {
17883         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17884 
17885         /* Turn on a single ISR mode in IGU if driver is going to use
17886          * INT#x or MSI
17887          */
17888         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17889             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17890         }
17891 
17892         /*
17893          * Timers workaround bug: function init part.
17894          * Need to wait 20msec after initializing ILT,
17895          * needed to make sure there are no requests in
17896          * one of the PXP internal queues with "old" ILT addresses
17897          */
17898         DELAY(20000);
17899 
17900         /*
17901          * Master enable - Due to WB DMAE writes performed before this
17902          * register is re-initialized as part of the regular function
17903          * init
17904          */
17905         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17906         /* Enable the function in IGU */
17907         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17908     }
17909 
17910     sc->dmae_ready = 1;
17911 
17912     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17913 
17914     if (!CHIP_IS_E1x(sc))
17915         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17916 
17917     ecore_init_block(sc, BLOCK_ATC, init_phase);
17918     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17919     ecore_init_block(sc, BLOCK_NIG, init_phase);
17920     ecore_init_block(sc, BLOCK_SRC, init_phase);
17921     ecore_init_block(sc, BLOCK_MISC, init_phase);
17922     ecore_init_block(sc, BLOCK_TCM, init_phase);
17923     ecore_init_block(sc, BLOCK_UCM, init_phase);
17924     ecore_init_block(sc, BLOCK_CCM, init_phase);
17925     ecore_init_block(sc, BLOCK_XCM, init_phase);
17926     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17927     ecore_init_block(sc, BLOCK_USEM, init_phase);
17928     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17929     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17930 
17931     if (!CHIP_IS_E1x(sc))
17932         REG_WR(sc, QM_REG_PF_EN, 1);
17933 
17934     if (!CHIP_IS_E1x(sc)) {
17935         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17936         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17937         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17938         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17939     }
17940     ecore_init_block(sc, BLOCK_QM, init_phase);
17941 
17942     ecore_init_block(sc, BLOCK_TM, init_phase);
17943     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17944 
17945     bxe_iov_init_dq(sc);
17946 
17947     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17948     ecore_init_block(sc, BLOCK_PRS, init_phase);
17949     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17950     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17951     ecore_init_block(sc, BLOCK_USDM, init_phase);
17952     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17953     ecore_init_block(sc, BLOCK_UPB, init_phase);
17954     ecore_init_block(sc, BLOCK_XPB, init_phase);
17955     ecore_init_block(sc, BLOCK_PBF, init_phase);
17956     if (!CHIP_IS_E1x(sc))
17957         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17958 
17959     ecore_init_block(sc, BLOCK_CDU, init_phase);
17960 
17961     ecore_init_block(sc, BLOCK_CFC, init_phase);
17962 
17963     if (!CHIP_IS_E1x(sc))
17964         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17965 
17966     if (IS_MF(sc)) {
17967         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17968         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17969     }
17970 
17971     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17972 
17973     /* HC init per function */
17974     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17975         if (CHIP_IS_E1H(sc)) {
17976             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17977 
17978             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17979             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17980         }
17981         ecore_init_block(sc, BLOCK_HC, init_phase);
17982 
17983     } else {
17984         int num_segs, sb_idx, prod_offset;
17985 
17986         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17987 
17988         if (!CHIP_IS_E1x(sc)) {
17989             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17990             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17991         }
17992 
17993         ecore_init_block(sc, BLOCK_IGU, init_phase);
17994 
17995         if (!CHIP_IS_E1x(sc)) {
17996             int dsb_idx = 0;
17997             /**
17998              * Producer memory:
17999              * E2 mode: address 0-135 match to the mapping memory;
18000              * 136 - PF0 default prod; 137 - PF1 default prod;
18001              * 138 - PF2 default prod; 139 - PF3 default prod;
18002              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18003              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18004              * 144-147 reserved.
18005              *
18006              * E1.5 mode - In backward compatible mode;
18007              * for non default SB; each even line in the memory
18008              * holds the U producer and each odd line hold
18009              * the C producer. The first 128 producers are for
18010              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18011              * producers are for the DSB for each PF.
18012              * Each PF has five segments: (the order inside each
18013              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18014              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18015              * 144-147 attn prods;
18016              */
18017             /* non-default-status-blocks */
18018             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18019                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18020             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18021                 prod_offset = (sc->igu_base_sb + sb_idx) *
18022                     num_segs;
18023 
18024                 for (i = 0; i < num_segs; i++) {
18025                     addr = IGU_REG_PROD_CONS_MEMORY +
18026                             (prod_offset + i) * 4;
18027                     REG_WR(sc, addr, 0);
18028                 }
18029                 /* send consumer update with value 0 */
18030                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18031                            USTORM_ID, 0, IGU_INT_NOP, 1);
18032                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18033             }
18034 
18035             /* default-status-blocks */
18036             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18037                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18038 
18039             if (CHIP_IS_MODE_4_PORT(sc))
18040                 dsb_idx = SC_FUNC(sc);
18041             else
18042                 dsb_idx = SC_VN(sc);
18043 
18044             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18045                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18046                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18047 
18048             /*
18049              * igu prods come in chunks of E1HVN_MAX (4) -
18050              * does not matters what is the current chip mode
18051              */
18052             for (i = 0; i < (num_segs * E1HVN_MAX);
18053                  i += E1HVN_MAX) {
18054                 addr = IGU_REG_PROD_CONS_MEMORY +
18055                             (prod_offset + i)*4;
18056                 REG_WR(sc, addr, 0);
18057             }
18058             /* send consumer update with 0 */
18059             if (CHIP_INT_MODE_IS_BC(sc)) {
18060                 bxe_ack_sb(sc, sc->igu_dsb_id,
18061                            USTORM_ID, 0, IGU_INT_NOP, 1);
18062                 bxe_ack_sb(sc, sc->igu_dsb_id,
18063                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18064                 bxe_ack_sb(sc, sc->igu_dsb_id,
18065                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18066                 bxe_ack_sb(sc, sc->igu_dsb_id,
18067                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18068                 bxe_ack_sb(sc, sc->igu_dsb_id,
18069                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18070             } else {
18071                 bxe_ack_sb(sc, sc->igu_dsb_id,
18072                            USTORM_ID, 0, IGU_INT_NOP, 1);
18073                 bxe_ack_sb(sc, sc->igu_dsb_id,
18074                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18075             }
18076             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18077 
18078             /* !!! these should become driver const once
18079                rf-tool supports split-68 const */
18080             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18081             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18082             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18083             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18084             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18085             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18086         }
18087     }
18088 
18089     /* Reset PCIE errors for debug */
18090     REG_WR(sc, 0x2114, 0xffffffff);
18091     REG_WR(sc, 0x2120, 0xffffffff);
18092 
18093     if (CHIP_IS_E1x(sc)) {
18094         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18095         main_mem_base = HC_REG_MAIN_MEMORY +
18096                 SC_PORT(sc) * (main_mem_size * 4);
18097         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18098         main_mem_width = 8;
18099 
18100         val = REG_RD(sc, main_mem_prty_clr);
18101         if (val) {
18102             BLOGD(sc, DBG_LOAD,
18103                   "Parity errors in HC block during function init (0x%x)!\n",
18104                   val);
18105         }
18106 
18107         /* Clear "false" parity errors in MSI-X table */
18108         for (i = main_mem_base;
18109              i < main_mem_base + main_mem_size * 4;
18110              i += main_mem_width) {
18111             bxe_read_dmae(sc, i, main_mem_width / 4);
18112             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18113                            i, main_mem_width / 4);
18114         }
18115         /* Clear HC parity attention */
18116         REG_RD(sc, main_mem_prty_clr);
18117     }
18118 
18119 #if 1
18120     /* Enable STORMs SP logging */
18121     REG_WR8(sc, BAR_USTRORM_INTMEM +
18122            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18123     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18124            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18125     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18126            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18127     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18128            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18129 #endif
18130 
18131     elink_phy_probe(&sc->link_params);
18132 
18133     return (0);
18134 }
18135 
18136 static void
18137 bxe_link_reset(struct bxe_softc *sc)
18138 {
18139     if (!BXE_NOMCP(sc)) {
18140 	bxe_acquire_phy_lock(sc);
18141         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18142 	bxe_release_phy_lock(sc);
18143     } else {
18144         if (!CHIP_REV_IS_SLOW(sc)) {
18145             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18146         }
18147     }
18148 }
18149 
18150 static void
18151 bxe_reset_port(struct bxe_softc *sc)
18152 {
18153     int port = SC_PORT(sc);
18154     uint32_t val;
18155 
18156 	ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18157     /* reset physical Link */
18158     bxe_link_reset(sc);
18159 
18160     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18161 
18162     /* Do not rcv packets to BRB */
18163     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18164     /* Do not direct rcv packets that are not for MCP to the BRB */
18165     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18166                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18167 
18168     /* Configure AEU */
18169     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18170 
18171     DELAY(100000);
18172 
18173     /* Check for BRB port occupancy */
18174     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18175     if (val) {
18176         BLOGD(sc, DBG_LOAD,
18177               "BRB1 is not empty, %d blocks are occupied\n", val);
18178     }
18179 
18180     /* TODO: Close Doorbell port? */
18181 }
18182 
18183 static void
18184 bxe_ilt_wr(struct bxe_softc *sc,
18185            uint32_t         index,
18186            bus_addr_t       addr)
18187 {
18188     int reg;
18189     uint32_t wb_write[2];
18190 
18191     if (CHIP_IS_E1(sc)) {
18192         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18193     } else {
18194         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18195     }
18196 
18197     wb_write[0] = ONCHIP_ADDR1(addr);
18198     wb_write[1] = ONCHIP_ADDR2(addr);
18199     REG_WR_DMAE(sc, reg, wb_write, 2);
18200 }
18201 
18202 static void
18203 bxe_clear_func_ilt(struct bxe_softc *sc,
18204                    uint32_t         func)
18205 {
18206     uint32_t i, base = FUNC_ILT_BASE(func);
18207     for (i = base; i < base + ILT_PER_FUNC; i++) {
18208         bxe_ilt_wr(sc, i, 0);
18209     }
18210 }
18211 
18212 static void
18213 bxe_reset_func(struct bxe_softc *sc)
18214 {
18215     struct bxe_fastpath *fp;
18216     int port = SC_PORT(sc);
18217     int func = SC_FUNC(sc);
18218     int i;
18219 
18220     /* Disable the function in the FW */
18221     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18222     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18223     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18224     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18225 
18226     /* FP SBs */
18227     FOR_EACH_ETH_QUEUE(sc, i) {
18228         fp = &sc->fp[i];
18229         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18230                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18231                 SB_DISABLED);
18232     }
18233 
18234     /* SP SB */
18235     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18236             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18237             SB_DISABLED);
18238 
18239     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18240         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18241     }
18242 
18243     /* Configure IGU */
18244     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18245         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18246         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18247     } else {
18248         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18249         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18250     }
18251 
18252     if (CNIC_LOADED(sc)) {
18253         /* Disable Timer scan */
18254         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18255         /*
18256          * Wait for at least 10ms and up to 2 second for the timers
18257          * scan to complete
18258          */
18259         for (i = 0; i < 200; i++) {
18260             DELAY(10000);
18261             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18262                 break;
18263         }
18264     }
18265 
18266     /* Clear ILT */
18267     bxe_clear_func_ilt(sc, func);
18268 
18269     /*
18270      * Timers workaround bug for E2: if this is vnic-3,
18271      * we need to set the entire ilt range for this timers.
18272      */
18273     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18274         struct ilt_client_info ilt_cli;
18275         /* use dummy TM client */
18276         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18277         ilt_cli.start = 0;
18278         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18279         ilt_cli.client_num = ILT_CLIENT_TM;
18280 
18281         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18282     }
18283 
18284     /* this assumes that reset_port() called before reset_func()*/
18285     if (!CHIP_IS_E1x(sc)) {
18286         bxe_pf_disable(sc);
18287     }
18288 
18289     sc->dmae_ready = 0;
18290 }
18291 
18292 static int
18293 bxe_gunzip_init(struct bxe_softc *sc)
18294 {
18295     return (0);
18296 }
18297 
18298 static void
18299 bxe_gunzip_end(struct bxe_softc *sc)
18300 {
18301     return;
18302 }
18303 
18304 static int
18305 bxe_init_firmware(struct bxe_softc *sc)
18306 {
18307     if (CHIP_IS_E1(sc)) {
18308         ecore_init_e1_firmware(sc);
18309         sc->iro_array = e1_iro_arr;
18310     } else if (CHIP_IS_E1H(sc)) {
18311         ecore_init_e1h_firmware(sc);
18312         sc->iro_array = e1h_iro_arr;
18313     } else if (!CHIP_IS_E1x(sc)) {
18314         ecore_init_e2_firmware(sc);
18315         sc->iro_array = e2_iro_arr;
18316     } else {
18317         BLOGE(sc, "Unsupported chip revision\n");
18318         return (-1);
18319     }
18320 
18321     return (0);
18322 }
18323 
18324 static void
18325 bxe_release_firmware(struct bxe_softc *sc)
18326 {
18327     /* Do nothing */
18328     return;
18329 }
18330 
18331 static int
18332 ecore_gunzip(struct bxe_softc *sc,
18333              const uint8_t    *zbuf,
18334              int              len)
18335 {
18336     /* XXX : Implement... */
18337     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18338     return (FALSE);
18339 }
18340 
18341 static void
18342 ecore_reg_wr_ind(struct bxe_softc *sc,
18343                  uint32_t         addr,
18344                  uint32_t         val)
18345 {
18346     bxe_reg_wr_ind(sc, addr, val);
18347 }
18348 
18349 static void
18350 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18351                           bus_addr_t       phys_addr,
18352                           uint32_t         addr,
18353                           uint32_t         len)
18354 {
18355     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18356 }
18357 
18358 void
18359 ecore_storm_memset_struct(struct bxe_softc *sc,
18360                           uint32_t         addr,
18361                           size_t           size,
18362                           uint32_t         *data)
18363 {
18364     uint8_t i;
18365     for (i = 0; i < size/4; i++) {
18366         REG_WR(sc, addr + (i * 4), data[i]);
18367     }
18368 }
18369 
18370 
18371 /*
18372  * character device - ioctl interface definitions
18373  */
18374 
18375 
18376 #include "bxe_dump.h"
18377 #include "bxe_ioctl.h"
18378 #include <sys/conf.h>
18379 
18380 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18381                 struct thread *td);
18382 
18383 static struct cdevsw bxe_cdevsw = {
18384     .d_version = D_VERSION,
18385     .d_ioctl = bxe_eioctl,
18386     .d_name = "bxecnic",
18387 };
18388 
18389 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18390 
18391 
18392 #define DUMP_ALL_PRESETS        0x1FFF
18393 #define DUMP_MAX_PRESETS        13
18394 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18395 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18396 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18397 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18398 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18399 
18400 #define IS_REG_IN_PRESET(presets, idx)  \
18401                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18402 
18403 
18404 static int
18405 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18406 {
18407     if (CHIP_IS_E1(sc))
18408         return dump_num_registers[0][preset-1];
18409     else if (CHIP_IS_E1H(sc))
18410         return dump_num_registers[1][preset-1];
18411     else if (CHIP_IS_E2(sc))
18412         return dump_num_registers[2][preset-1];
18413     else if (CHIP_IS_E3A0(sc))
18414         return dump_num_registers[3][preset-1];
18415     else if (CHIP_IS_E3B0(sc))
18416         return dump_num_registers[4][preset-1];
18417     else
18418         return 0;
18419 }
18420 
18421 static int
18422 bxe_get_total_regs_len32(struct bxe_softc *sc)
18423 {
18424     uint32_t preset_idx;
18425     int regdump_len32 = 0;
18426 
18427 
18428     /* Calculate the total preset regs length */
18429     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18430         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18431     }
18432 
18433     return regdump_len32;
18434 }
18435 
18436 static const uint32_t *
18437 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18438 {
18439     if (CHIP_IS_E2(sc))
18440         return page_vals_e2;
18441     else if (CHIP_IS_E3(sc))
18442         return page_vals_e3;
18443     else
18444         return NULL;
18445 }
18446 
18447 static uint32_t
18448 __bxe_get_page_reg_num(struct bxe_softc *sc)
18449 {
18450     if (CHIP_IS_E2(sc))
18451         return PAGE_MODE_VALUES_E2;
18452     else if (CHIP_IS_E3(sc))
18453         return PAGE_MODE_VALUES_E3;
18454     else
18455         return 0;
18456 }
18457 
18458 static const uint32_t *
18459 __bxe_get_page_write_ar(struct bxe_softc *sc)
18460 {
18461     if (CHIP_IS_E2(sc))
18462         return page_write_regs_e2;
18463     else if (CHIP_IS_E3(sc))
18464         return page_write_regs_e3;
18465     else
18466         return NULL;
18467 }
18468 
18469 static uint32_t
18470 __bxe_get_page_write_num(struct bxe_softc *sc)
18471 {
18472     if (CHIP_IS_E2(sc))
18473         return PAGE_WRITE_REGS_E2;
18474     else if (CHIP_IS_E3(sc))
18475         return PAGE_WRITE_REGS_E3;
18476     else
18477         return 0;
18478 }
18479 
18480 static const struct reg_addr *
18481 __bxe_get_page_read_ar(struct bxe_softc *sc)
18482 {
18483     if (CHIP_IS_E2(sc))
18484         return page_read_regs_e2;
18485     else if (CHIP_IS_E3(sc))
18486         return page_read_regs_e3;
18487     else
18488         return NULL;
18489 }
18490 
18491 static uint32_t
18492 __bxe_get_page_read_num(struct bxe_softc *sc)
18493 {
18494     if (CHIP_IS_E2(sc))
18495         return PAGE_READ_REGS_E2;
18496     else if (CHIP_IS_E3(sc))
18497         return PAGE_READ_REGS_E3;
18498     else
18499         return 0;
18500 }
18501 
18502 static bool
18503 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18504 {
18505     if (CHIP_IS_E1(sc))
18506         return IS_E1_REG(reg_info->chips);
18507     else if (CHIP_IS_E1H(sc))
18508         return IS_E1H_REG(reg_info->chips);
18509     else if (CHIP_IS_E2(sc))
18510         return IS_E2_REG(reg_info->chips);
18511     else if (CHIP_IS_E3A0(sc))
18512         return IS_E3A0_REG(reg_info->chips);
18513     else if (CHIP_IS_E3B0(sc))
18514         return IS_E3B0_REG(reg_info->chips);
18515     else
18516         return 0;
18517 }
18518 
18519 static bool
18520 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18521 {
18522     if (CHIP_IS_E1(sc))
18523         return IS_E1_REG(wreg_info->chips);
18524     else if (CHIP_IS_E1H(sc))
18525         return IS_E1H_REG(wreg_info->chips);
18526     else if (CHIP_IS_E2(sc))
18527         return IS_E2_REG(wreg_info->chips);
18528     else if (CHIP_IS_E3A0(sc))
18529         return IS_E3A0_REG(wreg_info->chips);
18530     else if (CHIP_IS_E3B0(sc))
18531         return IS_E3B0_REG(wreg_info->chips);
18532     else
18533         return 0;
18534 }
18535 
18536 /**
18537  * bxe_read_pages_regs - read "paged" registers
18538  *
18539  * @bp          device handle
18540  * @p           output buffer
18541  *
18542  * Reads "paged" memories: memories that may only be read by first writing to a
18543  * specific address ("write address") and then reading from a specific address
18544  * ("read address"). There may be more than one write address per "page" and
18545  * more than one read address per write address.
18546  */
18547 static void
18548 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18549 {
18550     uint32_t i, j, k, n;
18551 
18552     /* addresses of the paged registers */
18553     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18554     /* number of paged registers */
18555     int num_pages = __bxe_get_page_reg_num(sc);
18556     /* write addresses */
18557     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18558     /* number of write addresses */
18559     int write_num = __bxe_get_page_write_num(sc);
18560     /* read addresses info */
18561     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18562     /* number of read addresses */
18563     int read_num = __bxe_get_page_read_num(sc);
18564     uint32_t addr, size;
18565 
18566     for (i = 0; i < num_pages; i++) {
18567         for (j = 0; j < write_num; j++) {
18568             REG_WR(sc, write_addr[j], page_addr[i]);
18569 
18570             for (k = 0; k < read_num; k++) {
18571                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18572                     size = read_addr[k].size;
18573                     for (n = 0; n < size; n++) {
18574                         addr = read_addr[k].addr + n*4;
18575                         *p++ = REG_RD(sc, addr);
18576                     }
18577                 }
18578             }
18579         }
18580     }
18581     return;
18582 }
18583 
18584 
18585 static int
18586 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18587 {
18588     uint32_t i, j, addr;
18589     const struct wreg_addr *wreg_addr_p = NULL;
18590 
18591     if (CHIP_IS_E1(sc))
18592         wreg_addr_p = &wreg_addr_e1;
18593     else if (CHIP_IS_E1H(sc))
18594         wreg_addr_p = &wreg_addr_e1h;
18595     else if (CHIP_IS_E2(sc))
18596         wreg_addr_p = &wreg_addr_e2;
18597     else if (CHIP_IS_E3A0(sc))
18598         wreg_addr_p = &wreg_addr_e3;
18599     else if (CHIP_IS_E3B0(sc))
18600         wreg_addr_p = &wreg_addr_e3b0;
18601     else
18602         return (-1);
18603 
18604     /* Read the idle_chk registers */
18605     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18606         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18607             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18608             for (j = 0; j < idle_reg_addrs[i].size; j++)
18609                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18610         }
18611     }
18612 
18613     /* Read the regular registers */
18614     for (i = 0; i < REGS_COUNT; i++) {
18615         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18616             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18617             for (j = 0; j < reg_addrs[i].size; j++)
18618                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18619         }
18620     }
18621 
18622     /* Read the CAM registers */
18623     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18624         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18625         for (i = 0; i < wreg_addr_p->size; i++) {
18626             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18627 
18628             /* In case of wreg_addr register, read additional
18629                registers from read_regs array
18630              */
18631             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18632                 addr = *(wreg_addr_p->read_regs);
18633                 *p++ = REG_RD(sc, addr + j*4);
18634             }
18635         }
18636     }
18637 
18638     /* Paged registers are supported in E2 & E3 only */
18639     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18640         /* Read "paged" registers */
18641         bxe_read_pages_regs(sc, p, preset);
18642     }
18643 
18644     return 0;
18645 }
18646 
18647 int
18648 bxe_grc_dump(struct bxe_softc *sc)
18649 {
18650     int rval = 0;
18651     uint32_t preset_idx;
18652     uint8_t *buf;
18653     uint32_t size;
18654     struct  dump_header *d_hdr;
18655     uint32_t i;
18656     uint32_t reg_val;
18657     uint32_t reg_addr;
18658     uint32_t cmd_offset;
18659     struct ecore_ilt *ilt = SC_ILT(sc);
18660     struct bxe_fastpath *fp;
18661     struct ilt_client_info *ilt_cli;
18662     int grc_dump_size;
18663 
18664 
18665     if (sc->grcdump_done || sc->grcdump_started)
18666 	return (rval);
18667 
18668     sc->grcdump_started = 1;
18669     BLOGI(sc, "Started collecting grcdump\n");
18670 
18671     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18672                 sizeof(struct  dump_header);
18673 
18674     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18675 
18676     if (sc->grc_dump == NULL) {
18677         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18678         return(ENOMEM);
18679     }
18680 
18681 
18682 
18683     /* Disable parity attentions as long as following dump may
18684      * cause false alarms by reading never written registers. We
18685      * will re-enable parity attentions right after the dump.
18686      */
18687 
18688     /* Disable parity on path 0 */
18689     bxe_pretend_func(sc, 0);
18690 
18691     ecore_disable_blocks_parity(sc);
18692 
18693     /* Disable parity on path 1 */
18694     bxe_pretend_func(sc, 1);
18695     ecore_disable_blocks_parity(sc);
18696 
18697     /* Return to current function */
18698     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18699 
18700     buf = sc->grc_dump;
18701     d_hdr = sc->grc_dump;
18702 
18703     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18704     d_hdr->version = BNX2X_DUMP_VERSION;
18705     d_hdr->preset = DUMP_ALL_PRESETS;
18706 
18707     if (CHIP_IS_E1(sc)) {
18708         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18709     } else if (CHIP_IS_E1H(sc)) {
18710         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18711     } else if (CHIP_IS_E2(sc)) {
18712         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18713                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18714     } else if (CHIP_IS_E3A0(sc)) {
18715         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18716                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18717     } else if (CHIP_IS_E3B0(sc)) {
18718         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18719                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18720     }
18721 
18722     buf += sizeof(struct  dump_header);
18723 
18724     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18725 
18726         /* Skip presets with IOR */
18727         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18728             (preset_idx == 11))
18729             continue;
18730 
18731         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18732 
18733 	if (rval)
18734             break;
18735 
18736         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18737 
18738         buf += size;
18739     }
18740 
18741     bxe_pretend_func(sc, 0);
18742     ecore_clear_blocks_parity(sc);
18743     ecore_enable_blocks_parity(sc);
18744 
18745     bxe_pretend_func(sc, 1);
18746     ecore_clear_blocks_parity(sc);
18747     ecore_enable_blocks_parity(sc);
18748 
18749     /* Return to current function */
18750     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18751 
18752 
18753 
18754     if(sc->state == BXE_STATE_OPEN) {
18755         if(sc->fw_stats_req  != NULL) {
18756     		BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18757         			(uintmax_t)sc->fw_stats_req_mapping,
18758         			(uintmax_t)sc->fw_stats_data_mapping,
18759         			sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18760 		}
18761 		if(sc->def_sb != NULL) {
18762 			BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18763         			(void *)sc->def_sb_dma.paddr, sc->def_sb,
18764         			sizeof(struct host_sp_status_block));
18765 		}
18766 		if(sc->eq_dma.vaddr != NULL) {
18767     		BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18768         			(uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18769 		}
18770 		if(sc->sp_dma.vaddr != NULL) {
18771     		BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18772         			(uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18773         			sizeof(struct bxe_slowpath));
18774 		}
18775 		if(sc->spq_dma.vaddr != NULL) {
18776     		BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18777         			(uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18778 		}
18779 		if(sc->gz_buf_dma.vaddr != NULL) {
18780     		BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18781         			(uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18782         			FW_BUF_SIZE);
18783 		}
18784     	for (i = 0; i < sc->num_queues; i++) {
18785         	fp = &sc->fp[i];
18786 			if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
18787                         fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
18788                         fp->rx_sge_dma.vaddr != NULL) {
18789 
18790 				BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18791             			(uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18792             			sizeof(union bxe_host_hc_status_block));
18793 				BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18794             			(uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18795             			(BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18796         		BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18797             			(uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18798             			(BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18799         		BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18800             			(uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18801             			(BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18802         		BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18803             			(uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18804             			(BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18805     		}
18806 		}
18807 		if(ilt != NULL ) {
18808     		ilt_cli = &ilt->clients[1];
18809 			if(ilt->lines != NULL) {
18810     		for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18811         		BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18812             			(uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18813             			((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18814     		}
18815 			}
18816 		}
18817 
18818 
18819     	cmd_offset = DMAE_REG_CMD_MEM;
18820     	for (i = 0; i < 224; i++) {
18821         	reg_addr = (cmd_offset +(i * 4));
18822         	reg_val = REG_RD(sc, reg_addr);
18823         	BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18824             			reg_addr, reg_val);
18825     	}
18826 	}
18827 
18828     BLOGI(sc, "Collection of grcdump done\n");
18829     sc->grcdump_done = 1;
18830     return(rval);
18831 }
18832 
18833 static int
18834 bxe_add_cdev(struct bxe_softc *sc)
18835 {
18836     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18837 
18838     if (sc->eeprom == NULL) {
18839         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18840         return (-1);
18841     }
18842 
18843     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18844                             sc->ifp->if_dunit,
18845                             UID_ROOT,
18846                             GID_WHEEL,
18847                             0600,
18848                             "%s",
18849                             if_name(sc->ifp));
18850 
18851     if (sc->ioctl_dev == NULL) {
18852         free(sc->eeprom, M_DEVBUF);
18853         sc->eeprom = NULL;
18854         return (-1);
18855     }
18856 
18857     sc->ioctl_dev->si_drv1 = sc;
18858 
18859     return (0);
18860 }
18861 
18862 static void
18863 bxe_del_cdev(struct bxe_softc *sc)
18864 {
18865     if (sc->ioctl_dev != NULL)
18866         destroy_dev(sc->ioctl_dev);
18867 
18868     if (sc->eeprom != NULL) {
18869         free(sc->eeprom, M_DEVBUF);
18870         sc->eeprom = NULL;
18871     }
18872     sc->ioctl_dev = NULL;
18873 
18874     return;
18875 }
18876 
18877 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18878 {
18879 
18880     if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
18881         return FALSE;
18882 
18883     return TRUE;
18884 }
18885 
18886 
18887 static int
18888 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18889 {
18890     int rval = 0;
18891 
18892     if(!bxe_is_nvram_accessible(sc)) {
18893         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18894         return (-EAGAIN);
18895     }
18896     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18897 
18898 
18899    return (rval);
18900 }
18901 
18902 static int
18903 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18904 {
18905     int rval = 0;
18906 
18907     if(!bxe_is_nvram_accessible(sc)) {
18908         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18909         return (-EAGAIN);
18910     }
18911     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18912 
18913    return (rval);
18914 }
18915 
18916 static int
18917 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18918 {
18919     int rval = 0;
18920 
18921     switch (eeprom->eeprom_cmd) {
18922 
18923     case BXE_EEPROM_CMD_SET_EEPROM:
18924 
18925         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18926                        eeprom->eeprom_data_len);
18927 
18928         if (rval)
18929             break;
18930 
18931         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18932                        eeprom->eeprom_data_len);
18933         break;
18934 
18935     case BXE_EEPROM_CMD_GET_EEPROM:
18936 
18937         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18938                        eeprom->eeprom_data_len);
18939 
18940         if (rval) {
18941             break;
18942         }
18943 
18944         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18945                        eeprom->eeprom_data_len);
18946         break;
18947 
18948     default:
18949             rval = EINVAL;
18950             break;
18951     }
18952 
18953     if (rval) {
18954         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18955     }
18956 
18957     return (rval);
18958 }
18959 
18960 static int
18961 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18962 {
18963     uint32_t ext_phy_config;
18964     int port = SC_PORT(sc);
18965     int cfg_idx = bxe_get_link_cfg_idx(sc);
18966 
18967     dev_p->supported = sc->port.supported[cfg_idx] |
18968             (sc->port.supported[cfg_idx ^ 1] &
18969             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18970     dev_p->advertising = sc->port.advertising[cfg_idx];
18971     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18972         ELINK_ETH_PHY_SFP_1G_FIBER) {
18973         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18974         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18975     }
18976     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18977         !(sc->flags & BXE_MF_FUNC_DIS)) {
18978         dev_p->duplex = sc->link_vars.duplex;
18979         if (IS_MF(sc) && !BXE_NOMCP(sc))
18980             dev_p->speed = bxe_get_mf_speed(sc);
18981         else
18982             dev_p->speed = sc->link_vars.line_speed;
18983     } else {
18984         dev_p->duplex = DUPLEX_UNKNOWN;
18985         dev_p->speed = SPEED_UNKNOWN;
18986     }
18987 
18988     dev_p->port = bxe_media_detect(sc);
18989 
18990     ext_phy_config = SHMEM_RD(sc,
18991                          dev_info.port_hw_config[port].external_phy_config);
18992     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
18993         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
18994         dev_p->phy_address =  sc->port.phy_addr;
18995     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18996             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
18997         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18998             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
18999         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19000     else
19001         dev_p->phy_address = 0;
19002 
19003     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19004         dev_p->autoneg = AUTONEG_ENABLE;
19005     else
19006        dev_p->autoneg = AUTONEG_DISABLE;
19007 
19008 
19009     return 0;
19010 }
19011 
19012 static int
19013 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19014         struct thread *td)
19015 {
19016     struct bxe_softc    *sc;
19017     int                 rval = 0;
19018     device_t            pci_dev;
19019     bxe_grcdump_t       *dump = NULL;
19020     int grc_dump_size;
19021     bxe_drvinfo_t   *drv_infop = NULL;
19022     bxe_dev_setting_t  *dev_p;
19023     bxe_dev_setting_t  dev_set;
19024     bxe_get_regs_t  *reg_p;
19025     bxe_reg_rdw_t *reg_rdw_p;
19026     bxe_pcicfg_rdw_t *cfg_rdw_p;
19027     bxe_perm_mac_addr_t *mac_addr_p;
19028 
19029 
19030     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19031         return ENXIO;
19032 
19033     pci_dev= sc->dev;
19034 
19035     dump = (bxe_grcdump_t *)data;
19036 
19037     switch(cmd) {
19038 
19039         case BXE_GRC_DUMP_SIZE:
19040             dump->pci_func = sc->pcie_func;
19041             dump->grcdump_size =
19042                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19043                      sizeof(struct  dump_header);
19044             break;
19045 
19046         case BXE_GRC_DUMP:
19047 
19048             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19049                                 sizeof(struct  dump_header);
19050             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19051                 (dump->grcdump_size < grc_dump_size)) {
19052                 rval = EINVAL;
19053                 break;
19054             }
19055 
19056             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19057                 (!sc->grcdump_started)) {
19058                 rval =  bxe_grc_dump(sc);
19059             }
19060 
19061             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19062                 (sc->grc_dump != NULL))  {
19063                 dump->grcdump_dwords = grc_dump_size >> 2;
19064                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19065                 free(sc->grc_dump, M_DEVBUF);
19066                 sc->grc_dump = NULL;
19067                 sc->grcdump_started = 0;
19068                 sc->grcdump_done = 0;
19069             }
19070 
19071             break;
19072 
19073         case BXE_DRV_INFO:
19074             drv_infop = (bxe_drvinfo_t *)data;
19075             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19076             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19077                 BXE_DRIVER_VERSION);
19078             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19079                 sc->devinfo.bc_ver_str);
19080             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19081                 "%s", sc->fw_ver_str);
19082             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19083             drv_infop->reg_dump_len =
19084                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19085                     + sizeof(struct  dump_header);
19086             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19087                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19088             break;
19089 
19090         case BXE_DEV_SETTING:
19091             dev_p = (bxe_dev_setting_t *)data;
19092             bxe_get_settings(sc, &dev_set);
19093             dev_p->supported = dev_set.supported;
19094             dev_p->advertising = dev_set.advertising;
19095             dev_p->speed = dev_set.speed;
19096             dev_p->duplex = dev_set.duplex;
19097             dev_p->port = dev_set.port;
19098             dev_p->phy_address = dev_set.phy_address;
19099             dev_p->autoneg = dev_set.autoneg;
19100 
19101             break;
19102 
19103         case BXE_GET_REGS:
19104 
19105             reg_p = (bxe_get_regs_t *)data;
19106             grc_dump_size = reg_p->reg_buf_len;
19107 
19108             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19109                 bxe_grc_dump(sc);
19110             }
19111             if((sc->grcdump_done) && (sc->grcdump_started) &&
19112                 (sc->grc_dump != NULL))  {
19113                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19114                 free(sc->grc_dump, M_DEVBUF);
19115                 sc->grc_dump = NULL;
19116                 sc->grcdump_started = 0;
19117                 sc->grcdump_done = 0;
19118             }
19119 
19120             break;
19121 
19122         case BXE_RDW_REG:
19123             reg_rdw_p = (bxe_reg_rdw_t *)data;
19124             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19125                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19126                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19127 
19128             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19129                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19130                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19131 
19132             break;
19133 
19134         case BXE_RDW_PCICFG:
19135             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19136             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19137 
19138                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19139                                          cfg_rdw_p->cfg_width);
19140 
19141             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19142                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19143                             cfg_rdw_p->cfg_width);
19144             } else {
19145                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19146             }
19147             break;
19148 
19149         case BXE_MAC_ADDR:
19150             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19151             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19152                 sc->mac_addr_str);
19153             break;
19154 
19155         case BXE_EEPROM:
19156             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19157             break;
19158 
19159 
19160         default:
19161             break;
19162     }
19163 
19164     return (rval);
19165 }
19166