xref: /freebsd/sys/dev/bxe/bxe.c (revision a8197ad3aa952a03fc2aeebc2eafe9bb9de54550)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  * THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #define BXE_DRIVER_VERSION "1.78.91"
33 
34 #include "bxe.h"
35 #include "ecore_sp.h"
36 #include "ecore_init.h"
37 #include "ecore_init_ops.h"
38 
39 #include "57710_int_offsets.h"
40 #include "57711_int_offsets.h"
41 #include "57712_int_offsets.h"
42 
43 /*
44  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
45  * explicitly here for older kernels that don't include this changeset.
46  */
47 #ifndef CTLTYPE_U64
48 #define CTLTYPE_U64      CTLTYPE_QUAD
49 #define sysctl_handle_64 sysctl_handle_quad
50 #endif
51 
52 /*
53  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
54  * here as zero(0) for older kernels that don't include this changeset
55  * thereby masking the functionality.
56  */
57 #ifndef CSUM_TCP_IPV6
58 #define CSUM_TCP_IPV6 0
59 #define CSUM_UDP_IPV6 0
60 #endif
61 
62 /*
63  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
64  * for older kernels that don't include this changeset.
65  */
66 #if __FreeBSD_version < 900035
67 #define pci_find_cap pci_find_extcap
68 #endif
69 
70 #define BXE_DEF_SB_ATT_IDX 0x0001
71 #define BXE_DEF_SB_IDX     0x0002
72 
73 /*
74  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
75  * function HW initialization.
76  */
77 #define FLR_WAIT_USEC     10000 /* 10 msecs */
78 #define FLR_WAIT_INTERVAL 50    /* usecs */
79 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
80 
81 struct pbf_pN_buf_regs {
82     int pN;
83     uint32_t init_crd;
84     uint32_t crd;
85     uint32_t crd_freed;
86 };
87 
88 struct pbf_pN_cmd_regs {
89     int pN;
90     uint32_t lines_occup;
91     uint32_t lines_freed;
92 };
93 
94 /*
95  * PCI Device ID Table used by bxe_probe().
96  */
97 #define BXE_DEVDESC_MAX 64
98 static struct bxe_device_type bxe_devs[] = {
99     {
100         BRCM_VENDORID,
101         CHIP_NUM_57710,
102         PCI_ANY_ID, PCI_ANY_ID,
103         "QLogic NetXtreme II BCM57710 10GbE"
104     },
105     {
106         BRCM_VENDORID,
107         CHIP_NUM_57711,
108         PCI_ANY_ID, PCI_ANY_ID,
109         "QLogic NetXtreme II BCM57711 10GbE"
110     },
111     {
112         BRCM_VENDORID,
113         CHIP_NUM_57711E,
114         PCI_ANY_ID, PCI_ANY_ID,
115         "QLogic NetXtreme II BCM57711E 10GbE"
116     },
117     {
118         BRCM_VENDORID,
119         CHIP_NUM_57712,
120         PCI_ANY_ID, PCI_ANY_ID,
121         "QLogic NetXtreme II BCM57712 10GbE"
122     },
123     {
124         BRCM_VENDORID,
125         CHIP_NUM_57712_MF,
126         PCI_ANY_ID, PCI_ANY_ID,
127         "QLogic NetXtreme II BCM57712 MF 10GbE"
128     },
129     {
130         BRCM_VENDORID,
131         CHIP_NUM_57800,
132         PCI_ANY_ID, PCI_ANY_ID,
133         "QLogic NetXtreme II BCM57800 10GbE"
134     },
135     {
136         BRCM_VENDORID,
137         CHIP_NUM_57800_MF,
138         PCI_ANY_ID, PCI_ANY_ID,
139         "QLogic NetXtreme II BCM57800 MF 10GbE"
140     },
141     {
142         BRCM_VENDORID,
143         CHIP_NUM_57810,
144         PCI_ANY_ID, PCI_ANY_ID,
145         "QLogic NetXtreme II BCM57810 10GbE"
146     },
147     {
148         BRCM_VENDORID,
149         CHIP_NUM_57810_MF,
150         PCI_ANY_ID, PCI_ANY_ID,
151         "QLogic NetXtreme II BCM57810 MF 10GbE"
152     },
153     {
154         BRCM_VENDORID,
155         CHIP_NUM_57811,
156         PCI_ANY_ID, PCI_ANY_ID,
157         "QLogic NetXtreme II BCM57811 10GbE"
158     },
159     {
160         BRCM_VENDORID,
161         CHIP_NUM_57811_MF,
162         PCI_ANY_ID, PCI_ANY_ID,
163         "QLogic NetXtreme II BCM57811 MF 10GbE"
164     },
165     {
166         BRCM_VENDORID,
167         CHIP_NUM_57840_4_10,
168         PCI_ANY_ID, PCI_ANY_ID,
169         "QLogic NetXtreme II BCM57840 4x10GbE"
170     },
171     {
172         QLOGIC_VENDORID,
173         CHIP_NUM_57840_4_10,
174         PCI_ANY_ID, PCI_ANY_ID,
175         "QLogic NetXtreme II BCM57840 4x10GbE"
176     },
177     {
178         BRCM_VENDORID,
179         CHIP_NUM_57840_2_20,
180         PCI_ANY_ID, PCI_ANY_ID,
181         "QLogic NetXtreme II BCM57840 2x20GbE"
182     },
183     {
184         BRCM_VENDORID,
185         CHIP_NUM_57840_MF,
186         PCI_ANY_ID, PCI_ANY_ID,
187         "QLogic NetXtreme II BCM57840 MF 10GbE"
188     },
189     {
190         0, 0, 0, 0, NULL
191     }
192 };
193 
194 MALLOC_DECLARE(M_BXE_ILT);
195 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
196 
197 /*
198  * FreeBSD device entry points.
199  */
200 static int bxe_probe(device_t);
201 static int bxe_attach(device_t);
202 static int bxe_detach(device_t);
203 static int bxe_shutdown(device_t);
204 
205 
206 /*
207  * FreeBSD KLD module/device interface event handler method.
208  */
209 static device_method_t bxe_methods[] = {
210     /* Device interface (device_if.h) */
211     DEVMETHOD(device_probe,     bxe_probe),
212     DEVMETHOD(device_attach,    bxe_attach),
213     DEVMETHOD(device_detach,    bxe_detach),
214     DEVMETHOD(device_shutdown,  bxe_shutdown),
215     /* Bus interface (bus_if.h) */
216     DEVMETHOD(bus_print_child,  bus_generic_print_child),
217     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
218     KOBJMETHOD_END
219 };
220 
221 /*
222  * FreeBSD KLD Module data declaration
223  */
224 static driver_t bxe_driver = {
225     "bxe",                   /* module name */
226     bxe_methods,             /* event handler */
227     sizeof(struct bxe_softc) /* extra data */
228 };
229 
230 /*
231  * FreeBSD dev class is needed to manage dev instances and
232  * to associate with a bus type
233  */
234 static devclass_t bxe_devclass;
235 
236 MODULE_DEPEND(bxe, pci, 1, 1, 1);
237 MODULE_DEPEND(bxe, ether, 1, 1, 1);
238 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
239 
240 DEBUGNET_DEFINE(bxe);
241 
242 /* resources needed for unloading a previously loaded device */
243 
244 #define BXE_PREV_WAIT_NEEDED 1
245 struct mtx bxe_prev_mtx;
246 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
247 struct bxe_prev_list_node {
248     LIST_ENTRY(bxe_prev_list_node) node;
249     uint8_t bus;
250     uint8_t slot;
251     uint8_t path;
252     uint8_t aer; /* XXX automatic error recovery */
253     uint8_t undi;
254 };
255 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
256 
257 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
258 
259 /* Tunable device values... */
260 
261 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
262     "bxe driver parameters");
263 
264 /* Debug */
265 unsigned long bxe_debug = 0;
266 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
267              &bxe_debug, 0, "Debug logging mode");
268 
269 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
270 static int bxe_interrupt_mode = INTR_MODE_MSIX;
271 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
272            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
273 
274 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
275 static int bxe_queue_count = 4;
276 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
277            &bxe_queue_count, 0, "Multi-Queue queue count");
278 
279 /* max number of buffers per queue (default RX_BD_USABLE) */
280 static int bxe_max_rx_bufs = 0;
281 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
282            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
283 
284 /* Host interrupt coalescing RX tick timer (usecs) */
285 static int bxe_hc_rx_ticks = 25;
286 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
287            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
288 
289 /* Host interrupt coalescing TX tick timer (usecs) */
290 static int bxe_hc_tx_ticks = 50;
291 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
292            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
293 
294 /* Maximum number of Rx packets to process at a time */
295 static int bxe_rx_budget = 0xffffffff;
296 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
297            &bxe_rx_budget, 0, "Rx processing budget");
298 
299 /* Maximum LRO aggregation size */
300 static int bxe_max_aggregation_size = 0;
301 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
302            &bxe_max_aggregation_size, 0, "max aggregation size");
303 
304 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
305 static int bxe_mrrs = -1;
306 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
307            &bxe_mrrs, 0, "PCIe maximum read request size");
308 
309 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
310 static int bxe_autogreeen = 0;
311 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
312            &bxe_autogreeen, 0, "AutoGrEEEn support");
313 
314 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
315 static int bxe_udp_rss = 0;
316 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
317            &bxe_udp_rss, 0, "UDP RSS support");
318 
319 
320 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
321 
322 #define STATS_OFFSET32(stat_name)                   \
323     (offsetof(struct bxe_eth_stats, stat_name) / 4)
324 
325 #define Q_STATS_OFFSET32(stat_name)                   \
326     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
327 
328 static const struct {
329     uint32_t offset;
330     uint32_t size;
331     uint32_t flags;
332 #define STATS_FLAGS_PORT  1
333 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
334 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
335     char string[STAT_NAME_LEN];
336 } bxe_eth_stats_arr[] = {
337     { STATS_OFFSET32(total_bytes_received_hi),
338                 8, STATS_FLAGS_BOTH, "rx_bytes" },
339     { STATS_OFFSET32(error_bytes_received_hi),
340                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
341     { STATS_OFFSET32(total_unicast_packets_received_hi),
342                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
343     { STATS_OFFSET32(total_multicast_packets_received_hi),
344                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
345     { STATS_OFFSET32(total_broadcast_packets_received_hi),
346                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
347     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
348                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
349     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
350                 8, STATS_FLAGS_PORT, "rx_align_errors" },
351     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
352                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
353     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
354                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
355     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
356                 8, STATS_FLAGS_PORT, "rx_fragments" },
357     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
358                 8, STATS_FLAGS_PORT, "rx_jabbers" },
359     { STATS_OFFSET32(no_buff_discard_hi),
360                 8, STATS_FLAGS_BOTH, "rx_discards" },
361     { STATS_OFFSET32(mac_filter_discard),
362                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
363     { STATS_OFFSET32(mf_tag_discard),
364                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
365     { STATS_OFFSET32(pfc_frames_received_hi),
366                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
367     { STATS_OFFSET32(pfc_frames_sent_hi),
368                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
369     { STATS_OFFSET32(brb_drop_hi),
370                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
371     { STATS_OFFSET32(brb_truncate_hi),
372                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
373     { STATS_OFFSET32(pause_frames_received_hi),
374                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
375     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
376                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
377     { STATS_OFFSET32(nig_timer_max),
378                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
379     { STATS_OFFSET32(total_bytes_transmitted_hi),
380                 8, STATS_FLAGS_BOTH, "tx_bytes" },
381     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
382                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
383     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
384                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
385     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
386                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
387     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
388                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
389     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
390                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
391     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
392                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
393     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
394                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
395     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
396                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
397     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
398                 8, STATS_FLAGS_PORT, "tx_deferred" },
399     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
400                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
401     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
402                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
403     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
404                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
405     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
406                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
407     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
408                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
409     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
410                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
411     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
412                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
413     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
414                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
415     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
416                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
417     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
418                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
419     { STATS_OFFSET32(pause_frames_sent_hi),
420                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
421     { STATS_OFFSET32(total_tpa_aggregations_hi),
422                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
423     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
424                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
425     { STATS_OFFSET32(total_tpa_bytes_hi),
426                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
427     { STATS_OFFSET32(eee_tx_lpi),
428                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
429     { STATS_OFFSET32(rx_calls),
430                 4, STATS_FLAGS_FUNC, "rx_calls"},
431     { STATS_OFFSET32(rx_pkts),
432                 4, STATS_FLAGS_FUNC, "rx_pkts"},
433     { STATS_OFFSET32(rx_tpa_pkts),
434                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
435     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
436                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
437     { STATS_OFFSET32(rx_bxe_service_rxsgl),
438                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
439     { STATS_OFFSET32(rx_jumbo_sge_pkts),
440                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
441     { STATS_OFFSET32(rx_soft_errors),
442                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
443     { STATS_OFFSET32(rx_hw_csum_errors),
444                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
445     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
446                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
447     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
448                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
449     { STATS_OFFSET32(rx_budget_reached),
450                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
451     { STATS_OFFSET32(tx_pkts),
452                 4, STATS_FLAGS_FUNC, "tx_pkts"},
453     { STATS_OFFSET32(tx_soft_errors),
454                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
455     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
456                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
457     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
458                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
459     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
460                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
461     { STATS_OFFSET32(tx_ofld_frames_lso),
462                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
463     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
464                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
465     { STATS_OFFSET32(tx_encap_failures),
466                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
467     { STATS_OFFSET32(tx_hw_queue_full),
468                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
469     { STATS_OFFSET32(tx_hw_max_queue_depth),
470                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
471     { STATS_OFFSET32(tx_dma_mapping_failure),
472                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
473     { STATS_OFFSET32(tx_max_drbr_queue_depth),
474                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
475     { STATS_OFFSET32(tx_window_violation_std),
476                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
477     { STATS_OFFSET32(tx_window_violation_tso),
478                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
479     { STATS_OFFSET32(tx_chain_lost_mbuf),
480                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
481     { STATS_OFFSET32(tx_frames_deferred),
482                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
483     { STATS_OFFSET32(tx_queue_xoff),
484                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
485     { STATS_OFFSET32(mbuf_defrag_attempts),
486                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
487     { STATS_OFFSET32(mbuf_defrag_failures),
488                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
489     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
490                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
491     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
492                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
493     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
494                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
495     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
496                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
497     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
498                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
499     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
500                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
501     { STATS_OFFSET32(mbuf_alloc_tx),
502                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
503     { STATS_OFFSET32(mbuf_alloc_rx),
504                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
505     { STATS_OFFSET32(mbuf_alloc_sge),
506                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
507     { STATS_OFFSET32(mbuf_alloc_tpa),
508                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
509     { STATS_OFFSET32(tx_queue_full_return),
510                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
511     { STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
512                 4, STATS_FLAGS_FUNC, "bxe_tx_mq_sc_state_failures"},
513     { STATS_OFFSET32(tx_request_link_down_failures),
514                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
515     { STATS_OFFSET32(bd_avail_too_less_failures),
516                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
517     { STATS_OFFSET32(tx_mq_not_empty),
518                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"},
519     { STATS_OFFSET32(nsegs_path1_errors),
520                 4, STATS_FLAGS_FUNC, "nsegs_path1_errors"},
521     { STATS_OFFSET32(nsegs_path2_errors),
522                 4, STATS_FLAGS_FUNC, "nsegs_path2_errors"}
523 
524 
525 };
526 
527 static const struct {
528     uint32_t offset;
529     uint32_t size;
530     char string[STAT_NAME_LEN];
531 } bxe_eth_q_stats_arr[] = {
532     { Q_STATS_OFFSET32(total_bytes_received_hi),
533                 8, "rx_bytes" },
534     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
535                 8, "rx_ucast_packets" },
536     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
537                 8, "rx_mcast_packets" },
538     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
539                 8, "rx_bcast_packets" },
540     { Q_STATS_OFFSET32(no_buff_discard_hi),
541                 8, "rx_discards" },
542     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
543                 8, "tx_bytes" },
544     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
545                 8, "tx_ucast_packets" },
546     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
547                 8, "tx_mcast_packets" },
548     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
549                 8, "tx_bcast_packets" },
550     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
551                 8, "tpa_aggregations" },
552     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
553                 8, "tpa_aggregated_frames"},
554     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
555                 8, "tpa_bytes"},
556     { Q_STATS_OFFSET32(rx_calls),
557                 4, "rx_calls"},
558     { Q_STATS_OFFSET32(rx_pkts),
559                 4, "rx_pkts"},
560     { Q_STATS_OFFSET32(rx_tpa_pkts),
561                 4, "rx_tpa_pkts"},
562     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
563                 4, "rx_erroneous_jumbo_sge_pkts"},
564     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
565                 4, "rx_bxe_service_rxsgl"},
566     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
567                 4, "rx_jumbo_sge_pkts"},
568     { Q_STATS_OFFSET32(rx_soft_errors),
569                 4, "rx_soft_errors"},
570     { Q_STATS_OFFSET32(rx_hw_csum_errors),
571                 4, "rx_hw_csum_errors"},
572     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
573                 4, "rx_ofld_frames_csum_ip"},
574     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
575                 4, "rx_ofld_frames_csum_tcp_udp"},
576     { Q_STATS_OFFSET32(rx_budget_reached),
577                 4, "rx_budget_reached"},
578     { Q_STATS_OFFSET32(tx_pkts),
579                 4, "tx_pkts"},
580     { Q_STATS_OFFSET32(tx_soft_errors),
581                 4, "tx_soft_errors"},
582     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
583                 4, "tx_ofld_frames_csum_ip"},
584     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
585                 4, "tx_ofld_frames_csum_tcp"},
586     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
587                 4, "tx_ofld_frames_csum_udp"},
588     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
589                 4, "tx_ofld_frames_lso"},
590     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
591                 4, "tx_ofld_frames_lso_hdr_splits"},
592     { Q_STATS_OFFSET32(tx_encap_failures),
593                 4, "tx_encap_failures"},
594     { Q_STATS_OFFSET32(tx_hw_queue_full),
595                 4, "tx_hw_queue_full"},
596     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
597                 4, "tx_hw_max_queue_depth"},
598     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
599                 4, "tx_dma_mapping_failure"},
600     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
601                 4, "tx_max_drbr_queue_depth"},
602     { Q_STATS_OFFSET32(tx_window_violation_std),
603                 4, "tx_window_violation_std"},
604     { Q_STATS_OFFSET32(tx_window_violation_tso),
605                 4, "tx_window_violation_tso"},
606     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
607                 4, "tx_chain_lost_mbuf"},
608     { Q_STATS_OFFSET32(tx_frames_deferred),
609                 4, "tx_frames_deferred"},
610     { Q_STATS_OFFSET32(tx_queue_xoff),
611                 4, "tx_queue_xoff"},
612     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
613                 4, "mbuf_defrag_attempts"},
614     { Q_STATS_OFFSET32(mbuf_defrag_failures),
615                 4, "mbuf_defrag_failures"},
616     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
617                 4, "mbuf_rx_bd_alloc_failed"},
618     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
619                 4, "mbuf_rx_bd_mapping_failed"},
620     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
621                 4, "mbuf_rx_tpa_alloc_failed"},
622     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
623                 4, "mbuf_rx_tpa_mapping_failed"},
624     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
625                 4, "mbuf_rx_sge_alloc_failed"},
626     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
627                 4, "mbuf_rx_sge_mapping_failed"},
628     { Q_STATS_OFFSET32(mbuf_alloc_tx),
629                 4, "mbuf_alloc_tx"},
630     { Q_STATS_OFFSET32(mbuf_alloc_rx),
631                 4, "mbuf_alloc_rx"},
632     { Q_STATS_OFFSET32(mbuf_alloc_sge),
633                 4, "mbuf_alloc_sge"},
634     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
635                 4, "mbuf_alloc_tpa"},
636     { Q_STATS_OFFSET32(tx_queue_full_return),
637                 4, "tx_queue_full_return"},
638     { Q_STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
639                 4, "bxe_tx_mq_sc_state_failures"},
640     { Q_STATS_OFFSET32(tx_request_link_down_failures),
641                 4, "tx_request_link_down_failures"},
642     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
643                 4, "bd_avail_too_less_failures"},
644     { Q_STATS_OFFSET32(tx_mq_not_empty),
645                 4, "tx_mq_not_empty"},
646     { Q_STATS_OFFSET32(nsegs_path1_errors),
647                 4, "nsegs_path1_errors"},
648     { Q_STATS_OFFSET32(nsegs_path2_errors),
649                 4, "nsegs_path2_errors"}
650 
651 
652 };
653 
654 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
655 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
656 
657 
658 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
659                                  uint8_t          read_cfg,
660                                  uint8_t          cmng_type);
661 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
662 static void    storm_memset_cmng(struct bxe_softc *sc,
663                                  struct cmng_init *cmng,
664                                  uint8_t          port);
665 static void    bxe_set_reset_global(struct bxe_softc *sc);
666 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
667 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
668                                  int              engine);
669 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
670 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
671                                    uint8_t          *global,
672                                    uint8_t          print);
673 static void    bxe_int_disable(struct bxe_softc *sc);
674 static int     bxe_release_leader_lock(struct bxe_softc *sc);
675 static void    bxe_pf_disable(struct bxe_softc *sc);
676 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
677 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
678                                       struct bxe_fastpath *fp,
679                                       uint16_t            rx_bd_prod,
680                                       uint16_t            rx_cq_prod,
681                                       uint16_t            rx_sge_prod);
682 static void    bxe_link_report_locked(struct bxe_softc *sc);
683 static void    bxe_link_report(struct bxe_softc *sc);
684 static void    bxe_link_status_update(struct bxe_softc *sc);
685 static void    bxe_periodic_callout_func(void *xsc);
686 static void    bxe_periodic_start(struct bxe_softc *sc);
687 static void    bxe_periodic_stop(struct bxe_softc *sc);
688 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
689                                     uint16_t prev_index,
690                                     uint16_t index);
691 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
692                                      int                 queue);
693 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
694                                      uint16_t            index);
695 static uint8_t bxe_txeof(struct bxe_softc *sc,
696                          struct bxe_fastpath *fp);
697 static void    bxe_task_fp(struct bxe_fastpath *fp);
698 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
699                                      struct mbuf      *m,
700                                      uint8_t          contents);
701 static int     bxe_alloc_mem(struct bxe_softc *sc);
702 static void    bxe_free_mem(struct bxe_softc *sc);
703 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
704 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
705 static int     bxe_interrupt_attach(struct bxe_softc *sc);
706 static void    bxe_interrupt_detach(struct bxe_softc *sc);
707 static void    bxe_set_rx_mode(struct bxe_softc *sc);
708 static int     bxe_init_locked(struct bxe_softc *sc);
709 static int     bxe_stop_locked(struct bxe_softc *sc);
710 static void    bxe_sp_err_timeout_task(void *arg, int pending);
711 void           bxe_parity_recover(struct bxe_softc *sc);
712 void           bxe_handle_error(struct bxe_softc *sc);
713 static __noinline int bxe_nic_load(struct bxe_softc *sc,
714                                    int              load_mode);
715 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
716                                      uint32_t         unload_mode,
717                                      uint8_t          keep_link);
718 
719 static void bxe_handle_sp_tq(void *context, int pending);
720 static void bxe_handle_fp_tq(void *context, int pending);
721 
722 static int bxe_add_cdev(struct bxe_softc *sc);
723 static void bxe_del_cdev(struct bxe_softc *sc);
724 int bxe_grc_dump(struct bxe_softc *sc);
725 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
726 static void bxe_free_buf_rings(struct bxe_softc *sc);
727 
728 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
729 uint32_t
730 calc_crc32(uint8_t  *crc32_packet,
731            uint32_t crc32_length,
732            uint32_t crc32_seed,
733            uint8_t  complement)
734 {
735    uint32_t byte         = 0;
736    uint32_t bit          = 0;
737    uint8_t  msb          = 0;
738    uint32_t temp         = 0;
739    uint32_t shft         = 0;
740    uint8_t  current_byte = 0;
741    uint32_t crc32_result = crc32_seed;
742    const uint32_t CRC32_POLY = 0x1edc6f41;
743 
744    if ((crc32_packet == NULL) ||
745        (crc32_length == 0) ||
746        ((crc32_length % 8) != 0))
747     {
748         return (crc32_result);
749     }
750 
751     for (byte = 0; byte < crc32_length; byte = byte + 1)
752     {
753         current_byte = crc32_packet[byte];
754         for (bit = 0; bit < 8; bit = bit + 1)
755         {
756             /* msb = crc32_result[31]; */
757             msb = (uint8_t)(crc32_result >> 31);
758 
759             crc32_result = crc32_result << 1;
760 
761             /* it (msb != current_byte[bit]) */
762             if (msb != (0x1 & (current_byte >> bit)))
763             {
764                 crc32_result = crc32_result ^ CRC32_POLY;
765                 /* crc32_result[0] = 1 */
766                 crc32_result |= 1;
767             }
768         }
769     }
770 
771     /* Last step is to:
772      * 1. "mirror" every bit
773      * 2. swap the 4 bytes
774      * 3. complement each bit
775      */
776 
777     /* Mirror */
778     temp = crc32_result;
779     shft = sizeof(crc32_result) * 8 - 1;
780 
781     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
782     {
783         temp <<= 1;
784         temp |= crc32_result & 1;
785         shft-- ;
786     }
787 
788     /* temp[31-bit] = crc32_result[bit] */
789     temp <<= shft;
790 
791     /* Swap */
792     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
793     {
794         uint32_t t0, t1, t2, t3;
795         t0 = (0x000000ff & (temp >> 24));
796         t1 = (0x0000ff00 & (temp >> 8));
797         t2 = (0x00ff0000 & (temp << 8));
798         t3 = (0xff000000 & (temp << 24));
799         crc32_result = t0 | t1 | t2 | t3;
800     }
801 
802     /* Complement */
803     if (complement)
804     {
805         crc32_result = ~crc32_result;
806     }
807 
808     return (crc32_result);
809 }
810 
811 int
812 bxe_test_bit(int                    nr,
813              volatile unsigned long *addr)
814 {
815     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
816 }
817 
818 void
819 bxe_set_bit(unsigned int           nr,
820             volatile unsigned long *addr)
821 {
822     atomic_set_acq_long(addr, (1 << nr));
823 }
824 
825 void
826 bxe_clear_bit(int                    nr,
827               volatile unsigned long *addr)
828 {
829     atomic_clear_acq_long(addr, (1 << nr));
830 }
831 
832 int
833 bxe_test_and_set_bit(int                    nr,
834                        volatile unsigned long *addr)
835 {
836     unsigned long x;
837     nr = (1 << nr);
838     do {
839         x = *addr;
840     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
841     // if (x & nr) bit_was_set; else bit_was_not_set;
842     return (x & nr);
843 }
844 
845 int
846 bxe_test_and_clear_bit(int                    nr,
847                        volatile unsigned long *addr)
848 {
849     unsigned long x;
850     nr = (1 << nr);
851     do {
852         x = *addr;
853     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
854     // if (x & nr) bit_was_set; else bit_was_not_set;
855     return (x & nr);
856 }
857 
858 int
859 bxe_cmpxchg(volatile int *addr,
860             int          old,
861             int          new)
862 {
863     int x;
864     do {
865         x = *addr;
866     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
867     return (x);
868 }
869 
870 /*
871  * Get DMA memory from the OS.
872  *
873  * Validates that the OS has provided DMA buffers in response to a
874  * bus_dmamap_load call and saves the physical address of those buffers.
875  * When the callback is used the OS will return 0 for the mapping function
876  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
877  * failures back to the caller.
878  *
879  * Returns:
880  *   Nothing.
881  */
882 static void
883 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
884 {
885     struct bxe_dma *dma = arg;
886 
887     if (error) {
888         dma->paddr = 0;
889         dma->nseg  = 0;
890         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
891     } else {
892         dma->paddr = segs->ds_addr;
893         dma->nseg  = nseg;
894     }
895 }
896 
897 /*
898  * Allocate a block of memory and map it for DMA. No partial completions
899  * allowed and release any resources acquired if we can't acquire all
900  * resources.
901  *
902  * Returns:
903  *   0 = Success, !0 = Failure
904  */
905 int
906 bxe_dma_alloc(struct bxe_softc *sc,
907               bus_size_t       size,
908               struct bxe_dma   *dma,
909               const char       *msg)
910 {
911     int rc;
912 
913     if (dma->size > 0) {
914         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
915               (unsigned long)dma->size);
916         return (1);
917     }
918 
919     memset(dma, 0, sizeof(*dma)); /* sanity */
920     dma->sc   = sc;
921     dma->size = size;
922     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
923 
924     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
925                             BCM_PAGE_SIZE,      /* alignment */
926                             0,                  /* boundary limit */
927                             BUS_SPACE_MAXADDR,  /* restricted low */
928                             BUS_SPACE_MAXADDR,  /* restricted hi */
929                             NULL,               /* addr filter() */
930                             NULL,               /* addr filter() arg */
931                             size,               /* max map size */
932                             1,                  /* num discontinuous */
933                             size,               /* max seg size */
934                             BUS_DMA_ALLOCNOW,   /* flags */
935                             NULL,               /* lock() */
936                             NULL,               /* lock() arg */
937                             &dma->tag);         /* returned dma tag */
938     if (rc != 0) {
939         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
940         memset(dma, 0, sizeof(*dma));
941         return (1);
942     }
943 
944     rc = bus_dmamem_alloc(dma->tag,
945                           (void **)&dma->vaddr,
946                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
947                           &dma->map);
948     if (rc != 0) {
949         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
950         bus_dma_tag_destroy(dma->tag);
951         memset(dma, 0, sizeof(*dma));
952         return (1);
953     }
954 
955     rc = bus_dmamap_load(dma->tag,
956                          dma->map,
957                          dma->vaddr,
958                          size,
959                          bxe_dma_map_addr, /* BLOGD in here */
960                          dma,
961                          BUS_DMA_NOWAIT);
962     if (rc != 0) {
963         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
964         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
965         bus_dma_tag_destroy(dma->tag);
966         memset(dma, 0, sizeof(*dma));
967         return (1);
968     }
969 
970     return (0);
971 }
972 
973 void
974 bxe_dma_free(struct bxe_softc *sc,
975              struct bxe_dma   *dma)
976 {
977     if (dma->size > 0) {
978         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
979 
980         bus_dmamap_sync(dma->tag, dma->map,
981                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
982         bus_dmamap_unload(dma->tag, dma->map);
983         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
984         bus_dma_tag_destroy(dma->tag);
985     }
986 
987     memset(dma, 0, sizeof(*dma));
988 }
989 
990 /*
991  * These indirect read and write routines are only during init.
992  * The locking is handled by the MCP.
993  */
994 
995 void
996 bxe_reg_wr_ind(struct bxe_softc *sc,
997                uint32_t         addr,
998                uint32_t         val)
999 {
1000     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1001     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
1002     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1003 }
1004 
1005 uint32_t
1006 bxe_reg_rd_ind(struct bxe_softc *sc,
1007                uint32_t         addr)
1008 {
1009     uint32_t val;
1010 
1011     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1012     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1013     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1014 
1015     return (val);
1016 }
1017 
1018 static int
1019 bxe_acquire_hw_lock(struct bxe_softc *sc,
1020                     uint32_t         resource)
1021 {
1022     uint32_t lock_status;
1023     uint32_t resource_bit = (1 << resource);
1024     int func = SC_FUNC(sc);
1025     uint32_t hw_lock_control_reg;
1026     int cnt;
1027 
1028     /* validate the resource is within range */
1029     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1030         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1031             " resource_bit 0x%x\n", resource, resource_bit);
1032         return (-1);
1033     }
1034 
1035     if (func <= 5) {
1036         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1037     } else {
1038         hw_lock_control_reg =
1039                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1040     }
1041 
1042     /* validate the resource is not already taken */
1043     lock_status = REG_RD(sc, hw_lock_control_reg);
1044     if (lock_status & resource_bit) {
1045         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1046               resource, lock_status, resource_bit);
1047         return (-1);
1048     }
1049 
1050     /* try every 5ms for 5 seconds */
1051     for (cnt = 0; cnt < 1000; cnt++) {
1052         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1053         lock_status = REG_RD(sc, hw_lock_control_reg);
1054         if (lock_status & resource_bit) {
1055             return (0);
1056         }
1057         DELAY(5000);
1058     }
1059 
1060     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1061         resource, resource_bit);
1062     return (-1);
1063 }
1064 
1065 static int
1066 bxe_release_hw_lock(struct bxe_softc *sc,
1067                     uint32_t         resource)
1068 {
1069     uint32_t lock_status;
1070     uint32_t resource_bit = (1 << resource);
1071     int func = SC_FUNC(sc);
1072     uint32_t hw_lock_control_reg;
1073 
1074     /* validate the resource is within range */
1075     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1076         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1077             " resource_bit 0x%x\n", resource, resource_bit);
1078         return (-1);
1079     }
1080 
1081     if (func <= 5) {
1082         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1083     } else {
1084         hw_lock_control_reg =
1085                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1086     }
1087 
1088     /* validate the resource is currently taken */
1089     lock_status = REG_RD(sc, hw_lock_control_reg);
1090     if (!(lock_status & resource_bit)) {
1091         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1092               resource, lock_status, resource_bit);
1093         return (-1);
1094     }
1095 
1096     REG_WR(sc, hw_lock_control_reg, resource_bit);
1097     return (0);
1098 }
1099 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1100 {
1101 	BXE_PHY_LOCK(sc);
1102 	bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1103 }
1104 
1105 static void bxe_release_phy_lock(struct bxe_softc *sc)
1106 {
1107 	bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO);
1108 	BXE_PHY_UNLOCK(sc);
1109 }
1110 /*
1111  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1112  * had we done things the other way around, if two pfs from the same port
1113  * would attempt to access nvram at the same time, we could run into a
1114  * scenario such as:
1115  * pf A takes the port lock.
1116  * pf B succeeds in taking the same lock since they are from the same port.
1117  * pf A takes the per pf misc lock. Performs eeprom access.
1118  * pf A finishes. Unlocks the per pf misc lock.
1119  * Pf B takes the lock and proceeds to perform it's own access.
1120  * pf A unlocks the per port lock, while pf B is still working (!).
1121  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1122  * access corrupted by pf B).*
1123  */
1124 static int
1125 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1126 {
1127     int port = SC_PORT(sc);
1128     int count, i;
1129     uint32_t val = 0;
1130 
1131     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1132     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1133 
1134     /* adjust timeout for emulation/FPGA */
1135     count = NVRAM_TIMEOUT_COUNT;
1136     if (CHIP_REV_IS_SLOW(sc)) {
1137         count *= 100;
1138     }
1139 
1140     /* request access to nvram interface */
1141     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1142            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1143 
1144     for (i = 0; i < count*10; i++) {
1145         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1146         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1147             break;
1148         }
1149 
1150         DELAY(5);
1151     }
1152 
1153     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1154         BLOGE(sc, "Cannot get access to nvram interface "
1155             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1156             port, val);
1157         return (-1);
1158     }
1159 
1160     return (0);
1161 }
1162 
1163 static int
1164 bxe_release_nvram_lock(struct bxe_softc *sc)
1165 {
1166     int port = SC_PORT(sc);
1167     int count, i;
1168     uint32_t val = 0;
1169 
1170     /* adjust timeout for emulation/FPGA */
1171     count = NVRAM_TIMEOUT_COUNT;
1172     if (CHIP_REV_IS_SLOW(sc)) {
1173         count *= 100;
1174     }
1175 
1176     /* relinquish nvram interface */
1177     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1178            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1179 
1180     for (i = 0; i < count*10; i++) {
1181         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1182         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1183             break;
1184         }
1185 
1186         DELAY(5);
1187     }
1188 
1189     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1190         BLOGE(sc, "Cannot free access to nvram interface "
1191             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1192             port, val);
1193         return (-1);
1194     }
1195 
1196     /* release HW lock: protect against other PFs in PF Direct Assignment */
1197     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1198 
1199     return (0);
1200 }
1201 
1202 static void
1203 bxe_enable_nvram_access(struct bxe_softc *sc)
1204 {
1205     uint32_t val;
1206 
1207     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1208 
1209     /* enable both bits, even on read */
1210     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1211            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1212 }
1213 
1214 static void
1215 bxe_disable_nvram_access(struct bxe_softc *sc)
1216 {
1217     uint32_t val;
1218 
1219     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1220 
1221     /* disable both bits, even after read */
1222     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1223            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1224                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1225 }
1226 
1227 static int
1228 bxe_nvram_read_dword(struct bxe_softc *sc,
1229                      uint32_t         offset,
1230                      uint32_t         *ret_val,
1231                      uint32_t         cmd_flags)
1232 {
1233     int count, i, rc;
1234     uint32_t val;
1235 
1236     /* build the command word */
1237     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1238 
1239     /* need to clear DONE bit separately */
1240     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1241 
1242     /* address of the NVRAM to read from */
1243     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1244            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1245 
1246     /* issue a read command */
1247     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1248 
1249     /* adjust timeout for emulation/FPGA */
1250     count = NVRAM_TIMEOUT_COUNT;
1251     if (CHIP_REV_IS_SLOW(sc)) {
1252         count *= 100;
1253     }
1254 
1255     /* wait for completion */
1256     *ret_val = 0;
1257     rc = -1;
1258     for (i = 0; i < count; i++) {
1259         DELAY(5);
1260         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1261 
1262         if (val & MCPR_NVM_COMMAND_DONE) {
1263             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1264             /* we read nvram data in cpu order
1265              * but ethtool sees it as an array of bytes
1266              * converting to big-endian will do the work
1267              */
1268             *ret_val = htobe32(val);
1269             rc = 0;
1270             break;
1271         }
1272     }
1273 
1274     if (rc == -1) {
1275         BLOGE(sc, "nvram read timeout expired "
1276             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1277             offset, cmd_flags, val);
1278     }
1279 
1280     return (rc);
1281 }
1282 
1283 static int
1284 bxe_nvram_read(struct bxe_softc *sc,
1285                uint32_t         offset,
1286                uint8_t          *ret_buf,
1287                int              buf_size)
1288 {
1289     uint32_t cmd_flags;
1290     uint32_t val;
1291     int rc;
1292 
1293     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1294         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1295               offset, buf_size);
1296         return (-1);
1297     }
1298 
1299     if ((offset + buf_size) > sc->devinfo.flash_size) {
1300         BLOGE(sc, "Invalid parameter, "
1301                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1302               offset, buf_size, sc->devinfo.flash_size);
1303         return (-1);
1304     }
1305 
1306     /* request access to nvram interface */
1307     rc = bxe_acquire_nvram_lock(sc);
1308     if (rc) {
1309         return (rc);
1310     }
1311 
1312     /* enable access to nvram interface */
1313     bxe_enable_nvram_access(sc);
1314 
1315     /* read the first word(s) */
1316     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1317     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1318         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1319         memcpy(ret_buf, &val, 4);
1320 
1321         /* advance to the next dword */
1322         offset += sizeof(uint32_t);
1323         ret_buf += sizeof(uint32_t);
1324         buf_size -= sizeof(uint32_t);
1325         cmd_flags = 0;
1326     }
1327 
1328     if (rc == 0) {
1329         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1330         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1331         memcpy(ret_buf, &val, 4);
1332     }
1333 
1334     /* disable access to nvram interface */
1335     bxe_disable_nvram_access(sc);
1336     bxe_release_nvram_lock(sc);
1337 
1338     return (rc);
1339 }
1340 
1341 static int
1342 bxe_nvram_write_dword(struct bxe_softc *sc,
1343                       uint32_t         offset,
1344                       uint32_t         val,
1345                       uint32_t         cmd_flags)
1346 {
1347     int count, i, rc;
1348 
1349     /* build the command word */
1350     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1351 
1352     /* need to clear DONE bit separately */
1353     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1354 
1355     /* write the data */
1356     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1357 
1358     /* address of the NVRAM to write to */
1359     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1360            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1361 
1362     /* issue the write command */
1363     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1364 
1365     /* adjust timeout for emulation/FPGA */
1366     count = NVRAM_TIMEOUT_COUNT;
1367     if (CHIP_REV_IS_SLOW(sc)) {
1368         count *= 100;
1369     }
1370 
1371     /* wait for completion */
1372     rc = -1;
1373     for (i = 0; i < count; i++) {
1374         DELAY(5);
1375         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1376         if (val & MCPR_NVM_COMMAND_DONE) {
1377             rc = 0;
1378             break;
1379         }
1380     }
1381 
1382     if (rc == -1) {
1383         BLOGE(sc, "nvram write timeout expired "
1384             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1385             offset, cmd_flags, val);
1386     }
1387 
1388     return (rc);
1389 }
1390 
1391 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1392 
1393 static int
1394 bxe_nvram_write1(struct bxe_softc *sc,
1395                  uint32_t         offset,
1396                  uint8_t          *data_buf,
1397                  int              buf_size)
1398 {
1399     uint32_t cmd_flags;
1400     uint32_t align_offset;
1401     uint32_t val;
1402     int rc;
1403 
1404     if ((offset + buf_size) > sc->devinfo.flash_size) {
1405         BLOGE(sc, "Invalid parameter, "
1406                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1407               offset, buf_size, sc->devinfo.flash_size);
1408         return (-1);
1409     }
1410 
1411     /* request access to nvram interface */
1412     rc = bxe_acquire_nvram_lock(sc);
1413     if (rc) {
1414         return (rc);
1415     }
1416 
1417     /* enable access to nvram interface */
1418     bxe_enable_nvram_access(sc);
1419 
1420     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1421     align_offset = (offset & ~0x03);
1422     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1423 
1424     if (rc == 0) {
1425         val &= ~(0xff << BYTE_OFFSET(offset));
1426         val |= (*data_buf << BYTE_OFFSET(offset));
1427 
1428         /* nvram data is returned as an array of bytes
1429          * convert it back to cpu order
1430          */
1431         val = be32toh(val);
1432 
1433         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1434     }
1435 
1436     /* disable access to nvram interface */
1437     bxe_disable_nvram_access(sc);
1438     bxe_release_nvram_lock(sc);
1439 
1440     return (rc);
1441 }
1442 
1443 static int
1444 bxe_nvram_write(struct bxe_softc *sc,
1445                 uint32_t         offset,
1446                 uint8_t          *data_buf,
1447                 int              buf_size)
1448 {
1449     uint32_t cmd_flags;
1450     uint32_t val;
1451     uint32_t written_so_far;
1452     int rc;
1453 
1454     if (buf_size == 1) {
1455         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1456     }
1457 
1458     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1459         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1460               offset, buf_size);
1461         return (-1);
1462     }
1463 
1464     if (buf_size == 0) {
1465         return (0); /* nothing to do */
1466     }
1467 
1468     if ((offset + buf_size) > sc->devinfo.flash_size) {
1469         BLOGE(sc, "Invalid parameter, "
1470                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1471               offset, buf_size, sc->devinfo.flash_size);
1472         return (-1);
1473     }
1474 
1475     /* request access to nvram interface */
1476     rc = bxe_acquire_nvram_lock(sc);
1477     if (rc) {
1478         return (rc);
1479     }
1480 
1481     /* enable access to nvram interface */
1482     bxe_enable_nvram_access(sc);
1483 
1484     written_so_far = 0;
1485     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1486     while ((written_so_far < buf_size) && (rc == 0)) {
1487         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1488             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1489         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1490             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1491         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1492             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1493         }
1494 
1495         memcpy(&val, data_buf, 4);
1496 
1497         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1498 
1499         /* advance to the next dword */
1500         offset += sizeof(uint32_t);
1501         data_buf += sizeof(uint32_t);
1502         written_so_far += sizeof(uint32_t);
1503         cmd_flags = 0;
1504     }
1505 
1506     /* disable access to nvram interface */
1507     bxe_disable_nvram_access(sc);
1508     bxe_release_nvram_lock(sc);
1509 
1510     return (rc);
1511 }
1512 
1513 /* copy command into DMAE command memory and set DMAE command Go */
1514 void
1515 bxe_post_dmae(struct bxe_softc    *sc,
1516               struct dmae_cmd *dmae,
1517               int                 idx)
1518 {
1519     uint32_t cmd_offset;
1520     int i;
1521 
1522     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1523     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1524         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1525     }
1526 
1527     REG_WR(sc, dmae_reg_go_c[idx], 1);
1528 }
1529 
1530 uint32_t
1531 bxe_dmae_opcode_add_comp(uint32_t opcode,
1532                          uint8_t  comp_type)
1533 {
1534     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1535                       DMAE_CMD_C_TYPE_ENABLE));
1536 }
1537 
1538 uint32_t
1539 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1540 {
1541     return (opcode & ~DMAE_CMD_SRC_RESET);
1542 }
1543 
1544 uint32_t
1545 bxe_dmae_opcode(struct bxe_softc *sc,
1546                 uint8_t          src_type,
1547                 uint8_t          dst_type,
1548                 uint8_t          with_comp,
1549                 uint8_t          comp_type)
1550 {
1551     uint32_t opcode = 0;
1552 
1553     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1554                (dst_type << DMAE_CMD_DST_SHIFT));
1555 
1556     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1557 
1558     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1559 
1560     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1561                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1562 
1563     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1564 
1565 #ifdef __BIG_ENDIAN
1566     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1567 #else
1568     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1569 #endif
1570 
1571     if (with_comp) {
1572         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1573     }
1574 
1575     return (opcode);
1576 }
1577 
1578 static void
1579 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1580                         struct dmae_cmd *dmae,
1581                         uint8_t             src_type,
1582                         uint8_t             dst_type)
1583 {
1584     memset(dmae, 0, sizeof(struct dmae_cmd));
1585 
1586     /* set the opcode */
1587     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1588                                    TRUE, DMAE_COMP_PCI);
1589 
1590     /* fill in the completion parameters */
1591     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1592     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1593     dmae->comp_val     = DMAE_COMP_VAL;
1594 }
1595 
1596 /* issue a DMAE command over the init channel and wait for completion */
1597 static int
1598 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1599                          struct dmae_cmd *dmae)
1600 {
1601     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1602     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1603 
1604     BXE_DMAE_LOCK(sc);
1605 
1606     /* reset completion */
1607     *wb_comp = 0;
1608 
1609     /* post the command on the channel used for initializations */
1610     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1611 
1612     /* wait for completion */
1613     DELAY(5);
1614 
1615     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1616         if (!timeout ||
1617             (sc->recovery_state != BXE_RECOVERY_DONE &&
1618              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1619             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1620                 *wb_comp, sc->recovery_state);
1621             BXE_DMAE_UNLOCK(sc);
1622             return (DMAE_TIMEOUT);
1623         }
1624 
1625         timeout--;
1626         DELAY(50);
1627     }
1628 
1629     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1630         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1631                 *wb_comp, sc->recovery_state);
1632         BXE_DMAE_UNLOCK(sc);
1633         return (DMAE_PCI_ERROR);
1634     }
1635 
1636     BXE_DMAE_UNLOCK(sc);
1637     return (0);
1638 }
1639 
1640 void
1641 bxe_read_dmae(struct bxe_softc *sc,
1642               uint32_t         src_addr,
1643               uint32_t         len32)
1644 {
1645     struct dmae_cmd dmae;
1646     uint32_t *data;
1647     int i, rc;
1648 
1649     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1650 
1651     if (!sc->dmae_ready) {
1652         data = BXE_SP(sc, wb_data[0]);
1653 
1654         for (i = 0; i < len32; i++) {
1655             data[i] = (CHIP_IS_E1(sc)) ?
1656                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1657                           REG_RD(sc, (src_addr + (i * 4)));
1658         }
1659 
1660         return;
1661     }
1662 
1663     /* set opcode and fixed command fields */
1664     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1665 
1666     /* fill in addresses and len */
1667     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1668     dmae.src_addr_hi = 0;
1669     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1670     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1671     dmae.len         = len32;
1672 
1673     /* issue the command and wait for completion */
1674     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1675         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1676     }
1677 }
1678 
1679 void
1680 bxe_write_dmae(struct bxe_softc *sc,
1681                bus_addr_t       dma_addr,
1682                uint32_t         dst_addr,
1683                uint32_t         len32)
1684 {
1685     struct dmae_cmd dmae;
1686     int rc;
1687 
1688     if (!sc->dmae_ready) {
1689         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1690 
1691         if (CHIP_IS_E1(sc)) {
1692             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1693         } else {
1694             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1695         }
1696 
1697         return;
1698     }
1699 
1700     /* set opcode and fixed command fields */
1701     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1702 
1703     /* fill in addresses and len */
1704     dmae.src_addr_lo = U64_LO(dma_addr);
1705     dmae.src_addr_hi = U64_HI(dma_addr);
1706     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1707     dmae.dst_addr_hi = 0;
1708     dmae.len         = len32;
1709 
1710     /* issue the command and wait for completion */
1711     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1712         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1713     }
1714 }
1715 
1716 void
1717 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1718                         bus_addr_t       phys_addr,
1719                         uint32_t         addr,
1720                         uint32_t         len)
1721 {
1722     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1723     int offset = 0;
1724 
1725     while (len > dmae_wr_max) {
1726         bxe_write_dmae(sc,
1727                        (phys_addr + offset), /* src DMA address */
1728                        (addr + offset),      /* dst GRC address */
1729                        dmae_wr_max);
1730         offset += (dmae_wr_max * 4);
1731         len -= dmae_wr_max;
1732     }
1733 
1734     bxe_write_dmae(sc,
1735                    (phys_addr + offset), /* src DMA address */
1736                    (addr + offset),      /* dst GRC address */
1737                    len);
1738 }
1739 
1740 void
1741 bxe_set_ctx_validation(struct bxe_softc   *sc,
1742                        struct eth_context *cxt,
1743                        uint32_t           cid)
1744 {
1745     /* ustorm cxt validation */
1746     cxt->ustorm_ag_context.cdu_usage =
1747         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1748             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1749     /* xcontext validation */
1750     cxt->xstorm_ag_context.cdu_reserved =
1751         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1752             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1753 }
1754 
1755 static void
1756 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1757                             uint8_t          port,
1758                             uint8_t          fw_sb_id,
1759                             uint8_t          sb_index,
1760                             uint8_t          ticks)
1761 {
1762     uint32_t addr =
1763         (BAR_CSTRORM_INTMEM +
1764          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1765 
1766     REG_WR8(sc, addr, ticks);
1767 
1768     BLOGD(sc, DBG_LOAD,
1769           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1770           port, fw_sb_id, sb_index, ticks);
1771 }
1772 
1773 static void
1774 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1775                             uint8_t          port,
1776                             uint16_t         fw_sb_id,
1777                             uint8_t          sb_index,
1778                             uint8_t          disable)
1779 {
1780     uint32_t enable_flag =
1781         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1782     uint32_t addr =
1783         (BAR_CSTRORM_INTMEM +
1784          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1785     uint8_t flags;
1786 
1787     /* clear and set */
1788     flags = REG_RD8(sc, addr);
1789     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1790     flags |= enable_flag;
1791     REG_WR8(sc, addr, flags);
1792 
1793     BLOGD(sc, DBG_LOAD,
1794           "port %d fw_sb_id %d sb_index %d disable %d\n",
1795           port, fw_sb_id, sb_index, disable);
1796 }
1797 
1798 void
1799 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1800                              uint8_t          fw_sb_id,
1801                              uint8_t          sb_index,
1802                              uint8_t          disable,
1803                              uint16_t         usec)
1804 {
1805     int port = SC_PORT(sc);
1806     uint8_t ticks = (usec / 4); /* XXX ??? */
1807 
1808     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1809 
1810     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1811     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1812 }
1813 
1814 void
1815 elink_cb_udelay(struct bxe_softc *sc,
1816                 uint32_t         usecs)
1817 {
1818     DELAY(usecs);
1819 }
1820 
1821 uint32_t
1822 elink_cb_reg_read(struct bxe_softc *sc,
1823                   uint32_t         reg_addr)
1824 {
1825     return (REG_RD(sc, reg_addr));
1826 }
1827 
1828 void
1829 elink_cb_reg_write(struct bxe_softc *sc,
1830                    uint32_t         reg_addr,
1831                    uint32_t         val)
1832 {
1833     REG_WR(sc, reg_addr, val);
1834 }
1835 
1836 void
1837 elink_cb_reg_wb_write(struct bxe_softc *sc,
1838                       uint32_t         offset,
1839                       uint32_t         *wb_write,
1840                       uint16_t         len)
1841 {
1842     REG_WR_DMAE(sc, offset, wb_write, len);
1843 }
1844 
1845 void
1846 elink_cb_reg_wb_read(struct bxe_softc *sc,
1847                      uint32_t         offset,
1848                      uint32_t         *wb_write,
1849                      uint16_t         len)
1850 {
1851     REG_RD_DMAE(sc, offset, wb_write, len);
1852 }
1853 
1854 uint8_t
1855 elink_cb_path_id(struct bxe_softc *sc)
1856 {
1857     return (SC_PATH(sc));
1858 }
1859 
1860 void
1861 elink_cb_event_log(struct bxe_softc     *sc,
1862                    const elink_log_id_t elink_log_id,
1863                    ...)
1864 {
1865     /* XXX */
1866     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1867 }
1868 
1869 static int
1870 bxe_set_spio(struct bxe_softc *sc,
1871              int              spio,
1872              uint32_t         mode)
1873 {
1874     uint32_t spio_reg;
1875 
1876     /* Only 2 SPIOs are configurable */
1877     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1878         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1879         return (-1);
1880     }
1881 
1882     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1883 
1884     /* read SPIO and mask except the float bits */
1885     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1886 
1887     switch (mode) {
1888     case MISC_SPIO_OUTPUT_LOW:
1889         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1890         /* clear FLOAT and set CLR */
1891         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1892         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1893         break;
1894 
1895     case MISC_SPIO_OUTPUT_HIGH:
1896         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1897         /* clear FLOAT and set SET */
1898         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1899         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1900         break;
1901 
1902     case MISC_SPIO_INPUT_HI_Z:
1903         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1904         /* set FLOAT */
1905         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1906         break;
1907 
1908     default:
1909         break;
1910     }
1911 
1912     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1913     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1914 
1915     return (0);
1916 }
1917 
1918 static int
1919 bxe_gpio_read(struct bxe_softc *sc,
1920               int              gpio_num,
1921               uint8_t          port)
1922 {
1923     /* The GPIO should be swapped if swap register is set and active */
1924     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1925                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1926     int gpio_shift = (gpio_num +
1927                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1928     uint32_t gpio_mask = (1 << gpio_shift);
1929     uint32_t gpio_reg;
1930 
1931     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1932         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1933             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1934             gpio_mask);
1935         return (-1);
1936     }
1937 
1938     /* read GPIO value */
1939     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1940 
1941     /* get the requested pin value */
1942     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1943 }
1944 
1945 static int
1946 bxe_gpio_write(struct bxe_softc *sc,
1947                int              gpio_num,
1948                uint32_t         mode,
1949                uint8_t          port)
1950 {
1951     /* The GPIO should be swapped if swap register is set and active */
1952     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1953                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1954     int gpio_shift = (gpio_num +
1955                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1956     uint32_t gpio_mask = (1 << gpio_shift);
1957     uint32_t gpio_reg;
1958 
1959     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1960         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1961             " gpio_shift %d gpio_mask 0x%x\n",
1962             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1963         return (-1);
1964     }
1965 
1966     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1967 
1968     /* read GPIO and mask except the float bits */
1969     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1970 
1971     switch (mode) {
1972     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1973         BLOGD(sc, DBG_PHY,
1974               "Set GPIO %d (shift %d) -> output low\n",
1975               gpio_num, gpio_shift);
1976         /* clear FLOAT and set CLR */
1977         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1978         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1979         break;
1980 
1981     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1982         BLOGD(sc, DBG_PHY,
1983               "Set GPIO %d (shift %d) -> output high\n",
1984               gpio_num, gpio_shift);
1985         /* clear FLOAT and set SET */
1986         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1987         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1988         break;
1989 
1990     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1991         BLOGD(sc, DBG_PHY,
1992               "Set GPIO %d (shift %d) -> input\n",
1993               gpio_num, gpio_shift);
1994         /* set FLOAT */
1995         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1996         break;
1997 
1998     default:
1999         break;
2000     }
2001 
2002     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2003     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2004 
2005     return (0);
2006 }
2007 
2008 static int
2009 bxe_gpio_mult_write(struct bxe_softc *sc,
2010                     uint8_t          pins,
2011                     uint32_t         mode)
2012 {
2013     uint32_t gpio_reg;
2014 
2015     /* any port swapping should be handled by caller */
2016 
2017     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2018 
2019     /* read GPIO and mask except the float bits */
2020     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2021     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2022     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2023     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2024 
2025     switch (mode) {
2026     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2027         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2028         /* set CLR */
2029         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2030         break;
2031 
2032     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2033         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2034         /* set SET */
2035         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2036         break;
2037 
2038     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2039         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2040         /* set FLOAT */
2041         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2042         break;
2043 
2044     default:
2045         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2046             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2047         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2048         return (-1);
2049     }
2050 
2051     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2052     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2053 
2054     return (0);
2055 }
2056 
2057 static int
2058 bxe_gpio_int_write(struct bxe_softc *sc,
2059                    int              gpio_num,
2060                    uint32_t         mode,
2061                    uint8_t          port)
2062 {
2063     /* The GPIO should be swapped if swap register is set and active */
2064     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2065                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2066     int gpio_shift = (gpio_num +
2067                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2068     uint32_t gpio_mask = (1 << gpio_shift);
2069     uint32_t gpio_reg;
2070 
2071     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2072         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2073             " gpio_shift %d gpio_mask 0x%x\n",
2074             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2075         return (-1);
2076     }
2077 
2078     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2079 
2080     /* read GPIO int */
2081     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2082 
2083     switch (mode) {
2084     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2085         BLOGD(sc, DBG_PHY,
2086               "Clear GPIO INT %d (shift %d) -> output low\n",
2087               gpio_num, gpio_shift);
2088         /* clear SET and set CLR */
2089         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2090         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2091         break;
2092 
2093     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2094         BLOGD(sc, DBG_PHY,
2095               "Set GPIO INT %d (shift %d) -> output high\n",
2096               gpio_num, gpio_shift);
2097         /* clear CLR and set SET */
2098         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2099         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2100         break;
2101 
2102     default:
2103         break;
2104     }
2105 
2106     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2107     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2108 
2109     return (0);
2110 }
2111 
2112 uint32_t
2113 elink_cb_gpio_read(struct bxe_softc *sc,
2114                    uint16_t         gpio_num,
2115                    uint8_t          port)
2116 {
2117     return (bxe_gpio_read(sc, gpio_num, port));
2118 }
2119 
2120 uint8_t
2121 elink_cb_gpio_write(struct bxe_softc *sc,
2122                     uint16_t         gpio_num,
2123                     uint8_t          mode, /* 0=low 1=high */
2124                     uint8_t          port)
2125 {
2126     return (bxe_gpio_write(sc, gpio_num, mode, port));
2127 }
2128 
2129 uint8_t
2130 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2131                          uint8_t          pins,
2132                          uint8_t          mode) /* 0=low 1=high */
2133 {
2134     return (bxe_gpio_mult_write(sc, pins, mode));
2135 }
2136 
2137 uint8_t
2138 elink_cb_gpio_int_write(struct bxe_softc *sc,
2139                         uint16_t         gpio_num,
2140                         uint8_t          mode, /* 0=low 1=high */
2141                         uint8_t          port)
2142 {
2143     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2144 }
2145 
2146 void
2147 elink_cb_notify_link_changed(struct bxe_softc *sc)
2148 {
2149     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2150                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2151 }
2152 
2153 /* send the MCP a request, block until there is a reply */
2154 uint32_t
2155 elink_cb_fw_command(struct bxe_softc *sc,
2156                     uint32_t         command,
2157                     uint32_t         param)
2158 {
2159     int mb_idx = SC_FW_MB_IDX(sc);
2160     uint32_t seq;
2161     uint32_t rc = 0;
2162     uint32_t cnt = 1;
2163     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2164 
2165     BXE_FWMB_LOCK(sc);
2166 
2167     seq = ++sc->fw_seq;
2168     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2169     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2170 
2171     BLOGD(sc, DBG_PHY,
2172           "wrote command 0x%08x to FW MB param 0x%08x\n",
2173           (command | seq), param);
2174 
2175     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2176     do {
2177         DELAY(delay * 1000);
2178         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2179     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2180 
2181     BLOGD(sc, DBG_PHY,
2182           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2183           cnt*delay, rc, seq);
2184 
2185     /* is this a reply to our command? */
2186     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2187         rc &= FW_MSG_CODE_MASK;
2188     } else {
2189         /* Ruh-roh! */
2190         BLOGE(sc, "FW failed to respond!\n");
2191         // XXX bxe_fw_dump(sc);
2192         rc = 0;
2193     }
2194 
2195     BXE_FWMB_UNLOCK(sc);
2196     return (rc);
2197 }
2198 
2199 static uint32_t
2200 bxe_fw_command(struct bxe_softc *sc,
2201                uint32_t         command,
2202                uint32_t         param)
2203 {
2204     return (elink_cb_fw_command(sc, command, param));
2205 }
2206 
2207 static void
2208 __storm_memset_dma_mapping(struct bxe_softc *sc,
2209                            uint32_t         addr,
2210                            bus_addr_t       mapping)
2211 {
2212     REG_WR(sc, addr, U64_LO(mapping));
2213     REG_WR(sc, (addr + 4), U64_HI(mapping));
2214 }
2215 
2216 static void
2217 storm_memset_spq_addr(struct bxe_softc *sc,
2218                       bus_addr_t       mapping,
2219                       uint16_t         abs_fid)
2220 {
2221     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2222                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2223     __storm_memset_dma_mapping(sc, addr, mapping);
2224 }
2225 
2226 static void
2227 storm_memset_vf_to_pf(struct bxe_softc *sc,
2228                       uint16_t         abs_fid,
2229                       uint16_t         pf_id)
2230 {
2231     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2232     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2233     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2234     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2235 }
2236 
2237 static void
2238 storm_memset_func_en(struct bxe_softc *sc,
2239                      uint16_t         abs_fid,
2240                      uint8_t          enable)
2241 {
2242     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2243     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2244     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2245     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2246 }
2247 
2248 static void
2249 storm_memset_eq_data(struct bxe_softc       *sc,
2250                      struct event_ring_data *eq_data,
2251                      uint16_t               pfid)
2252 {
2253     uint32_t addr;
2254     size_t size;
2255 
2256     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2257     size = sizeof(struct event_ring_data);
2258     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2259 }
2260 
2261 static void
2262 storm_memset_eq_prod(struct bxe_softc *sc,
2263                      uint16_t         eq_prod,
2264                      uint16_t         pfid)
2265 {
2266     uint32_t addr = (BAR_CSTRORM_INTMEM +
2267                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2268     REG_WR16(sc, addr, eq_prod);
2269 }
2270 
2271 /*
2272  * Post a slowpath command.
2273  *
2274  * A slowpath command is used to propagate a configuration change through
2275  * the controller in a controlled manner, allowing each STORM processor and
2276  * other H/W blocks to phase in the change.  The commands sent on the
2277  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2278  * completion of the ramrod will occur in different ways.  Here's a
2279  * breakdown of ramrods and how they complete:
2280  *
2281  * RAMROD_CMD_ID_ETH_PORT_SETUP
2282  *   Used to setup the leading connection on a port.  Completes on the
2283  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2284  *
2285  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2286  *   Used to setup an additional connection on a port.  Completes on the
2287  *   RCQ of the multi-queue/RSS connection being initialized.
2288  *
2289  * RAMROD_CMD_ID_ETH_STAT_QUERY
2290  *   Used to force the storm processors to update the statistics database
2291  *   in host memory.  This ramrod is send on the leading connection CID and
2292  *   completes as an index increment of the CSTORM on the default status
2293  *   block.
2294  *
2295  * RAMROD_CMD_ID_ETH_UPDATE
2296  *   Used to update the state of the leading connection, usually to udpate
2297  *   the RSS indirection table.  Completes on the RCQ of the leading
2298  *   connection. (Not currently used under FreeBSD until OS support becomes
2299  *   available.)
2300  *
2301  * RAMROD_CMD_ID_ETH_HALT
2302  *   Used when tearing down a connection prior to driver unload.  Completes
2303  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2304  *   use this on the leading connection.
2305  *
2306  * RAMROD_CMD_ID_ETH_SET_MAC
2307  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2308  *   the RCQ of the leading connection.
2309  *
2310  * RAMROD_CMD_ID_ETH_CFC_DEL
2311  *   Used when tearing down a conneciton prior to driver unload.  Completes
2312  *   on the RCQ of the leading connection (since the current connection
2313  *   has been completely removed from controller memory).
2314  *
2315  * RAMROD_CMD_ID_ETH_PORT_DEL
2316  *   Used to tear down the leading connection prior to driver unload,
2317  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2318  *   default status block.
2319  *
2320  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2321  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2322  *   RSS connection that is being offloaded.  (Not currently used under
2323  *   FreeBSD.)
2324  *
2325  * There can only be one command pending per function.
2326  *
2327  * Returns:
2328  *   0 = Success, !0 = Failure.
2329  */
2330 
2331 /* must be called under the spq lock */
2332 static inline
2333 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2334 {
2335     struct eth_spe *next_spe = sc->spq_prod_bd;
2336 
2337     if (sc->spq_prod_bd == sc->spq_last_bd) {
2338         /* wrap back to the first eth_spq */
2339         sc->spq_prod_bd = sc->spq;
2340         sc->spq_prod_idx = 0;
2341     } else {
2342         sc->spq_prod_bd++;
2343         sc->spq_prod_idx++;
2344     }
2345 
2346     return (next_spe);
2347 }
2348 
2349 /* must be called under the spq lock */
2350 static inline
2351 void bxe_sp_prod_update(struct bxe_softc *sc)
2352 {
2353     int func = SC_FUNC(sc);
2354 
2355     /*
2356      * Make sure that BD data is updated before writing the producer.
2357      * BD data is written to the memory, the producer is read from the
2358      * memory, thus we need a full memory barrier to ensure the ordering.
2359      */
2360     mb();
2361 
2362     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2363              sc->spq_prod_idx);
2364 
2365     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2366                       BUS_SPACE_BARRIER_WRITE);
2367 }
2368 
2369 /**
2370  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2371  *
2372  * @cmd:      command to check
2373  * @cmd_type: command type
2374  */
2375 static inline
2376 int bxe_is_contextless_ramrod(int cmd,
2377                               int cmd_type)
2378 {
2379     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2380         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2381         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2382         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2383         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2384         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2385         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2386         return (TRUE);
2387     } else {
2388         return (FALSE);
2389     }
2390 }
2391 
2392 /**
2393  * bxe_sp_post - place a single command on an SP ring
2394  *
2395  * @sc:         driver handle
2396  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2397  * @cid:        SW CID the command is related to
2398  * @data_hi:    command private data address (high 32 bits)
2399  * @data_lo:    command private data address (low 32 bits)
2400  * @cmd_type:   command type (e.g. NONE, ETH)
2401  *
2402  * SP data is handled as if it's always an address pair, thus data fields are
2403  * not swapped to little endian in upper functions. Instead this function swaps
2404  * data as if it's two uint32 fields.
2405  */
2406 int
2407 bxe_sp_post(struct bxe_softc *sc,
2408             int              command,
2409             int              cid,
2410             uint32_t         data_hi,
2411             uint32_t         data_lo,
2412             int              cmd_type)
2413 {
2414     struct eth_spe *spe;
2415     uint16_t type;
2416     int common;
2417 
2418     common = bxe_is_contextless_ramrod(command, cmd_type);
2419 
2420     BXE_SP_LOCK(sc);
2421 
2422     if (common) {
2423         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2424             BLOGE(sc, "EQ ring is full!\n");
2425             BXE_SP_UNLOCK(sc);
2426             return (-1);
2427         }
2428     } else {
2429         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2430             BLOGE(sc, "SPQ ring is full!\n");
2431             BXE_SP_UNLOCK(sc);
2432             return (-1);
2433         }
2434     }
2435 
2436     spe = bxe_sp_get_next(sc);
2437 
2438     /* CID needs port number to be encoded int it */
2439     spe->hdr.conn_and_cmd_data =
2440         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2441 
2442     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2443 
2444     /* TBD: Check if it works for VFs */
2445     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2446              SPE_HDR_T_FUNCTION_ID);
2447 
2448     spe->hdr.type = htole16(type);
2449 
2450     spe->data.update_data_addr.hi = htole32(data_hi);
2451     spe->data.update_data_addr.lo = htole32(data_lo);
2452 
2453     /*
2454      * It's ok if the actual decrement is issued towards the memory
2455      * somewhere between the lock and unlock. Thus no more explict
2456      * memory barrier is needed.
2457      */
2458     if (common) {
2459         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2460     } else {
2461         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2462     }
2463 
2464     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2465     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2466           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2467     BLOGD(sc, DBG_SP,
2468           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2469           sc->spq_prod_idx,
2470           (uint32_t)U64_HI(sc->spq_dma.paddr),
2471           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2472           command,
2473           common,
2474           HW_CID(sc, cid),
2475           data_hi,
2476           data_lo,
2477           type,
2478           atomic_load_acq_long(&sc->cq_spq_left),
2479           atomic_load_acq_long(&sc->eq_spq_left));
2480 
2481     bxe_sp_prod_update(sc);
2482 
2483     BXE_SP_UNLOCK(sc);
2484     return (0);
2485 }
2486 
2487 /**
2488  * bxe_debug_print_ind_table - prints the indirection table configuration.
2489  *
2490  * @sc: driver hanlde
2491  * @p:  pointer to rss configuration
2492  */
2493 
2494 /*
2495  * FreeBSD Device probe function.
2496  *
2497  * Compares the device found to the driver's list of supported devices and
2498  * reports back to the bsd loader whether this is the right driver for the device.
2499  * This is the driver entry function called from the "kldload" command.
2500  *
2501  * Returns:
2502  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2503  */
2504 static int
2505 bxe_probe(device_t dev)
2506 {
2507     struct bxe_device_type *t;
2508     char *descbuf;
2509     uint16_t did, sdid, svid, vid;
2510 
2511     /* Find our device structure */
2512     t = bxe_devs;
2513 
2514     /* Get the data for the device to be probed. */
2515     vid  = pci_get_vendor(dev);
2516     did  = pci_get_device(dev);
2517     svid = pci_get_subvendor(dev);
2518     sdid = pci_get_subdevice(dev);
2519 
2520     /* Look through the list of known devices for a match. */
2521     while (t->bxe_name != NULL) {
2522         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2523             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2524             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2525             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2526             if (descbuf == NULL)
2527                 return (ENOMEM);
2528 
2529             /* Print out the device identity. */
2530             snprintf(descbuf, BXE_DEVDESC_MAX,
2531                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2532                      (((pci_read_config(dev, PCIR_REVID, 4) &
2533                         0xf0) >> 4) + 'A'),
2534                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2535                      BXE_DRIVER_VERSION);
2536 
2537             device_set_desc_copy(dev, descbuf);
2538             free(descbuf, M_TEMP);
2539             return (BUS_PROBE_DEFAULT);
2540         }
2541         t++;
2542     }
2543 
2544     return (ENXIO);
2545 }
2546 
2547 static void
2548 bxe_init_mutexes(struct bxe_softc *sc)
2549 {
2550 #ifdef BXE_CORE_LOCK_SX
2551     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2552              "bxe%d_core_lock", sc->unit);
2553     sx_init(&sc->core_sx, sc->core_sx_name);
2554 #else
2555     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2556              "bxe%d_core_lock", sc->unit);
2557     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2558 #endif
2559 
2560     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2561              "bxe%d_sp_lock", sc->unit);
2562     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2563 
2564     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2565              "bxe%d_dmae_lock", sc->unit);
2566     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2567 
2568     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2569              "bxe%d_phy_lock", sc->unit);
2570     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2571 
2572     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2573              "bxe%d_fwmb_lock", sc->unit);
2574     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2575 
2576     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2577              "bxe%d_print_lock", sc->unit);
2578     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2579 
2580     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2581              "bxe%d_stats_lock", sc->unit);
2582     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2583 
2584     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2585              "bxe%d_mcast_lock", sc->unit);
2586     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2587 }
2588 
2589 static void
2590 bxe_release_mutexes(struct bxe_softc *sc)
2591 {
2592 #ifdef BXE_CORE_LOCK_SX
2593     sx_destroy(&sc->core_sx);
2594 #else
2595     if (mtx_initialized(&sc->core_mtx)) {
2596         mtx_destroy(&sc->core_mtx);
2597     }
2598 #endif
2599 
2600     if (mtx_initialized(&sc->sp_mtx)) {
2601         mtx_destroy(&sc->sp_mtx);
2602     }
2603 
2604     if (mtx_initialized(&sc->dmae_mtx)) {
2605         mtx_destroy(&sc->dmae_mtx);
2606     }
2607 
2608     if (mtx_initialized(&sc->port.phy_mtx)) {
2609         mtx_destroy(&sc->port.phy_mtx);
2610     }
2611 
2612     if (mtx_initialized(&sc->fwmb_mtx)) {
2613         mtx_destroy(&sc->fwmb_mtx);
2614     }
2615 
2616     if (mtx_initialized(&sc->print_mtx)) {
2617         mtx_destroy(&sc->print_mtx);
2618     }
2619 
2620     if (mtx_initialized(&sc->stats_mtx)) {
2621         mtx_destroy(&sc->stats_mtx);
2622     }
2623 
2624     if (mtx_initialized(&sc->mcast_mtx)) {
2625         mtx_destroy(&sc->mcast_mtx);
2626     }
2627 }
2628 
2629 static void
2630 bxe_tx_disable(struct bxe_softc* sc)
2631 {
2632     if_t ifp = sc->ifp;
2633 
2634     /* tell the stack the driver is stopped and TX queue is full */
2635     if (ifp !=  NULL) {
2636         if_setdrvflags(ifp, 0);
2637     }
2638 }
2639 
2640 static void
2641 bxe_drv_pulse(struct bxe_softc *sc)
2642 {
2643     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2644              sc->fw_drv_pulse_wr_seq);
2645 }
2646 
2647 static inline uint16_t
2648 bxe_tx_avail(struct bxe_softc *sc,
2649              struct bxe_fastpath *fp)
2650 {
2651     int16_t  used;
2652     uint16_t prod;
2653     uint16_t cons;
2654 
2655     prod = fp->tx_bd_prod;
2656     cons = fp->tx_bd_cons;
2657 
2658     used = SUB_S16(prod, cons);
2659 
2660     return (int16_t)(sc->tx_ring_size) - used;
2661 }
2662 
2663 static inline int
2664 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2665 {
2666     uint16_t hw_cons;
2667 
2668     mb(); /* status block fields can change */
2669     hw_cons = le16toh(*fp->tx_cons_sb);
2670     return (hw_cons != fp->tx_pkt_cons);
2671 }
2672 
2673 static inline uint8_t
2674 bxe_has_tx_work(struct bxe_fastpath *fp)
2675 {
2676     /* expand this for multi-cos if ever supported */
2677     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2678 }
2679 
2680 static inline int
2681 bxe_has_rx_work(struct bxe_fastpath *fp)
2682 {
2683     uint16_t rx_cq_cons_sb;
2684 
2685     mb(); /* status block fields can change */
2686     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2687     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2688         rx_cq_cons_sb++;
2689     return (fp->rx_cq_cons != rx_cq_cons_sb);
2690 }
2691 
2692 static void
2693 bxe_sp_event(struct bxe_softc    *sc,
2694              struct bxe_fastpath *fp,
2695              union eth_rx_cqe    *rr_cqe)
2696 {
2697     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2698     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2699     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2700     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2701 
2702     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2703           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2704 
2705     switch (command) {
2706     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2707         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2708         drv_cmd = ECORE_Q_CMD_UPDATE;
2709         break;
2710 
2711     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2712         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2713         drv_cmd = ECORE_Q_CMD_SETUP;
2714         break;
2715 
2716     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2717         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2718         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2719         break;
2720 
2721     case (RAMROD_CMD_ID_ETH_HALT):
2722         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2723         drv_cmd = ECORE_Q_CMD_HALT;
2724         break;
2725 
2726     case (RAMROD_CMD_ID_ETH_TERMINATE):
2727         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2728         drv_cmd = ECORE_Q_CMD_TERMINATE;
2729         break;
2730 
2731     case (RAMROD_CMD_ID_ETH_EMPTY):
2732         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2733         drv_cmd = ECORE_Q_CMD_EMPTY;
2734         break;
2735 
2736     default:
2737         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2738               command, fp->index);
2739         return;
2740     }
2741 
2742     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2743         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2744         /*
2745          * q_obj->complete_cmd() failure means that this was
2746          * an unexpected completion.
2747          *
2748          * In this case we don't want to increase the sc->spq_left
2749          * because apparently we haven't sent this command the first
2750          * place.
2751          */
2752         // bxe_panic(sc, ("Unexpected SP completion\n"));
2753         return;
2754     }
2755 
2756     atomic_add_acq_long(&sc->cq_spq_left, 1);
2757 
2758     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2759           atomic_load_acq_long(&sc->cq_spq_left));
2760 }
2761 
2762 /*
2763  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2764  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2765  * the current aggregation queue as in-progress.
2766  */
2767 static void
2768 bxe_tpa_start(struct bxe_softc            *sc,
2769               struct bxe_fastpath         *fp,
2770               uint16_t                    queue,
2771               uint16_t                    cons,
2772               uint16_t                    prod,
2773               struct eth_fast_path_rx_cqe *cqe)
2774 {
2775     struct bxe_sw_rx_bd tmp_bd;
2776     struct bxe_sw_rx_bd *rx_buf;
2777     struct eth_rx_bd *rx_bd;
2778     int max_agg_queues;
2779     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2780     uint16_t index;
2781 
2782     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2783                        "cons=%d prod=%d\n",
2784           fp->index, queue, cons, prod);
2785 
2786     max_agg_queues = MAX_AGG_QS(sc);
2787 
2788     KASSERT((queue < max_agg_queues),
2789             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2790              fp->index, queue, max_agg_queues));
2791 
2792     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2793             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2794              fp->index, queue));
2795 
2796     /* copy the existing mbuf and mapping from the TPA pool */
2797     tmp_bd = tpa_info->bd;
2798 
2799     if (tmp_bd.m == NULL) {
2800         uint32_t *tmp;
2801 
2802         tmp = (uint32_t *)cqe;
2803 
2804         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2805               fp->index, queue, cons, prod);
2806         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2807             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2808 
2809         /* XXX Error handling? */
2810         return;
2811     }
2812 
2813     /* change the TPA queue to the start state */
2814     tpa_info->state            = BXE_TPA_STATE_START;
2815     tpa_info->placement_offset = cqe->placement_offset;
2816     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2817     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2818     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2819 
2820     fp->rx_tpa_queue_used |= (1 << queue);
2821 
2822     /*
2823      * If all the buffer descriptors are filled with mbufs then fill in
2824      * the current consumer index with a new BD. Else if a maximum Rx
2825      * buffer limit is imposed then fill in the next producer index.
2826      */
2827     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2828                 prod : cons;
2829 
2830     /* move the received mbuf and mapping to TPA pool */
2831     tpa_info->bd = fp->rx_mbuf_chain[cons];
2832 
2833     /* release any existing RX BD mbuf mappings */
2834     if (cons != index) {
2835         rx_buf = &fp->rx_mbuf_chain[cons];
2836 
2837         if (rx_buf->m_map != NULL) {
2838             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2839                             BUS_DMASYNC_POSTREAD);
2840             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2841         }
2842 
2843         /*
2844          * We get here when the maximum number of rx buffers is less than
2845          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2846          * it out here without concern of a memory leak.
2847          */
2848         fp->rx_mbuf_chain[cons].m = NULL;
2849     }
2850 
2851     /* update the Rx SW BD with the mbuf info from the TPA pool */
2852     fp->rx_mbuf_chain[index] = tmp_bd;
2853 
2854     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2855     rx_bd = &fp->rx_chain[index];
2856     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2857     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2858 }
2859 
2860 /*
2861  * When a TPA aggregation is completed, loop through the individual mbufs
2862  * of the aggregation, combining them into a single mbuf which will be sent
2863  * up the stack. Refill all freed SGEs with mbufs as we go along.
2864  */
2865 static int
2866 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2867                    struct bxe_fastpath       *fp,
2868                    struct bxe_sw_tpa_info    *tpa_info,
2869                    uint16_t                  queue,
2870                    uint16_t                  pages,
2871                    struct mbuf               *m,
2872 			       struct eth_end_agg_rx_cqe *cqe,
2873                    uint16_t                  cqe_idx)
2874 {
2875     struct mbuf *m_frag;
2876     uint32_t frag_len, frag_size, i;
2877     uint16_t sge_idx;
2878     int rc = 0;
2879     int j;
2880 
2881     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2882 
2883     BLOGD(sc, DBG_LRO,
2884           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2885           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2886 
2887     /* make sure the aggregated frame is not too big to handle */
2888     if (pages > 8 * PAGES_PER_SGE) {
2889 
2890         uint32_t *tmp = (uint32_t *)cqe;
2891 
2892         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2893                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2894               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2895               tpa_info->len_on_bd, frag_size);
2896 
2897         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2898             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7));
2899 
2900         bxe_panic(sc, ("sge page count error\n"));
2901         return (EINVAL);
2902     }
2903 
2904     /*
2905      * Scan through the scatter gather list pulling individual mbufs into a
2906      * single mbuf for the host stack.
2907      */
2908     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2909         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2910 
2911         /*
2912          * Firmware gives the indices of the SGE as if the ring is an array
2913          * (meaning that the "next" element will consume 2 indices).
2914          */
2915         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2916 
2917         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2918                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2919               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2920 
2921         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2922 
2923         /* allocate a new mbuf for the SGE */
2924         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2925         if (rc) {
2926             /* Leave all remaining SGEs in the ring! */
2927             return (rc);
2928         }
2929 
2930         /* update the fragment length */
2931         m_frag->m_len = frag_len;
2932 
2933         /* concatenate the fragment to the head mbuf */
2934         m_cat(m, m_frag);
2935         fp->eth_q_stats.mbuf_alloc_sge--;
2936 
2937         /* update the TPA mbuf size and remaining fragment size */
2938         m->m_pkthdr.len += frag_len;
2939         frag_size -= frag_len;
2940     }
2941 
2942     BLOGD(sc, DBG_LRO,
2943           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2944           fp->index, queue, frag_size);
2945 
2946     return (rc);
2947 }
2948 
2949 static inline void
2950 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2951 {
2952     int i, j;
2953 
2954     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2955         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2956 
2957         for (j = 0; j < 2; j++) {
2958             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2959             idx--;
2960         }
2961     }
2962 }
2963 
2964 static inline void
2965 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2966 {
2967     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2968     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2969 
2970     /*
2971      * Clear the two last indices in the page to 1. These are the indices that
2972      * correspond to the "next" element, hence will never be indicated and
2973      * should be removed from the calculations.
2974      */
2975     bxe_clear_sge_mask_next_elems(fp);
2976 }
2977 
2978 static inline void
2979 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2980                         uint16_t            idx)
2981 {
2982     uint16_t last_max = fp->last_max_sge;
2983 
2984     if (SUB_S16(idx, last_max) > 0) {
2985         fp->last_max_sge = idx;
2986     }
2987 }
2988 
2989 static inline void
2990 bxe_update_sge_prod(struct bxe_softc          *sc,
2991                     struct bxe_fastpath       *fp,
2992                     uint16_t                  sge_len,
2993                     union eth_sgl_or_raw_data *cqe)
2994 {
2995     uint16_t last_max, last_elem, first_elem;
2996     uint16_t delta = 0;
2997     uint16_t i;
2998 
2999     if (!sge_len) {
3000         return;
3001     }
3002 
3003     /* first mark all used pages */
3004     for (i = 0; i < sge_len; i++) {
3005         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3006                             RX_SGE(le16toh(cqe->sgl[i])));
3007     }
3008 
3009     BLOGD(sc, DBG_LRO,
3010           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3011           fp->index, sge_len - 1,
3012           le16toh(cqe->sgl[sge_len - 1]));
3013 
3014     /* assume that the last SGE index is the biggest */
3015     bxe_update_last_max_sge(fp,
3016                             le16toh(cqe->sgl[sge_len - 1]));
3017 
3018     last_max = RX_SGE(fp->last_max_sge);
3019     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3020     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3021 
3022     /* if ring is not full */
3023     if (last_elem + 1 != first_elem) {
3024         last_elem++;
3025     }
3026 
3027     /* now update the prod */
3028     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3029         if (__predict_true(fp->sge_mask[i])) {
3030             break;
3031         }
3032 
3033         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3034         delta += BIT_VEC64_ELEM_SZ;
3035     }
3036 
3037     if (delta > 0) {
3038         fp->rx_sge_prod += delta;
3039         /* clear page-end entries */
3040         bxe_clear_sge_mask_next_elems(fp);
3041     }
3042 
3043     BLOGD(sc, DBG_LRO,
3044           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3045           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3046 }
3047 
3048 /*
3049  * The aggregation on the current TPA queue has completed. Pull the individual
3050  * mbuf fragments together into a single mbuf, perform all necessary checksum
3051  * calculations, and send the resuting mbuf to the stack.
3052  */
3053 static void
3054 bxe_tpa_stop(struct bxe_softc          *sc,
3055              struct bxe_fastpath       *fp,
3056              struct bxe_sw_tpa_info    *tpa_info,
3057              uint16_t                  queue,
3058              uint16_t                  pages,
3059 			 struct eth_end_agg_rx_cqe *cqe,
3060              uint16_t                  cqe_idx)
3061 {
3062     if_t ifp = sc->ifp;
3063     struct mbuf *m;
3064     int rc = 0;
3065 
3066     BLOGD(sc, DBG_LRO,
3067           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3068           fp->index, queue, tpa_info->placement_offset,
3069           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3070 
3071     m = tpa_info->bd.m;
3072 
3073     /* allocate a replacement before modifying existing mbuf */
3074     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3075     if (rc) {
3076         /* drop the frame and log an error */
3077         fp->eth_q_stats.rx_soft_errors++;
3078         goto bxe_tpa_stop_exit;
3079     }
3080 
3081     /* we have a replacement, fixup the current mbuf */
3082     m_adj(m, tpa_info->placement_offset);
3083     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3084 
3085     /* mark the checksums valid (taken care of by the firmware) */
3086     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3087     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3088     m->m_pkthdr.csum_data = 0xffff;
3089     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3090                                CSUM_IP_VALID   |
3091                                CSUM_DATA_VALID |
3092                                CSUM_PSEUDO_HDR);
3093 
3094     /* aggregate all of the SGEs into a single mbuf */
3095     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3096     if (rc) {
3097         /* drop the packet and log an error */
3098         fp->eth_q_stats.rx_soft_errors++;
3099         m_freem(m);
3100     } else {
3101         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3102             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3103             m->m_flags |= M_VLANTAG;
3104         }
3105 
3106         /* assign packet to this interface interface */
3107         if_setrcvif(m, ifp);
3108 
3109 #if __FreeBSD_version >= 800000
3110         /* specify what RSS queue was used for this flow */
3111         m->m_pkthdr.flowid = fp->index;
3112         BXE_SET_FLOWID(m);
3113 #endif
3114 
3115         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3116         fp->eth_q_stats.rx_tpa_pkts++;
3117 
3118         /* pass the frame to the stack */
3119         if_input(ifp, m);
3120     }
3121 
3122     /* we passed an mbuf up the stack or dropped the frame */
3123     fp->eth_q_stats.mbuf_alloc_tpa--;
3124 
3125 bxe_tpa_stop_exit:
3126 
3127     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3128     fp->rx_tpa_queue_used &= ~(1 << queue);
3129 }
3130 
3131 static uint8_t
3132 bxe_service_rxsgl(
3133                  struct bxe_fastpath *fp,
3134                  uint16_t len,
3135                  uint16_t lenonbd,
3136                  struct mbuf *m,
3137                  struct eth_fast_path_rx_cqe *cqe_fp)
3138 {
3139     struct mbuf *m_frag;
3140     uint16_t frags, frag_len;
3141     uint16_t sge_idx = 0;
3142     uint16_t j;
3143     uint8_t i, rc = 0;
3144     uint32_t frag_size;
3145 
3146     /* adjust the mbuf */
3147     m->m_len = lenonbd;
3148 
3149     frag_size =  len - lenonbd;
3150     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3151 
3152     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3153         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3154 
3155         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3156         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3157         m_frag->m_len = frag_len;
3158 
3159        /* allocate a new mbuf for the SGE */
3160         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3161         if (rc) {
3162             /* Leave all remaining SGEs in the ring! */
3163             return (rc);
3164         }
3165         fp->eth_q_stats.mbuf_alloc_sge--;
3166 
3167         /* concatenate the fragment to the head mbuf */
3168         m_cat(m, m_frag);
3169 
3170         frag_size -= frag_len;
3171     }
3172 
3173     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3174 
3175     return rc;
3176 }
3177 
3178 static uint8_t
3179 bxe_rxeof(struct bxe_softc    *sc,
3180           struct bxe_fastpath *fp)
3181 {
3182     if_t ifp = sc->ifp;
3183     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3184     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3185     int rx_pkts = 0;
3186     int rc = 0;
3187 
3188     BXE_FP_RX_LOCK(fp);
3189 
3190     /* CQ "next element" is of the size of the regular element */
3191     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3192     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3193         hw_cq_cons++;
3194     }
3195 
3196     bd_cons = fp->rx_bd_cons;
3197     bd_prod = fp->rx_bd_prod;
3198     bd_prod_fw = bd_prod;
3199     sw_cq_cons = fp->rx_cq_cons;
3200     sw_cq_prod = fp->rx_cq_prod;
3201 
3202     /*
3203      * Memory barrier necessary as speculative reads of the rx
3204      * buffer can be ahead of the index in the status block
3205      */
3206     rmb();
3207 
3208     BLOGD(sc, DBG_RX,
3209           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3210           fp->index, hw_cq_cons, sw_cq_cons);
3211 
3212     while (sw_cq_cons != hw_cq_cons) {
3213         struct bxe_sw_rx_bd *rx_buf = NULL;
3214         union eth_rx_cqe *cqe;
3215         struct eth_fast_path_rx_cqe *cqe_fp;
3216         uint8_t cqe_fp_flags;
3217         enum eth_rx_cqe_type cqe_fp_type;
3218         uint16_t len, lenonbd,  pad;
3219         struct mbuf *m = NULL;
3220 
3221         comp_ring_cons = RCQ(sw_cq_cons);
3222         bd_prod = RX_BD(bd_prod);
3223         bd_cons = RX_BD(bd_cons);
3224 
3225         cqe          = &fp->rcq_chain[comp_ring_cons];
3226         cqe_fp       = &cqe->fast_path_cqe;
3227         cqe_fp_flags = cqe_fp->type_error_flags;
3228         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3229 
3230         BLOGD(sc, DBG_RX,
3231               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3232               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3233               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3234               fp->index,
3235               hw_cq_cons,
3236               sw_cq_cons,
3237               bd_prod,
3238               bd_cons,
3239               CQE_TYPE(cqe_fp_flags),
3240               cqe_fp_flags,
3241               cqe_fp->status_flags,
3242               le32toh(cqe_fp->rss_hash_result),
3243               le16toh(cqe_fp->vlan_tag),
3244               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3245               le16toh(cqe_fp->len_on_bd));
3246 
3247         /* is this a slowpath msg? */
3248         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3249             bxe_sp_event(sc, fp, cqe);
3250             goto next_cqe;
3251         }
3252 
3253         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3254 
3255         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3256             struct bxe_sw_tpa_info *tpa_info;
3257             uint16_t frag_size, pages;
3258             uint8_t queue;
3259 
3260             if (CQE_TYPE_START(cqe_fp_type)) {
3261                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3262                               bd_cons, bd_prod, cqe_fp);
3263                 m = NULL; /* packet not ready yet */
3264                 goto next_rx;
3265             }
3266 
3267             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3268                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3269 
3270             queue = cqe->end_agg_cqe.queue_index;
3271             tpa_info = &fp->rx_tpa_info[queue];
3272 
3273             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3274                   fp->index, queue);
3275 
3276             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3277                          tpa_info->len_on_bd);
3278             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3279 
3280             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3281                          &cqe->end_agg_cqe, comp_ring_cons);
3282 
3283             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3284 
3285             goto next_cqe;
3286         }
3287 
3288         /* non TPA */
3289 
3290         /* is this an error packet? */
3291         if (__predict_false(cqe_fp_flags &
3292                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3293             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3294             fp->eth_q_stats.rx_soft_errors++;
3295             goto next_rx;
3296         }
3297 
3298         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3299         lenonbd = le16toh(cqe_fp->len_on_bd);
3300         pad = cqe_fp->placement_offset;
3301 
3302         m = rx_buf->m;
3303 
3304         if (__predict_false(m == NULL)) {
3305             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3306                   bd_cons, fp->index);
3307             goto next_rx;
3308         }
3309 
3310         /* XXX double copy if packet length under a threshold */
3311 
3312         /*
3313          * If all the buffer descriptors are filled with mbufs then fill in
3314          * the current consumer index with a new BD. Else if a maximum Rx
3315          * buffer limit is imposed then fill in the next producer index.
3316          */
3317         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3318                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3319                                       bd_prod : bd_cons);
3320         if (rc != 0) {
3321 
3322             /* we simply reuse the received mbuf and don't post it to the stack */
3323             m = NULL;
3324 
3325             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3326                   fp->index, rc);
3327             fp->eth_q_stats.rx_soft_errors++;
3328 
3329             if (sc->max_rx_bufs != RX_BD_USABLE) {
3330                 /* copy this consumer index to the producer index */
3331                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3332                        sizeof(struct bxe_sw_rx_bd));
3333                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3334             }
3335 
3336             goto next_rx;
3337         }
3338 
3339         /* current mbuf was detached from the bd */
3340         fp->eth_q_stats.mbuf_alloc_rx--;
3341 
3342         /* we allocated a replacement mbuf, fixup the current one */
3343         m_adj(m, pad);
3344         m->m_pkthdr.len = m->m_len = len;
3345 
3346         if ((len > 60) && (len > lenonbd)) {
3347             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3348             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3349             if (rc)
3350                 break;
3351             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3352         } else if (lenonbd < len) {
3353             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3354         }
3355 
3356         /* assign packet to this interface interface */
3357 	if_setrcvif(m, ifp);
3358 
3359         /* assume no hardware checksum has complated */
3360         m->m_pkthdr.csum_flags = 0;
3361 
3362         /* validate checksum if offload enabled */
3363         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3364             /* check for a valid IP frame */
3365             if (!(cqe->fast_path_cqe.status_flags &
3366                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3367                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3368                 if (__predict_false(cqe_fp_flags &
3369                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3370                     fp->eth_q_stats.rx_hw_csum_errors++;
3371                 } else {
3372                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3373                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3374                 }
3375             }
3376 
3377             /* check for a valid TCP/UDP frame */
3378             if (!(cqe->fast_path_cqe.status_flags &
3379                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3380                 if (__predict_false(cqe_fp_flags &
3381                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3382                     fp->eth_q_stats.rx_hw_csum_errors++;
3383                 } else {
3384                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3385                     m->m_pkthdr.csum_data = 0xFFFF;
3386                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3387                                                CSUM_PSEUDO_HDR);
3388                 }
3389             }
3390         }
3391 
3392         /* if there is a VLAN tag then flag that info */
3393         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3394             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3395             m->m_flags |= M_VLANTAG;
3396         }
3397 
3398 #if __FreeBSD_version >= 800000
3399         /* specify what RSS queue was used for this flow */
3400         m->m_pkthdr.flowid = fp->index;
3401         BXE_SET_FLOWID(m);
3402 #endif
3403 
3404 next_rx:
3405 
3406         bd_cons    = RX_BD_NEXT(bd_cons);
3407         bd_prod    = RX_BD_NEXT(bd_prod);
3408         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3409 
3410         /* pass the frame to the stack */
3411         if (__predict_true(m != NULL)) {
3412             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3413             rx_pkts++;
3414             if_input(ifp, m);
3415         }
3416 
3417 next_cqe:
3418 
3419         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3420         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3421 
3422         /* limit spinning on the queue */
3423         if (rc != 0)
3424             break;
3425 
3426         if (rx_pkts == sc->rx_budget) {
3427             fp->eth_q_stats.rx_budget_reached++;
3428             break;
3429         }
3430     } /* while work to do */
3431 
3432     fp->rx_bd_cons = bd_cons;
3433     fp->rx_bd_prod = bd_prod_fw;
3434     fp->rx_cq_cons = sw_cq_cons;
3435     fp->rx_cq_prod = sw_cq_prod;
3436 
3437     /* Update producers */
3438     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3439 
3440     fp->eth_q_stats.rx_pkts += rx_pkts;
3441     fp->eth_q_stats.rx_calls++;
3442 
3443     BXE_FP_RX_UNLOCK(fp);
3444 
3445     return (sw_cq_cons != hw_cq_cons);
3446 }
3447 
3448 static uint16_t
3449 bxe_free_tx_pkt(struct bxe_softc    *sc,
3450                 struct bxe_fastpath *fp,
3451                 uint16_t            idx)
3452 {
3453     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3454     struct eth_tx_start_bd *tx_start_bd;
3455     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3456     uint16_t new_cons;
3457     int nbd;
3458 
3459     /* unmap the mbuf from non-paged memory */
3460     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3461 
3462     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3463     nbd = le16toh(tx_start_bd->nbd) - 1;
3464 
3465     new_cons = (tx_buf->first_bd + nbd);
3466 
3467     /* free the mbuf */
3468     if (__predict_true(tx_buf->m != NULL)) {
3469         m_freem(tx_buf->m);
3470         fp->eth_q_stats.mbuf_alloc_tx--;
3471     } else {
3472         fp->eth_q_stats.tx_chain_lost_mbuf++;
3473     }
3474 
3475     tx_buf->m = NULL;
3476     tx_buf->first_bd = 0;
3477 
3478     return (new_cons);
3479 }
3480 
3481 /* transmit timeout watchdog */
3482 static int
3483 bxe_watchdog(struct bxe_softc    *sc,
3484              struct bxe_fastpath *fp)
3485 {
3486     BXE_FP_TX_LOCK(fp);
3487 
3488     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3489         BXE_FP_TX_UNLOCK(fp);
3490         return (0);
3491     }
3492 
3493     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3494 
3495     BXE_FP_TX_UNLOCK(fp);
3496     BXE_SET_ERROR_BIT(sc, BXE_ERR_TXQ_STUCK);
3497     taskqueue_enqueue_timeout(taskqueue_thread,
3498         &sc->sp_err_timeout_task, hz/10);
3499 
3500     return (-1);
3501 }
3502 
3503 /* processes transmit completions */
3504 static uint8_t
3505 bxe_txeof(struct bxe_softc    *sc,
3506           struct bxe_fastpath *fp)
3507 {
3508     if_t ifp = sc->ifp;
3509     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3510     uint16_t tx_bd_avail;
3511 
3512     BXE_FP_TX_LOCK_ASSERT(fp);
3513 
3514     bd_cons = fp->tx_bd_cons;
3515     hw_cons = le16toh(*fp->tx_cons_sb);
3516     sw_cons = fp->tx_pkt_cons;
3517 
3518     while (sw_cons != hw_cons) {
3519         pkt_cons = TX_BD(sw_cons);
3520 
3521         BLOGD(sc, DBG_TX,
3522               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3523               fp->index, hw_cons, sw_cons, pkt_cons);
3524 
3525         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3526 
3527         sw_cons++;
3528     }
3529 
3530     fp->tx_pkt_cons = sw_cons;
3531     fp->tx_bd_cons  = bd_cons;
3532 
3533     BLOGD(sc, DBG_TX,
3534           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3535           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3536 
3537     mb();
3538 
3539     tx_bd_avail = bxe_tx_avail(sc, fp);
3540 
3541     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3542         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3543     } else {
3544         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3545     }
3546 
3547     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3548         /* reset the watchdog timer if there are pending transmits */
3549         fp->watchdog_timer = BXE_TX_TIMEOUT;
3550         return (TRUE);
3551     } else {
3552         /* clear watchdog when there are no pending transmits */
3553         fp->watchdog_timer = 0;
3554         return (FALSE);
3555     }
3556 }
3557 
3558 static void
3559 bxe_drain_tx_queues(struct bxe_softc *sc)
3560 {
3561     struct bxe_fastpath *fp;
3562     int i, count;
3563 
3564     /* wait until all TX fastpath tasks have completed */
3565     for (i = 0; i < sc->num_queues; i++) {
3566         fp = &sc->fp[i];
3567 
3568         count = 1000;
3569 
3570         while (bxe_has_tx_work(fp)) {
3571 
3572             BXE_FP_TX_LOCK(fp);
3573             bxe_txeof(sc, fp);
3574             BXE_FP_TX_UNLOCK(fp);
3575 
3576             if (count == 0) {
3577                 BLOGE(sc, "Timeout waiting for fp[%d] "
3578                           "transmits to complete!\n", i);
3579                 bxe_panic(sc, ("tx drain failure\n"));
3580                 return;
3581             }
3582 
3583             count--;
3584             DELAY(1000);
3585             rmb();
3586         }
3587     }
3588 
3589     return;
3590 }
3591 
3592 static int
3593 bxe_del_all_macs(struct bxe_softc          *sc,
3594                  struct ecore_vlan_mac_obj *mac_obj,
3595                  int                       mac_type,
3596                  uint8_t                   wait_for_comp)
3597 {
3598     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3599     int rc;
3600 
3601     /* wait for completion of requested */
3602     if (wait_for_comp) {
3603         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3604     }
3605 
3606     /* Set the mac type of addresses we want to clear */
3607     bxe_set_bit(mac_type, &vlan_mac_flags);
3608 
3609     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3610     if (rc < 0) {
3611         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3612             rc, mac_type, wait_for_comp);
3613     }
3614 
3615     return (rc);
3616 }
3617 
3618 static int
3619 bxe_fill_accept_flags(struct bxe_softc *sc,
3620                       uint32_t         rx_mode,
3621                       unsigned long    *rx_accept_flags,
3622                       unsigned long    *tx_accept_flags)
3623 {
3624     /* Clear the flags first */
3625     *rx_accept_flags = 0;
3626     *tx_accept_flags = 0;
3627 
3628     switch (rx_mode) {
3629     case BXE_RX_MODE_NONE:
3630         /*
3631          * 'drop all' supersedes any accept flags that may have been
3632          * passed to the function.
3633          */
3634         break;
3635 
3636     case BXE_RX_MODE_NORMAL:
3637         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3638         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3639         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3640 
3641         /* internal switching mode */
3642         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3643         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3644         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3645 
3646         break;
3647 
3648     case BXE_RX_MODE_ALLMULTI:
3649         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3650         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3651         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3652 
3653         /* internal switching mode */
3654         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3655         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3656         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3657 
3658         break;
3659 
3660     case BXE_RX_MODE_PROMISC:
3661         /*
3662          * According to deffinition of SI mode, iface in promisc mode
3663          * should receive matched and unmatched (in resolution of port)
3664          * unicast packets.
3665          */
3666         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3667         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3668         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3669         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3670 
3671         /* internal switching mode */
3672         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3673         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3674 
3675         if (IS_MF_SI(sc)) {
3676             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3677         } else {
3678             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3679         }
3680 
3681         break;
3682 
3683     default:
3684         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3685         return (-1);
3686     }
3687 
3688     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3689     if (rx_mode != BXE_RX_MODE_NONE) {
3690         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3691         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3692     }
3693 
3694     return (0);
3695 }
3696 
3697 static int
3698 bxe_set_q_rx_mode(struct bxe_softc *sc,
3699                   uint8_t          cl_id,
3700                   unsigned long    rx_mode_flags,
3701                   unsigned long    rx_accept_flags,
3702                   unsigned long    tx_accept_flags,
3703                   unsigned long    ramrod_flags)
3704 {
3705     struct ecore_rx_mode_ramrod_params ramrod_param;
3706     int rc;
3707 
3708     memset(&ramrod_param, 0, sizeof(ramrod_param));
3709 
3710     /* Prepare ramrod parameters */
3711     ramrod_param.cid = 0;
3712     ramrod_param.cl_id = cl_id;
3713     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3714     ramrod_param.func_id = SC_FUNC(sc);
3715 
3716     ramrod_param.pstate = &sc->sp_state;
3717     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3718 
3719     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3720     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3721 
3722     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3723 
3724     ramrod_param.ramrod_flags = ramrod_flags;
3725     ramrod_param.rx_mode_flags = rx_mode_flags;
3726 
3727     ramrod_param.rx_accept_flags = rx_accept_flags;
3728     ramrod_param.tx_accept_flags = tx_accept_flags;
3729 
3730     rc = ecore_config_rx_mode(sc, &ramrod_param);
3731     if (rc < 0) {
3732         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3733             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3734             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3735             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3736             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3737         return (rc);
3738     }
3739 
3740     return (0);
3741 }
3742 
3743 static int
3744 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3745 {
3746     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3747     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3748     int rc;
3749 
3750     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3751                                &tx_accept_flags);
3752     if (rc) {
3753         return (rc);
3754     }
3755 
3756     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3757     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3758 
3759     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3760     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3761                               rx_accept_flags, tx_accept_flags,
3762                               ramrod_flags));
3763 }
3764 
3765 /* returns the "mcp load_code" according to global load_count array */
3766 static int
3767 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3768 {
3769     int path = SC_PATH(sc);
3770     int port = SC_PORT(sc);
3771 
3772     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3773           path, load_count[path][0], load_count[path][1],
3774           load_count[path][2]);
3775     load_count[path][0]++;
3776     load_count[path][1 + port]++;
3777     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3778           path, load_count[path][0], load_count[path][1],
3779           load_count[path][2]);
3780     if (load_count[path][0] == 1) {
3781         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3782     } else if (load_count[path][1 + port] == 1) {
3783         return (FW_MSG_CODE_DRV_LOAD_PORT);
3784     } else {
3785         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3786     }
3787 }
3788 
3789 /* returns the "mcp load_code" according to global load_count array */
3790 static int
3791 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3792 {
3793     int port = SC_PORT(sc);
3794     int path = SC_PATH(sc);
3795 
3796     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3797           path, load_count[path][0], load_count[path][1],
3798           load_count[path][2]);
3799     load_count[path][0]--;
3800     load_count[path][1 + port]--;
3801     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3802           path, load_count[path][0], load_count[path][1],
3803           load_count[path][2]);
3804     if (load_count[path][0] == 0) {
3805         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3806     } else if (load_count[path][1 + port] == 0) {
3807         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3808     } else {
3809         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3810     }
3811 }
3812 
3813 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3814 static uint32_t
3815 bxe_send_unload_req(struct bxe_softc *sc,
3816                     int              unload_mode)
3817 {
3818     uint32_t reset_code = 0;
3819 
3820     /* Select the UNLOAD request mode */
3821     if (unload_mode == UNLOAD_NORMAL) {
3822         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3823     } else {
3824         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3825     }
3826 
3827     /* Send the request to the MCP */
3828     if (!BXE_NOMCP(sc)) {
3829         reset_code = bxe_fw_command(sc, reset_code, 0);
3830     } else {
3831         reset_code = bxe_nic_unload_no_mcp(sc);
3832     }
3833 
3834     return (reset_code);
3835 }
3836 
3837 /* send UNLOAD_DONE command to the MCP */
3838 static void
3839 bxe_send_unload_done(struct bxe_softc *sc,
3840                      uint8_t          keep_link)
3841 {
3842     uint32_t reset_param =
3843         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3844 
3845     /* Report UNLOAD_DONE to MCP */
3846     if (!BXE_NOMCP(sc)) {
3847         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3848     }
3849 }
3850 
3851 static int
3852 bxe_func_wait_started(struct bxe_softc *sc)
3853 {
3854     int tout = 50;
3855 
3856     if (!sc->port.pmf) {
3857         return (0);
3858     }
3859 
3860     /*
3861      * (assumption: No Attention from MCP at this stage)
3862      * PMF probably in the middle of TX disable/enable transaction
3863      * 1. Sync IRS for default SB
3864      * 2. Sync SP queue - this guarantees us that attention handling started
3865      * 3. Wait, that TX disable/enable transaction completes
3866      *
3867      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3868      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3869      * received completion for the transaction the state is TX_STOPPED.
3870      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3871      * transaction.
3872      */
3873 
3874     /* XXX make sure default SB ISR is done */
3875     /* need a way to synchronize an irq (intr_mtx?) */
3876 
3877     /* XXX flush any work queues */
3878 
3879     while (ecore_func_get_state(sc, &sc->func_obj) !=
3880            ECORE_F_STATE_STARTED && tout--) {
3881         DELAY(20000);
3882     }
3883 
3884     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3885         /*
3886          * Failed to complete the transaction in a "good way"
3887          * Force both transactions with CLR bit.
3888          */
3889         struct ecore_func_state_params func_params = { NULL };
3890 
3891         BLOGE(sc, "Unexpected function state! "
3892                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3893 
3894         func_params.f_obj = &sc->func_obj;
3895         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3896 
3897         /* STARTED-->TX_STOPPED */
3898         func_params.cmd = ECORE_F_CMD_TX_STOP;
3899         ecore_func_state_change(sc, &func_params);
3900 
3901         /* TX_STOPPED-->STARTED */
3902         func_params.cmd = ECORE_F_CMD_TX_START;
3903         return (ecore_func_state_change(sc, &func_params));
3904     }
3905 
3906     return (0);
3907 }
3908 
3909 static int
3910 bxe_stop_queue(struct bxe_softc *sc,
3911                int              index)
3912 {
3913     struct bxe_fastpath *fp = &sc->fp[index];
3914     struct ecore_queue_state_params q_params = { NULL };
3915     int rc;
3916 
3917     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3918 
3919     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3920     /* We want to wait for completion in this context */
3921     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3922 
3923     /* Stop the primary connection: */
3924 
3925     /* ...halt the connection */
3926     q_params.cmd = ECORE_Q_CMD_HALT;
3927     rc = ecore_queue_state_change(sc, &q_params);
3928     if (rc) {
3929         return (rc);
3930     }
3931 
3932     /* ...terminate the connection */
3933     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3934     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3935     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3936     rc = ecore_queue_state_change(sc, &q_params);
3937     if (rc) {
3938         return (rc);
3939     }
3940 
3941     /* ...delete cfc entry */
3942     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3943     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3944     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3945     return (ecore_queue_state_change(sc, &q_params));
3946 }
3947 
3948 /* wait for the outstanding SP commands */
3949 static inline uint8_t
3950 bxe_wait_sp_comp(struct bxe_softc *sc,
3951                  unsigned long    mask)
3952 {
3953     unsigned long tmp;
3954     int tout = 5000; /* wait for 5 secs tops */
3955 
3956     while (tout--) {
3957         mb();
3958         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3959             return (TRUE);
3960         }
3961 
3962         DELAY(1000);
3963     }
3964 
3965     mb();
3966 
3967     tmp = atomic_load_acq_long(&sc->sp_state);
3968     if (tmp & mask) {
3969         BLOGE(sc, "Filtering completion timed out: "
3970                   "sp_state 0x%lx, mask 0x%lx\n",
3971               tmp, mask);
3972         return (FALSE);
3973     }
3974 
3975     return (FALSE);
3976 }
3977 
3978 static int
3979 bxe_func_stop(struct bxe_softc *sc)
3980 {
3981     struct ecore_func_state_params func_params = { NULL };
3982     int rc;
3983 
3984     /* prepare parameters for function state transitions */
3985     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3986     func_params.f_obj = &sc->func_obj;
3987     func_params.cmd = ECORE_F_CMD_STOP;
3988 
3989     /*
3990      * Try to stop the function the 'good way'. If it fails (in case
3991      * of a parity error during bxe_chip_cleanup()) and we are
3992      * not in a debug mode, perform a state transaction in order to
3993      * enable further HW_RESET transaction.
3994      */
3995     rc = ecore_func_state_change(sc, &func_params);
3996     if (rc) {
3997         BLOGE(sc, "FUNC_STOP ramrod failed. "
3998                   "Running a dry transaction (%d)\n", rc);
3999         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
4000         return (ecore_func_state_change(sc, &func_params));
4001     }
4002 
4003     return (0);
4004 }
4005 
4006 static int
4007 bxe_reset_hw(struct bxe_softc *sc,
4008              uint32_t         load_code)
4009 {
4010     struct ecore_func_state_params func_params = { NULL };
4011 
4012     /* Prepare parameters for function state transitions */
4013     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4014 
4015     func_params.f_obj = &sc->func_obj;
4016     func_params.cmd = ECORE_F_CMD_HW_RESET;
4017 
4018     func_params.params.hw_init.load_phase = load_code;
4019 
4020     return (ecore_func_state_change(sc, &func_params));
4021 }
4022 
4023 static void
4024 bxe_int_disable_sync(struct bxe_softc *sc,
4025                      int              disable_hw)
4026 {
4027     if (disable_hw) {
4028         /* prevent the HW from sending interrupts */
4029         bxe_int_disable(sc);
4030     }
4031 
4032     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4033     /* make sure all ISRs are done */
4034 
4035     /* XXX make sure sp_task is not running */
4036     /* cancel and flush work queues */
4037 }
4038 
4039 static void
4040 bxe_chip_cleanup(struct bxe_softc *sc,
4041                  uint32_t         unload_mode,
4042                  uint8_t          keep_link)
4043 {
4044     int port = SC_PORT(sc);
4045     struct ecore_mcast_ramrod_params rparam = { NULL };
4046     uint32_t reset_code;
4047     int i, rc = 0;
4048 
4049     bxe_drain_tx_queues(sc);
4050 
4051     /* give HW time to discard old tx messages */
4052     DELAY(1000);
4053 
4054     /* Clean all ETH MACs */
4055     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4056     if (rc < 0) {
4057         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4058     }
4059 
4060     /* Clean up UC list  */
4061     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4062     if (rc < 0) {
4063         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4064     }
4065 
4066     /* Disable LLH */
4067     if (!CHIP_IS_E1(sc)) {
4068         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4069     }
4070 
4071     /* Set "drop all" to stop Rx */
4072 
4073     /*
4074      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4075      * a race between the completion code and this code.
4076      */
4077     BXE_MCAST_LOCK(sc);
4078 
4079     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4080         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4081     } else {
4082         bxe_set_storm_rx_mode(sc);
4083     }
4084 
4085     /* Clean up multicast configuration */
4086     rparam.mcast_obj = &sc->mcast_obj;
4087     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4088     if (rc < 0) {
4089         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4090     }
4091 
4092     BXE_MCAST_UNLOCK(sc);
4093 
4094     // XXX bxe_iov_chip_cleanup(sc);
4095 
4096     /*
4097      * Send the UNLOAD_REQUEST to the MCP. This will return if
4098      * this function should perform FUNCTION, PORT, or COMMON HW
4099      * reset.
4100      */
4101     reset_code = bxe_send_unload_req(sc, unload_mode);
4102 
4103     /*
4104      * (assumption: No Attention from MCP at this stage)
4105      * PMF probably in the middle of TX disable/enable transaction
4106      */
4107     rc = bxe_func_wait_started(sc);
4108     if (rc) {
4109         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4110     }
4111 
4112     /*
4113      * Close multi and leading connections
4114      * Completions for ramrods are collected in a synchronous way
4115      */
4116     for (i = 0; i < sc->num_queues; i++) {
4117         if (bxe_stop_queue(sc, i)) {
4118             goto unload_error;
4119         }
4120     }
4121 
4122     /*
4123      * If SP settings didn't get completed so far - something
4124      * very wrong has happen.
4125      */
4126     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4127         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4128     }
4129 
4130 unload_error:
4131 
4132     rc = bxe_func_stop(sc);
4133     if (rc) {
4134         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4135     }
4136 
4137     /* disable HW interrupts */
4138     bxe_int_disable_sync(sc, TRUE);
4139 
4140     /* detach interrupts */
4141     bxe_interrupt_detach(sc);
4142 
4143     /* Reset the chip */
4144     rc = bxe_reset_hw(sc, reset_code);
4145     if (rc) {
4146         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4147     }
4148 
4149     /* Report UNLOAD_DONE to MCP */
4150     bxe_send_unload_done(sc, keep_link);
4151 }
4152 
4153 static void
4154 bxe_disable_close_the_gate(struct bxe_softc *sc)
4155 {
4156     uint32_t val;
4157     int port = SC_PORT(sc);
4158 
4159     BLOGD(sc, DBG_LOAD,
4160           "Disabling 'close the gates'\n");
4161 
4162     if (CHIP_IS_E1(sc)) {
4163         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4164                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4165         val = REG_RD(sc, addr);
4166         val &= ~(0x300);
4167         REG_WR(sc, addr, val);
4168     } else {
4169         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4170         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4171                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4172         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4173     }
4174 }
4175 
4176 /*
4177  * Cleans the object that have internal lists without sending
4178  * ramrods. Should be run when interrutps are disabled.
4179  */
4180 static void
4181 bxe_squeeze_objects(struct bxe_softc *sc)
4182 {
4183     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4184     struct ecore_mcast_ramrod_params rparam = { NULL };
4185     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4186     int rc;
4187 
4188     /* Cleanup MACs' object first... */
4189 
4190     /* Wait for completion of requested */
4191     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4192     /* Perform a dry cleanup */
4193     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4194 
4195     /* Clean ETH primary MAC */
4196     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4197     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4198                              &ramrod_flags);
4199     if (rc != 0) {
4200         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4201     }
4202 
4203     /* Cleanup UC list */
4204     vlan_mac_flags = 0;
4205     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4206     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4207                              &ramrod_flags);
4208     if (rc != 0) {
4209         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4210     }
4211 
4212     /* Now clean mcast object... */
4213 
4214     rparam.mcast_obj = &sc->mcast_obj;
4215     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4216 
4217     /* Add a DEL command... */
4218     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4219     if (rc < 0) {
4220         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4221     }
4222 
4223     /* now wait until all pending commands are cleared */
4224 
4225     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4226     while (rc != 0) {
4227         if (rc < 0) {
4228             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4229             return;
4230         }
4231 
4232         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4233     }
4234 }
4235 
4236 /* stop the controller */
4237 static __noinline int
4238 bxe_nic_unload(struct bxe_softc *sc,
4239                uint32_t         unload_mode,
4240                uint8_t          keep_link)
4241 {
4242     uint8_t global = FALSE;
4243     uint32_t val;
4244     int i;
4245 
4246     BXE_CORE_LOCK_ASSERT(sc);
4247 
4248     if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4249 
4250     for (i = 0; i < sc->num_queues; i++) {
4251         struct bxe_fastpath *fp;
4252 
4253         fp = &sc->fp[i];
4254 	fp->watchdog_timer = 0;
4255         BXE_FP_TX_LOCK(fp);
4256         BXE_FP_TX_UNLOCK(fp);
4257     }
4258 
4259     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4260 
4261     /* mark driver as unloaded in shmem2 */
4262     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4263         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4264         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4265                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4266     }
4267 
4268     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4269         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4270 
4271 	if(CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
4272             /*
4273              * We can get here if the driver has been unloaded
4274              * during parity error recovery and is either waiting for a
4275              * leader to complete or for other functions to unload and
4276              * then ifconfig down has been issued. In this case we want to
4277              * unload and let other functions to complete a recovery
4278              * process.
4279              */
4280             sc->recovery_state = BXE_RECOVERY_DONE;
4281             sc->is_leader = 0;
4282             bxe_release_leader_lock(sc);
4283             mb();
4284             BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4285 	}
4286         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4287             " state = 0x%x\n", sc->recovery_state, sc->state);
4288         return (-1);
4289     }
4290 
4291     /*
4292      * Nothing to do during unload if previous bxe_nic_load()
4293      * did not completed successfully - all resourses are released.
4294      */
4295     if ((sc->state == BXE_STATE_CLOSED) ||
4296         (sc->state == BXE_STATE_ERROR)) {
4297         return (0);
4298     }
4299 
4300     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4301     mb();
4302 
4303     /* stop tx */
4304     bxe_tx_disable(sc);
4305 
4306     sc->rx_mode = BXE_RX_MODE_NONE;
4307     /* XXX set rx mode ??? */
4308 
4309     if (IS_PF(sc) && !sc->grcdump_done) {
4310         /* set ALWAYS_ALIVE bit in shmem */
4311         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4312 
4313         bxe_drv_pulse(sc);
4314 
4315         bxe_stats_handle(sc, STATS_EVENT_STOP);
4316         bxe_save_statistics(sc);
4317     }
4318 
4319     /* wait till consumers catch up with producers in all queues */
4320     bxe_drain_tx_queues(sc);
4321 
4322     /* if VF indicate to PF this function is going down (PF will delete sp
4323      * elements and clear initializations
4324      */
4325     if (IS_VF(sc)) {
4326         ; /* bxe_vfpf_close_vf(sc); */
4327     } else if (unload_mode != UNLOAD_RECOVERY) {
4328         /* if this is a normal/close unload need to clean up chip */
4329         if (!sc->grcdump_done)
4330             bxe_chip_cleanup(sc, unload_mode, keep_link);
4331     } else {
4332         /* Send the UNLOAD_REQUEST to the MCP */
4333         bxe_send_unload_req(sc, unload_mode);
4334 
4335         /*
4336          * Prevent transactions to host from the functions on the
4337          * engine that doesn't reset global blocks in case of global
4338          * attention once gloabl blocks are reset and gates are opened
4339          * (the engine which leader will perform the recovery
4340          * last).
4341          */
4342         if (!CHIP_IS_E1x(sc)) {
4343             bxe_pf_disable(sc);
4344         }
4345 
4346         /* disable HW interrupts */
4347         bxe_int_disable_sync(sc, TRUE);
4348 
4349         /* detach interrupts */
4350         bxe_interrupt_detach(sc);
4351 
4352         /* Report UNLOAD_DONE to MCP */
4353         bxe_send_unload_done(sc, FALSE);
4354     }
4355 
4356     /*
4357      * At this stage no more interrupts will arrive so we may safely clean
4358      * the queue'able objects here in case they failed to get cleaned so far.
4359      */
4360     if (IS_PF(sc)) {
4361         bxe_squeeze_objects(sc);
4362     }
4363 
4364     /* There should be no more pending SP commands at this stage */
4365     sc->sp_state = 0;
4366 
4367     sc->port.pmf = 0;
4368 
4369     bxe_free_fp_buffers(sc);
4370 
4371     if (IS_PF(sc)) {
4372         bxe_free_mem(sc);
4373     }
4374 
4375     bxe_free_fw_stats_mem(sc);
4376 
4377     sc->state = BXE_STATE_CLOSED;
4378 
4379     /*
4380      * Check if there are pending parity attentions. If there are - set
4381      * RECOVERY_IN_PROGRESS.
4382      */
4383     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4384         bxe_set_reset_in_progress(sc);
4385 
4386         /* Set RESET_IS_GLOBAL if needed */
4387         if (global) {
4388             bxe_set_reset_global(sc);
4389         }
4390     }
4391 
4392     /*
4393      * The last driver must disable a "close the gate" if there is no
4394      * parity attention or "process kill" pending.
4395      */
4396     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4397         bxe_reset_is_done(sc, SC_PATH(sc))) {
4398         bxe_disable_close_the_gate(sc);
4399     }
4400 
4401     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4402 
4403     bxe_link_report(sc);
4404 
4405     return (0);
4406 }
4407 
4408 /*
4409  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4410  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4411  */
4412 static int
4413 bxe_ifmedia_update(struct ifnet  *ifp)
4414 {
4415     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4416     struct ifmedia *ifm;
4417 
4418     ifm = &sc->ifmedia;
4419 
4420     /* We only support Ethernet media type. */
4421     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4422         return (EINVAL);
4423     }
4424 
4425     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4426     case IFM_AUTO:
4427          break;
4428     case IFM_10G_CX4:
4429     case IFM_10G_SR:
4430     case IFM_10G_T:
4431     case IFM_10G_TWINAX:
4432     default:
4433         /* We don't support changing the media type. */
4434         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4435               IFM_SUBTYPE(ifm->ifm_media));
4436         return (EINVAL);
4437     }
4438 
4439     return (0);
4440 }
4441 
4442 /*
4443  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4444  */
4445 static void
4446 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4447 {
4448     struct bxe_softc *sc = if_getsoftc(ifp);
4449 
4450     /* Bug 165447: the 'ifconfig' tool skips printing of the "status: ..."
4451        line if the IFM_AVALID flag is *NOT* set. So we need to set this
4452        flag unconditionally (irrespective of the admininistrative
4453        'up/down' state of the interface) to ensure that that line is always
4454        displayed.
4455     */
4456     ifmr->ifm_status = IFM_AVALID;
4457 
4458     /* Setup the default interface info. */
4459     ifmr->ifm_active = IFM_ETHER;
4460 
4461     /* Report link down if the driver isn't running. */
4462     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4463         ifmr->ifm_active |= IFM_NONE;
4464         BLOGD(sc, DBG_PHY, "in %s : nic still not loaded fully\n", __func__);
4465         BLOGD(sc, DBG_PHY, "in %s : link_up (1) : %d\n",
4466                 __func__, sc->link_vars.link_up);
4467         return;
4468     }
4469 
4470 
4471     if (sc->link_vars.link_up) {
4472         ifmr->ifm_status |= IFM_ACTIVE;
4473         ifmr->ifm_active |= IFM_FDX;
4474     } else {
4475         ifmr->ifm_active |= IFM_NONE;
4476         BLOGD(sc, DBG_PHY, "in %s : setting IFM_NONE\n",
4477                 __func__);
4478         return;
4479     }
4480 
4481     ifmr->ifm_active |= sc->media;
4482     return;
4483 }
4484 
4485 static void
4486 bxe_handle_chip_tq(void *context,
4487                    int  pending)
4488 {
4489     struct bxe_softc *sc = (struct bxe_softc *)context;
4490     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4491 
4492     switch (work)
4493     {
4494 
4495     case CHIP_TQ_REINIT:
4496         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4497             /* restart the interface */
4498             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4499             bxe_periodic_stop(sc);
4500             BXE_CORE_LOCK(sc);
4501             bxe_stop_locked(sc);
4502             bxe_init_locked(sc);
4503             BXE_CORE_UNLOCK(sc);
4504         }
4505         break;
4506 
4507     default:
4508         break;
4509     }
4510 }
4511 
4512 /*
4513  * Handles any IOCTL calls from the operating system.
4514  *
4515  * Returns:
4516  *   0 = Success, >0 Failure
4517  */
4518 static int
4519 bxe_ioctl(if_t ifp,
4520           u_long       command,
4521           caddr_t      data)
4522 {
4523     struct bxe_softc *sc = if_getsoftc(ifp);
4524     struct ifreq *ifr = (struct ifreq *)data;
4525     int mask = 0;
4526     int reinit = 0;
4527     int error = 0;
4528 
4529     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4530     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4531 
4532     switch (command)
4533     {
4534     case SIOCSIFMTU:
4535         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4536               ifr->ifr_mtu);
4537 
4538         if (sc->mtu == ifr->ifr_mtu) {
4539             /* nothing to change */
4540             break;
4541         }
4542 
4543         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4544             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4545                   ifr->ifr_mtu, mtu_min, mtu_max);
4546             error = EINVAL;
4547             break;
4548         }
4549 
4550         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4551                              (unsigned long)ifr->ifr_mtu);
4552 	/*
4553         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4554                               (unsigned long)ifr->ifr_mtu);
4555 	XXX - Not sure why it needs to be atomic
4556 	*/
4557 	if_setmtu(ifp, ifr->ifr_mtu);
4558         reinit = 1;
4559         break;
4560 
4561     case SIOCSIFFLAGS:
4562         /* toggle the interface state up or down */
4563         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4564 
4565 	BXE_CORE_LOCK(sc);
4566         /* check if the interface is up */
4567         if (if_getflags(ifp) & IFF_UP) {
4568             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4569                 /* set the receive mode flags */
4570                 bxe_set_rx_mode(sc);
4571             } else if(sc->state != BXE_STATE_DISABLED) {
4572 		bxe_init_locked(sc);
4573             }
4574         } else {
4575             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4576 		bxe_periodic_stop(sc);
4577 		bxe_stop_locked(sc);
4578             }
4579         }
4580 	BXE_CORE_UNLOCK(sc);
4581 
4582         break;
4583 
4584     case SIOCADDMULTI:
4585     case SIOCDELMULTI:
4586         /* add/delete multicast addresses */
4587         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4588 
4589         /* check if the interface is up */
4590         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4591             /* set the receive mode flags */
4592 	    BXE_CORE_LOCK(sc);
4593             bxe_set_rx_mode(sc);
4594 	    BXE_CORE_UNLOCK(sc);
4595         }
4596 
4597         break;
4598 
4599     case SIOCSIFCAP:
4600         /* find out which capabilities have changed */
4601         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4602 
4603         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4604               mask);
4605 
4606         /* toggle the LRO capabilites enable flag */
4607         if (mask & IFCAP_LRO) {
4608 	    if_togglecapenable(ifp, IFCAP_LRO);
4609             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4610                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4611             reinit = 1;
4612         }
4613 
4614         /* toggle the TXCSUM checksum capabilites enable flag */
4615         if (mask & IFCAP_TXCSUM) {
4616 	    if_togglecapenable(ifp, IFCAP_TXCSUM);
4617             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4618                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4619             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
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 the RXCSUM checksum capabilities enable flag */
4632         if (mask & IFCAP_RXCSUM) {
4633 	    if_togglecapenable(ifp, IFCAP_RXCSUM);
4634             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4635                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4636             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4637                 if_sethwassistbits(ifp, (CSUM_IP      |
4638                                     CSUM_TCP      |
4639                                     CSUM_UDP      |
4640                                     CSUM_TSO      |
4641                                     CSUM_TCP_IPV6 |
4642                                     CSUM_UDP_IPV6), 0);
4643             } else {
4644 		if_clearhwassist(ifp); /* XXX */
4645             }
4646         }
4647 
4648         /* toggle TSO4 capabilities enabled flag */
4649         if (mask & IFCAP_TSO4) {
4650             if_togglecapenable(ifp, IFCAP_TSO4);
4651             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4652                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4653         }
4654 
4655         /* toggle TSO6 capabilities enabled flag */
4656         if (mask & IFCAP_TSO6) {
4657 	    if_togglecapenable(ifp, IFCAP_TSO6);
4658             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4659                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4660         }
4661 
4662         /* toggle VLAN_HWTSO capabilities enabled flag */
4663         if (mask & IFCAP_VLAN_HWTSO) {
4664 
4665 	    if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4666             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4667                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4668         }
4669 
4670         /* toggle VLAN_HWCSUM capabilities enabled flag */
4671         if (mask & IFCAP_VLAN_HWCSUM) {
4672             /* XXX investigate this... */
4673             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4674             error = EINVAL;
4675         }
4676 
4677         /* toggle VLAN_MTU capabilities enable flag */
4678         if (mask & IFCAP_VLAN_MTU) {
4679             /* XXX investigate this... */
4680             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4681             error = EINVAL;
4682         }
4683 
4684         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4685         if (mask & IFCAP_VLAN_HWTAGGING) {
4686             /* XXX investigate this... */
4687             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4688             error = EINVAL;
4689         }
4690 
4691         /* toggle VLAN_HWFILTER capabilities enabled flag */
4692         if (mask & IFCAP_VLAN_HWFILTER) {
4693             /* XXX investigate this... */
4694             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4695             error = EINVAL;
4696         }
4697 
4698         /* XXX not yet...
4699          * IFCAP_WOL_MAGIC
4700          */
4701 
4702         break;
4703 
4704     case SIOCSIFMEDIA:
4705     case SIOCGIFMEDIA:
4706         /* set/get interface media */
4707         BLOGD(sc, DBG_IOCTL,
4708               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4709               (command & 0xff));
4710         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4711         break;
4712 
4713     default:
4714         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4715               (command & 0xff));
4716         error = ether_ioctl(ifp, command, data);
4717         break;
4718     }
4719 
4720     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4721         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4722               "Re-initializing hardware from IOCTL change\n");
4723 	bxe_periodic_stop(sc);
4724 	BXE_CORE_LOCK(sc);
4725 	bxe_stop_locked(sc);
4726 	bxe_init_locked(sc);
4727 	BXE_CORE_UNLOCK(sc);
4728     }
4729 
4730     return (error);
4731 }
4732 
4733 static __noinline void
4734 bxe_dump_mbuf(struct bxe_softc *sc,
4735               struct mbuf      *m,
4736               uint8_t          contents)
4737 {
4738     char * type;
4739     int i = 0;
4740 
4741     if (!(sc->debug & DBG_MBUF)) {
4742         return;
4743     }
4744 
4745     if (m == NULL) {
4746         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4747         return;
4748     }
4749 
4750     while (m) {
4751 
4752 #if __FreeBSD_version >= 1000000
4753         BLOGD(sc, DBG_MBUF,
4754               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4755               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4756 
4757         if (m->m_flags & M_PKTHDR) {
4758              BLOGD(sc, DBG_MBUF,
4759                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4760                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4761                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4762         }
4763 #else
4764         BLOGD(sc, DBG_MBUF,
4765               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4766               i, m, m->m_len, m->m_flags,
4767               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4768 
4769         if (m->m_flags & M_PKTHDR) {
4770              BLOGD(sc, DBG_MBUF,
4771                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4772                    i, m->m_pkthdr.len, m->m_flags,
4773                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4774                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4775                    "\22M_PROMISC\23M_NOFREE",
4776                    (int)m->m_pkthdr.csum_flags,
4777                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4778                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4779                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4780                    "\14CSUM_PSEUDO_HDR");
4781         }
4782 #endif /* #if __FreeBSD_version >= 1000000 */
4783 
4784         if (m->m_flags & M_EXT) {
4785             switch (m->m_ext.ext_type) {
4786             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4787             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4788             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4789             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4790             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4791             case EXT_PACKET:     type = "EXT_PACKET";     break;
4792             case EXT_MBUF:       type = "EXT_MBUF";       break;
4793             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4794             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4795             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4796             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4797             default:             type = "UNKNOWN";        break;
4798             }
4799 
4800             BLOGD(sc, DBG_MBUF,
4801                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4802                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4803         }
4804 
4805         if (contents) {
4806             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4807         }
4808 
4809         m = m->m_next;
4810         i++;
4811     }
4812 }
4813 
4814 /*
4815  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4816  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4817  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4818  * The headers comes in a separate bd in FreeBSD so 13-3=10.
4819  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4820  */
4821 static int
4822 bxe_chktso_window(struct bxe_softc  *sc,
4823                   int               nsegs,
4824                   bus_dma_segment_t *segs,
4825                   struct mbuf       *m)
4826 {
4827     uint32_t num_wnds, wnd_size, wnd_sum;
4828     int32_t frag_idx, wnd_idx;
4829     unsigned short lso_mss;
4830     int defrag;
4831 
4832     defrag = 0;
4833     wnd_sum = 0;
4834     wnd_size = 10;
4835     num_wnds = nsegs - wnd_size;
4836     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4837 
4838     /*
4839      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4840      * first window sum of data while skipping the first assuming it is the
4841      * header in FreeBSD.
4842      */
4843     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4844         wnd_sum += htole16(segs[frag_idx].ds_len);
4845     }
4846 
4847     /* check the first 10 bd window size */
4848     if (wnd_sum < lso_mss) {
4849         return (1);
4850     }
4851 
4852     /* run through the windows */
4853     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4854         /* subtract the first mbuf->m_len of the last wndw(-header) */
4855         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4856         /* add the next mbuf len to the len of our new window */
4857         wnd_sum += htole16(segs[frag_idx].ds_len);
4858         if (wnd_sum < lso_mss) {
4859             return (1);
4860         }
4861     }
4862 
4863     return (0);
4864 }
4865 
4866 static uint8_t
4867 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4868                     struct mbuf         *m,
4869                     uint32_t            *parsing_data)
4870 {
4871     struct ether_vlan_header *eh = NULL;
4872     struct ip *ip4 = NULL;
4873     struct ip6_hdr *ip6 = NULL;
4874     caddr_t ip = NULL;
4875     struct tcphdr *th = NULL;
4876     int e_hlen, ip_hlen, l4_off;
4877     uint16_t proto;
4878 
4879     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4880         /* no L4 checksum offload needed */
4881         return (0);
4882     }
4883 
4884     /* get the Ethernet header */
4885     eh = mtod(m, struct ether_vlan_header *);
4886 
4887     /* handle VLAN encapsulation if present */
4888     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4889         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4890         proto  = ntohs(eh->evl_proto);
4891     } else {
4892         e_hlen = ETHER_HDR_LEN;
4893         proto  = ntohs(eh->evl_encap_proto);
4894     }
4895 
4896     switch (proto) {
4897     case ETHERTYPE_IP:
4898         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4899         ip4 = (m->m_len < sizeof(struct ip)) ?
4900                   (struct ip *)m->m_next->m_data :
4901                   (struct ip *)(m->m_data + e_hlen);
4902         /* ip_hl is number of 32-bit words */
4903         ip_hlen = (ip4->ip_hl << 2);
4904         ip = (caddr_t)ip4;
4905         break;
4906     case ETHERTYPE_IPV6:
4907         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4908         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4909                   (struct ip6_hdr *)m->m_next->m_data :
4910                   (struct ip6_hdr *)(m->m_data + e_hlen);
4911         /* XXX cannot support offload with IPv6 extensions */
4912         ip_hlen = sizeof(struct ip6_hdr);
4913         ip = (caddr_t)ip6;
4914         break;
4915     default:
4916         /* We can't offload in this case... */
4917         /* XXX error stat ??? */
4918         return (0);
4919     }
4920 
4921     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4922     l4_off = (e_hlen + ip_hlen);
4923 
4924     *parsing_data |=
4925         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4926          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4927 
4928     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4929                                   CSUM_TSO |
4930                                   CSUM_TCP_IPV6)) {
4931         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4932         th = (struct tcphdr *)(ip + ip_hlen);
4933         /* th_off is number of 32-bit words */
4934         *parsing_data |= ((th->th_off <<
4935                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4936                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4937         return (l4_off + (th->th_off << 2)); /* entire header length */
4938     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4939                                          CSUM_UDP_IPV6)) {
4940         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4941         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4942     } else {
4943         /* XXX error stat ??? */
4944         return (0);
4945     }
4946 }
4947 
4948 static uint8_t
4949 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4950                  struct mbuf                *m,
4951                  struct eth_tx_parse_bd_e1x *pbd)
4952 {
4953     struct ether_vlan_header *eh = NULL;
4954     struct ip *ip4 = NULL;
4955     struct ip6_hdr *ip6 = NULL;
4956     caddr_t ip = NULL;
4957     struct tcphdr *th = NULL;
4958     struct udphdr *uh = NULL;
4959     int e_hlen, ip_hlen;
4960     uint16_t proto;
4961     uint8_t hlen;
4962     uint16_t tmp_csum;
4963     uint32_t *tmp_uh;
4964 
4965     /* get the Ethernet header */
4966     eh = mtod(m, struct ether_vlan_header *);
4967 
4968     /* handle VLAN encapsulation if present */
4969     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4970         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4971         proto  = ntohs(eh->evl_proto);
4972     } else {
4973         e_hlen = ETHER_HDR_LEN;
4974         proto  = ntohs(eh->evl_encap_proto);
4975     }
4976 
4977     switch (proto) {
4978     case ETHERTYPE_IP:
4979         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4980         ip4 = (m->m_len < sizeof(struct ip)) ?
4981                   (struct ip *)m->m_next->m_data :
4982                   (struct ip *)(m->m_data + e_hlen);
4983         /* ip_hl is number of 32-bit words */
4984         ip_hlen = (ip4->ip_hl << 1);
4985         ip = (caddr_t)ip4;
4986         break;
4987     case ETHERTYPE_IPV6:
4988         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4989         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4990                   (struct ip6_hdr *)m->m_next->m_data :
4991                   (struct ip6_hdr *)(m->m_data + e_hlen);
4992         /* XXX cannot support offload with IPv6 extensions */
4993         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4994         ip = (caddr_t)ip6;
4995         break;
4996     default:
4997         /* We can't offload in this case... */
4998         /* XXX error stat ??? */
4999         return (0);
5000     }
5001 
5002     hlen = (e_hlen >> 1);
5003 
5004     /* note that rest of global_data is indirectly zeroed here */
5005     if (m->m_flags & M_VLANTAG) {
5006         pbd->global_data =
5007             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5008     } else {
5009         pbd->global_data = htole16(hlen);
5010     }
5011 
5012     pbd->ip_hlen_w = ip_hlen;
5013 
5014     hlen += pbd->ip_hlen_w;
5015 
5016     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5017 
5018     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5019                                   CSUM_TSO |
5020                                   CSUM_TCP_IPV6)) {
5021         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5022         /* th_off is number of 32-bit words */
5023         hlen += (uint16_t)(th->th_off << 1);
5024     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5025                                          CSUM_UDP_IPV6)) {
5026         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5027         hlen += (sizeof(struct udphdr) / 2);
5028     } else {
5029         /* valid case as only CSUM_IP was set */
5030         return (0);
5031     }
5032 
5033     pbd->total_hlen_w = htole16(hlen);
5034 
5035     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5036                                   CSUM_TSO |
5037                                   CSUM_TCP_IPV6)) {
5038         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5039         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5040     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5041                                          CSUM_UDP_IPV6)) {
5042         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5043 
5044         /*
5045          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5046          * checksums and does not know anything about the UDP header and where
5047          * the checksum field is located. It only knows about TCP. Therefore
5048          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5049          * offload. Since the checksum field offset for TCP is 16 bytes and
5050          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5051          * bytes less than the start of the UDP header. This allows the
5052          * hardware to write the checksum in the correct spot. But the
5053          * hardware will compute a checksum which includes the last 10 bytes
5054          * of the IP header. To correct this we tweak the stack computed
5055          * pseudo checksum by folding in the calculation of the inverse
5056          * checksum for those final 10 bytes of the IP header. This allows
5057          * the correct checksum to be computed by the hardware.
5058          */
5059 
5060         /* set pointer 10 bytes before UDP header */
5061         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5062 
5063         /* calculate a pseudo header checksum over the first 10 bytes */
5064         tmp_csum = in_pseudo(*tmp_uh,
5065                              *(tmp_uh + 1),
5066                              *(uint16_t *)(tmp_uh + 2));
5067 
5068         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5069     }
5070 
5071     return (hlen * 2); /* entire header length, number of bytes */
5072 }
5073 
5074 static void
5075 bxe_set_pbd_lso_e2(struct mbuf *m,
5076                    uint32_t    *parsing_data)
5077 {
5078     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5079                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5080                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5081 
5082     /* XXX test for IPv6 with extension header... */
5083 }
5084 
5085 static void
5086 bxe_set_pbd_lso(struct mbuf                *m,
5087                 struct eth_tx_parse_bd_e1x *pbd)
5088 {
5089     struct ether_vlan_header *eh = NULL;
5090     struct ip *ip = NULL;
5091     struct tcphdr *th = NULL;
5092     int e_hlen;
5093 
5094     /* get the Ethernet header */
5095     eh = mtod(m, struct ether_vlan_header *);
5096 
5097     /* handle VLAN encapsulation if present */
5098     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5099                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5100 
5101     /* get the IP and TCP header, with LSO entire header in first mbuf */
5102     /* XXX assuming IPv4 */
5103     ip = (struct ip *)(m->m_data + e_hlen);
5104     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5105 
5106     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5107     pbd->tcp_send_seq = ntohl(th->th_seq);
5108     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5109 
5110 #if 1
5111         /* XXX IPv4 */
5112         pbd->ip_id = ntohs(ip->ip_id);
5113         pbd->tcp_pseudo_csum =
5114             ntohs(in_pseudo(ip->ip_src.s_addr,
5115                             ip->ip_dst.s_addr,
5116                             htons(IPPROTO_TCP)));
5117 #else
5118         /* XXX IPv6 */
5119         pbd->tcp_pseudo_csum =
5120             ntohs(in_pseudo(&ip6->ip6_src,
5121                             &ip6->ip6_dst,
5122                             htons(IPPROTO_TCP)));
5123 #endif
5124 
5125     pbd->global_data |=
5126         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5127 }
5128 
5129 /*
5130  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5131  * visible to the controller.
5132  *
5133  * If an mbuf is submitted to this routine and cannot be given to the
5134  * controller (e.g. it has too many fragments) then the function may free
5135  * the mbuf and return to the caller.
5136  *
5137  * Returns:
5138  *   0 = Success, !0 = Failure
5139  *   Note the side effect that an mbuf may be freed if it causes a problem.
5140  */
5141 static int
5142 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5143 {
5144     bus_dma_segment_t segs[32];
5145     struct mbuf *m0;
5146     struct bxe_sw_tx_bd *tx_buf;
5147     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5148     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5149     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5150     struct eth_tx_bd *tx_data_bd;
5151     struct eth_tx_bd *tx_total_pkt_size_bd;
5152     struct eth_tx_start_bd *tx_start_bd;
5153     uint16_t bd_prod, pkt_prod, total_pkt_size;
5154     uint8_t mac_type;
5155     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5156     struct bxe_softc *sc;
5157     uint16_t tx_bd_avail;
5158     struct ether_vlan_header *eh;
5159     uint32_t pbd_e2_parsing_data = 0;
5160     uint8_t hlen = 0;
5161     int tmp_bd;
5162     int i;
5163 
5164     sc = fp->sc;
5165 
5166 #if __FreeBSD_version >= 800000
5167     M_ASSERTPKTHDR(*m_head);
5168 #endif /* #if __FreeBSD_version >= 800000 */
5169 
5170     m0 = *m_head;
5171     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5172     tx_start_bd = NULL;
5173     tx_data_bd = NULL;
5174     tx_total_pkt_size_bd = NULL;
5175 
5176     /* get the H/W pointer for packets and BDs */
5177     pkt_prod = fp->tx_pkt_prod;
5178     bd_prod = fp->tx_bd_prod;
5179 
5180     mac_type = UNICAST_ADDRESS;
5181 
5182     /* map the mbuf into the next open DMAable memory */
5183     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5184     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5185                                     tx_buf->m_map, m0,
5186                                     segs, &nsegs, BUS_DMA_NOWAIT);
5187 
5188     /* mapping errors */
5189     if(__predict_false(error != 0)) {
5190         fp->eth_q_stats.tx_dma_mapping_failure++;
5191         if (error == ENOMEM) {
5192             /* resource issue, try again later */
5193             rc = ENOMEM;
5194         } else if (error == EFBIG) {
5195             /* possibly recoverable with defragmentation */
5196             fp->eth_q_stats.mbuf_defrag_attempts++;
5197             m0 = m_defrag(*m_head, M_NOWAIT);
5198             if (m0 == NULL) {
5199                 fp->eth_q_stats.mbuf_defrag_failures++;
5200                 rc = ENOBUFS;
5201             } else {
5202                 /* defrag successful, try mapping again */
5203                 *m_head = m0;
5204                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5205                                                 tx_buf->m_map, m0,
5206                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5207                 if (error) {
5208                     fp->eth_q_stats.tx_dma_mapping_failure++;
5209                     rc = error;
5210                 }
5211             }
5212         } else {
5213             /* unknown, unrecoverable mapping error */
5214             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5215             bxe_dump_mbuf(sc, m0, FALSE);
5216             rc = error;
5217         }
5218 
5219         goto bxe_tx_encap_continue;
5220     }
5221 
5222     tx_bd_avail = bxe_tx_avail(sc, fp);
5223 
5224     /* make sure there is enough room in the send queue */
5225     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5226         /* Recoverable, try again later. */
5227         fp->eth_q_stats.tx_hw_queue_full++;
5228         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5229         rc = ENOMEM;
5230         goto bxe_tx_encap_continue;
5231     }
5232 
5233     /* capture the current H/W TX chain high watermark */
5234     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5235                         (TX_BD_USABLE - tx_bd_avail))) {
5236         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5237     }
5238 
5239     /* make sure it fits in the packet window */
5240     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5241         /*
5242          * The mbuf may be to big for the controller to handle. If the frame
5243          * is a TSO frame we'll need to do an additional check.
5244          */
5245         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5246             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5247                 goto bxe_tx_encap_continue; /* OK to send */
5248             } else {
5249                 fp->eth_q_stats.tx_window_violation_tso++;
5250             }
5251         } else {
5252             fp->eth_q_stats.tx_window_violation_std++;
5253         }
5254 
5255         /* lets try to defragment this mbuf and remap it */
5256         fp->eth_q_stats.mbuf_defrag_attempts++;
5257         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5258 
5259         m0 = m_defrag(*m_head, M_NOWAIT);
5260         if (m0 == NULL) {
5261             fp->eth_q_stats.mbuf_defrag_failures++;
5262             /* Ugh, just drop the frame... :( */
5263             rc = ENOBUFS;
5264         } else {
5265             /* defrag successful, try mapping again */
5266             *m_head = m0;
5267             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5268                                             tx_buf->m_map, m0,
5269                                             segs, &nsegs, BUS_DMA_NOWAIT);
5270             if (error) {
5271                 fp->eth_q_stats.tx_dma_mapping_failure++;
5272                 /* No sense in trying to defrag/copy chain, drop it. :( */
5273                 rc = error;
5274             } else {
5275                /* if the chain is still too long then drop it */
5276                 if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5277                     /*
5278                      * in case TSO is enabled nsegs should be checked against
5279                      * BXE_TSO_MAX_SEGMENTS
5280                      */
5281                     if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5282                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5283                         fp->eth_q_stats.nsegs_path1_errors++;
5284                         rc = ENODEV;
5285                     }
5286                 } else {
5287                     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5288                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5289                         fp->eth_q_stats.nsegs_path2_errors++;
5290                         rc = ENODEV;
5291                     }
5292                 }
5293             }
5294         }
5295     }
5296 
5297 bxe_tx_encap_continue:
5298 
5299     /* Check for errors */
5300     if (rc) {
5301         if (rc == ENOMEM) {
5302             /* recoverable try again later  */
5303         } else {
5304             fp->eth_q_stats.tx_soft_errors++;
5305             fp->eth_q_stats.mbuf_alloc_tx--;
5306             m_freem(*m_head);
5307             *m_head = NULL;
5308         }
5309 
5310         return (rc);
5311     }
5312 
5313     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5314     if (m0->m_flags & M_BCAST) {
5315         mac_type = BROADCAST_ADDRESS;
5316     } else if (m0->m_flags & M_MCAST) {
5317         mac_type = MULTICAST_ADDRESS;
5318     }
5319 
5320     /* store the mbuf into the mbuf ring */
5321     tx_buf->m        = m0;
5322     tx_buf->first_bd = fp->tx_bd_prod;
5323     tx_buf->flags    = 0;
5324 
5325     /* prepare the first transmit (start) BD for the mbuf */
5326     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5327 
5328     BLOGD(sc, DBG_TX,
5329           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5330           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5331 
5332     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5333     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5334     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5335     total_pkt_size += tx_start_bd->nbytes;
5336     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5337 
5338     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5339 
5340     /* all frames have at least Start BD + Parsing BD */
5341     nbds = nsegs + 1;
5342     tx_start_bd->nbd = htole16(nbds);
5343 
5344     if (m0->m_flags & M_VLANTAG) {
5345         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5346         tx_start_bd->bd_flags.as_bitfield |=
5347             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5348     } else {
5349         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5350         if (IS_VF(sc)) {
5351             /* map ethernet header to find type and header length */
5352             eh = mtod(m0, struct ether_vlan_header *);
5353             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5354         } else {
5355             /* used by FW for packet accounting */
5356             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5357         }
5358     }
5359 
5360     /*
5361      * add a parsing BD from the chain. The parsing BD is always added
5362      * though it is only used for TSO and chksum
5363      */
5364     bd_prod = TX_BD_NEXT(bd_prod);
5365 
5366     if (m0->m_pkthdr.csum_flags) {
5367         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5368             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5369             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5370         }
5371 
5372         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5373             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5374                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5375         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5376             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5377                                                   ETH_TX_BD_FLAGS_IS_UDP |
5378                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5379         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5380                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5381             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5382         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5383             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5384                                                   ETH_TX_BD_FLAGS_IS_UDP);
5385         }
5386     }
5387 
5388     if (!CHIP_IS_E1x(sc)) {
5389         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5390         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5391 
5392         if (m0->m_pkthdr.csum_flags) {
5393             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5394         }
5395 
5396         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5397                  mac_type);
5398     } else {
5399         uint16_t global_data = 0;
5400 
5401         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5402         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5403 
5404         if (m0->m_pkthdr.csum_flags) {
5405             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5406         }
5407 
5408         SET_FLAG(global_data,
5409                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5410         pbd_e1x->global_data |= htole16(global_data);
5411     }
5412 
5413     /* setup the parsing BD with TSO specific info */
5414     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5415         fp->eth_q_stats.tx_ofld_frames_lso++;
5416         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5417 
5418         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5419             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5420 
5421             /* split the first BD into header/data making the fw job easy */
5422             nbds++;
5423             tx_start_bd->nbd = htole16(nbds);
5424             tx_start_bd->nbytes = htole16(hlen);
5425 
5426             bd_prod = TX_BD_NEXT(bd_prod);
5427 
5428             /* new transmit BD after the tx_parse_bd */
5429             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5430             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5431             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5432             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5433             if (tx_total_pkt_size_bd == NULL) {
5434                 tx_total_pkt_size_bd = tx_data_bd;
5435             }
5436 
5437             BLOGD(sc, DBG_TX,
5438                   "TSO split header size is %d (%x:%x) nbds %d\n",
5439                   le16toh(tx_start_bd->nbytes),
5440                   le32toh(tx_start_bd->addr_hi),
5441                   le32toh(tx_start_bd->addr_lo),
5442                   nbds);
5443         }
5444 
5445         if (!CHIP_IS_E1x(sc)) {
5446             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5447         } else {
5448             bxe_set_pbd_lso(m0, pbd_e1x);
5449         }
5450     }
5451 
5452     if (pbd_e2_parsing_data) {
5453         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5454     }
5455 
5456     /* prepare remaining BDs, start tx bd contains first seg/frag */
5457     for (i = 1; i < nsegs ; i++) {
5458         bd_prod = TX_BD_NEXT(bd_prod);
5459         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5460         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5461         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5462         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5463         if (tx_total_pkt_size_bd == NULL) {
5464             tx_total_pkt_size_bd = tx_data_bd;
5465         }
5466         total_pkt_size += tx_data_bd->nbytes;
5467     }
5468 
5469     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5470 
5471     if (tx_total_pkt_size_bd != NULL) {
5472         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5473     }
5474 
5475     if (__predict_false(sc->debug & DBG_TX)) {
5476         tmp_bd = tx_buf->first_bd;
5477         for (i = 0; i < nbds; i++)
5478         {
5479             if (i == 0) {
5480                 BLOGD(sc, DBG_TX,
5481                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5482                       "bd_flags=0x%x hdr_nbds=%d\n",
5483                       tx_start_bd,
5484                       tmp_bd,
5485                       le16toh(tx_start_bd->nbd),
5486                       le16toh(tx_start_bd->vlan_or_ethertype),
5487                       tx_start_bd->bd_flags.as_bitfield,
5488                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5489             } else if (i == 1) {
5490                 if (pbd_e1x) {
5491                     BLOGD(sc, DBG_TX,
5492                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5493                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5494                           "tcp_seq=%u total_hlen_w=%u\n",
5495                           pbd_e1x,
5496                           tmp_bd,
5497                           pbd_e1x->global_data,
5498                           pbd_e1x->ip_hlen_w,
5499                           pbd_e1x->ip_id,
5500                           pbd_e1x->lso_mss,
5501                           pbd_e1x->tcp_flags,
5502                           pbd_e1x->tcp_pseudo_csum,
5503                           pbd_e1x->tcp_send_seq,
5504                           le16toh(pbd_e1x->total_hlen_w));
5505                 } else { /* if (pbd_e2) */
5506                     BLOGD(sc, DBG_TX,
5507                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5508                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5509                           pbd_e2,
5510                           tmp_bd,
5511                           pbd_e2->data.mac_addr.dst_hi,
5512                           pbd_e2->data.mac_addr.dst_mid,
5513                           pbd_e2->data.mac_addr.dst_lo,
5514                           pbd_e2->data.mac_addr.src_hi,
5515                           pbd_e2->data.mac_addr.src_mid,
5516                           pbd_e2->data.mac_addr.src_lo,
5517                           pbd_e2->parsing_data);
5518                 }
5519             }
5520 
5521             if (i != 1) { /* skip parse db as it doesn't hold data */
5522                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5523                 BLOGD(sc, DBG_TX,
5524                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5525                       tx_data_bd,
5526                       tmp_bd,
5527                       le16toh(tx_data_bd->nbytes),
5528                       le32toh(tx_data_bd->addr_hi),
5529                       le32toh(tx_data_bd->addr_lo));
5530             }
5531 
5532             tmp_bd = TX_BD_NEXT(tmp_bd);
5533         }
5534     }
5535 
5536     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5537 
5538     /* update TX BD producer index value for next TX */
5539     bd_prod = TX_BD_NEXT(bd_prod);
5540 
5541     /*
5542      * If the chain of tx_bd's describing this frame is adjacent to or spans
5543      * an eth_tx_next_bd element then we need to increment the nbds value.
5544      */
5545     if (TX_BD_IDX(bd_prod) < nbds) {
5546         nbds++;
5547     }
5548 
5549     /* don't allow reordering of writes for nbd and packets */
5550     mb();
5551 
5552     fp->tx_db.data.prod += nbds;
5553 
5554     /* producer points to the next free tx_bd at this point */
5555     fp->tx_pkt_prod++;
5556     fp->tx_bd_prod = bd_prod;
5557 
5558     DOORBELL(sc, fp->index, fp->tx_db.raw);
5559 
5560     fp->eth_q_stats.tx_pkts++;
5561 
5562     /* Prevent speculative reads from getting ahead of the status block. */
5563     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5564                       0, 0, BUS_SPACE_BARRIER_READ);
5565 
5566     /* Prevent speculative reads from getting ahead of the doorbell. */
5567     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5568                       0, 0, BUS_SPACE_BARRIER_READ);
5569 
5570     return (0);
5571 }
5572 
5573 static void
5574 bxe_tx_start_locked(struct bxe_softc *sc,
5575                     if_t ifp,
5576                     struct bxe_fastpath *fp)
5577 {
5578     struct mbuf *m = NULL;
5579     int tx_count = 0;
5580     uint16_t tx_bd_avail;
5581 
5582     BXE_FP_TX_LOCK_ASSERT(fp);
5583 
5584     /* keep adding entries while there are frames to send */
5585     while (!if_sendq_empty(ifp)) {
5586 
5587         /*
5588          * check for any frames to send
5589          * dequeue can still be NULL even if queue is not empty
5590          */
5591         m = if_dequeue(ifp);
5592         if (__predict_false(m == NULL)) {
5593             break;
5594         }
5595 
5596         /* the mbuf now belongs to us */
5597         fp->eth_q_stats.mbuf_alloc_tx++;
5598 
5599         /*
5600          * Put the frame into the transmit ring. If we don't have room,
5601          * place the mbuf back at the head of the TX queue, set the
5602          * OACTIVE flag, and wait for the NIC to drain the chain.
5603          */
5604         if (__predict_false(bxe_tx_encap(fp, &m))) {
5605             fp->eth_q_stats.tx_encap_failures++;
5606             if (m != NULL) {
5607                 /* mark the TX queue as full and return the frame */
5608                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5609 		if_sendq_prepend(ifp, m);
5610                 fp->eth_q_stats.mbuf_alloc_tx--;
5611                 fp->eth_q_stats.tx_queue_xoff++;
5612             }
5613 
5614             /* stop looking for more work */
5615             break;
5616         }
5617 
5618         /* the frame was enqueued successfully */
5619         tx_count++;
5620 
5621         /* send a copy of the frame to any BPF listeners. */
5622         if_etherbpfmtap(ifp, m);
5623 
5624         tx_bd_avail = bxe_tx_avail(sc, fp);
5625 
5626         /* handle any completions if we're running low */
5627         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5628             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5629             bxe_txeof(sc, fp);
5630             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5631                 break;
5632             }
5633         }
5634     }
5635 
5636     /* all TX packets were dequeued and/or the tx ring is full */
5637     if (tx_count > 0) {
5638         /* reset the TX watchdog timeout timer */
5639         fp->watchdog_timer = BXE_TX_TIMEOUT;
5640     }
5641 }
5642 
5643 /* Legacy (non-RSS) dispatch routine */
5644 static void
5645 bxe_tx_start(if_t ifp)
5646 {
5647     struct bxe_softc *sc;
5648     struct bxe_fastpath *fp;
5649 
5650     sc = if_getsoftc(ifp);
5651 
5652     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5653         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5654         return;
5655     }
5656 
5657     if (!sc->link_vars.link_up) {
5658         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5659         return;
5660     }
5661 
5662     fp = &sc->fp[0];
5663 
5664     if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5665         fp->eth_q_stats.tx_queue_full_return++;
5666         return;
5667     }
5668 
5669     BXE_FP_TX_LOCK(fp);
5670     bxe_tx_start_locked(sc, ifp, fp);
5671     BXE_FP_TX_UNLOCK(fp);
5672 }
5673 
5674 #if __FreeBSD_version >= 901504
5675 
5676 static int
5677 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5678                        if_t                ifp,
5679                        struct bxe_fastpath *fp,
5680                        struct mbuf         *m)
5681 {
5682     struct buf_ring *tx_br = fp->tx_br;
5683     struct mbuf *next;
5684     int depth, rc, tx_count;
5685     uint16_t tx_bd_avail;
5686 
5687     rc = tx_count = 0;
5688 
5689     BXE_FP_TX_LOCK_ASSERT(fp);
5690 
5691     if (sc->state != BXE_STATE_OPEN)  {
5692         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5693         return ENETDOWN;
5694     }
5695 
5696     if (!tx_br) {
5697         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5698         return (EINVAL);
5699     }
5700 
5701     if (m != NULL) {
5702         rc = drbr_enqueue(ifp, tx_br, m);
5703         if (rc != 0) {
5704             fp->eth_q_stats.tx_soft_errors++;
5705             goto bxe_tx_mq_start_locked_exit;
5706         }
5707     }
5708 
5709     if (!sc->link_vars.link_up || !(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5710         fp->eth_q_stats.tx_request_link_down_failures++;
5711         goto bxe_tx_mq_start_locked_exit;
5712     }
5713 
5714     /* fetch the depth of the driver queue */
5715     depth = drbr_inuse_drv(ifp, tx_br);
5716     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5717         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5718     }
5719 
5720     /* keep adding entries while there are frames to send */
5721     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5722         /* handle any completions if we're running low */
5723         tx_bd_avail = bxe_tx_avail(sc, fp);
5724         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5725             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5726             bxe_txeof(sc, fp);
5727             tx_bd_avail = bxe_tx_avail(sc, fp);
5728             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5729                 fp->eth_q_stats.bd_avail_too_less_failures++;
5730                 m_freem(next);
5731                 drbr_advance(ifp, tx_br);
5732                 rc = ENOBUFS;
5733                 break;
5734             }
5735         }
5736 
5737         /* the mbuf now belongs to us */
5738         fp->eth_q_stats.mbuf_alloc_tx++;
5739 
5740         /*
5741          * Put the frame into the transmit ring. If we don't have room,
5742          * place the mbuf back at the head of the TX queue, set the
5743          * OACTIVE flag, and wait for the NIC to drain the chain.
5744          */
5745         rc = bxe_tx_encap(fp, &next);
5746         if (__predict_false(rc != 0)) {
5747             fp->eth_q_stats.tx_encap_failures++;
5748             if (next != NULL) {
5749                 /* mark the TX queue as full and save the frame */
5750                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5751                 drbr_putback(ifp, tx_br, next);
5752                 fp->eth_q_stats.mbuf_alloc_tx--;
5753                 fp->eth_q_stats.tx_frames_deferred++;
5754             } else
5755                 drbr_advance(ifp, tx_br);
5756 
5757             /* stop looking for more work */
5758             break;
5759         }
5760 
5761         /* the transmit frame was enqueued successfully */
5762         tx_count++;
5763 
5764         /* send a copy of the frame to any BPF listeners */
5765 	if_etherbpfmtap(ifp, next);
5766 
5767         drbr_advance(ifp, tx_br);
5768     }
5769 
5770     /* all TX packets were dequeued and/or the tx ring is full */
5771     if (tx_count > 0) {
5772         /* reset the TX watchdog timeout timer */
5773         fp->watchdog_timer = BXE_TX_TIMEOUT;
5774     }
5775 
5776 bxe_tx_mq_start_locked_exit:
5777     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5778     if (!drbr_empty(ifp, tx_br)) {
5779         fp->eth_q_stats.tx_mq_not_empty++;
5780         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5781     }
5782 
5783     return (rc);
5784 }
5785 
5786 static void
5787 bxe_tx_mq_start_deferred(void *arg,
5788                          int pending)
5789 {
5790     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5791     struct bxe_softc *sc = fp->sc;
5792     if_t ifp = sc->ifp;
5793 
5794     BXE_FP_TX_LOCK(fp);
5795     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5796     BXE_FP_TX_UNLOCK(fp);
5797 }
5798 
5799 /* Multiqueue (TSS) dispatch routine. */
5800 static int
5801 bxe_tx_mq_start(struct ifnet *ifp,
5802                 struct mbuf  *m)
5803 {
5804     struct bxe_softc *sc = if_getsoftc(ifp);
5805     struct bxe_fastpath *fp;
5806     int fp_index, rc;
5807 
5808     fp_index = 0; /* default is the first queue */
5809 
5810     /* check if flowid is set */
5811 
5812     if (BXE_VALID_FLOWID(m))
5813         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5814 
5815     fp = &sc->fp[fp_index];
5816 
5817     if (sc->state != BXE_STATE_OPEN)  {
5818         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5819         return ENETDOWN;
5820     }
5821 
5822     if (BXE_FP_TX_TRYLOCK(fp)) {
5823         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5824         BXE_FP_TX_UNLOCK(fp);
5825     } else {
5826         rc = drbr_enqueue(ifp, fp->tx_br, m);
5827         taskqueue_enqueue(fp->tq, &fp->tx_task);
5828     }
5829 
5830     return (rc);
5831 }
5832 
5833 static void
5834 bxe_mq_flush(struct ifnet *ifp)
5835 {
5836     struct bxe_softc *sc = if_getsoftc(ifp);
5837     struct bxe_fastpath *fp;
5838     struct mbuf *m;
5839     int i;
5840 
5841     for (i = 0; i < sc->num_queues; i++) {
5842         fp = &sc->fp[i];
5843 
5844         if (fp->state != BXE_FP_STATE_IRQ) {
5845             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5846                   fp->index, fp->state);
5847             continue;
5848         }
5849 
5850         if (fp->tx_br != NULL) {
5851             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5852             BXE_FP_TX_LOCK(fp);
5853             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5854                 m_freem(m);
5855             }
5856             BXE_FP_TX_UNLOCK(fp);
5857         }
5858     }
5859 
5860     if_qflush(ifp);
5861 }
5862 
5863 #endif /* FreeBSD_version >= 901504 */
5864 
5865 static uint16_t
5866 bxe_cid_ilt_lines(struct bxe_softc *sc)
5867 {
5868     if (IS_SRIOV(sc)) {
5869         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5870     }
5871     return (L2_ILT_LINES(sc));
5872 }
5873 
5874 static void
5875 bxe_ilt_set_info(struct bxe_softc *sc)
5876 {
5877     struct ilt_client_info *ilt_client;
5878     struct ecore_ilt *ilt = sc->ilt;
5879     uint16_t line = 0;
5880 
5881     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5882     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5883 
5884     /* CDU */
5885     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5886     ilt_client->client_num = ILT_CLIENT_CDU;
5887     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5888     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5889     ilt_client->start = line;
5890     line += bxe_cid_ilt_lines(sc);
5891 
5892     if (CNIC_SUPPORT(sc)) {
5893         line += CNIC_ILT_LINES;
5894     }
5895 
5896     ilt_client->end = (line - 1);
5897 
5898     BLOGD(sc, DBG_LOAD,
5899           "ilt client[CDU]: start %d, end %d, "
5900           "psz 0x%x, flags 0x%x, hw psz %d\n",
5901           ilt_client->start, ilt_client->end,
5902           ilt_client->page_size,
5903           ilt_client->flags,
5904           ilog2(ilt_client->page_size >> 12));
5905 
5906     /* QM */
5907     if (QM_INIT(sc->qm_cid_count)) {
5908         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5909         ilt_client->client_num = ILT_CLIENT_QM;
5910         ilt_client->page_size = QM_ILT_PAGE_SZ;
5911         ilt_client->flags = 0;
5912         ilt_client->start = line;
5913 
5914         /* 4 bytes for each cid */
5915         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5916                              QM_ILT_PAGE_SZ);
5917 
5918         ilt_client->end = (line - 1);
5919 
5920         BLOGD(sc, DBG_LOAD,
5921               "ilt client[QM]: start %d, end %d, "
5922               "psz 0x%x, flags 0x%x, hw psz %d\n",
5923               ilt_client->start, ilt_client->end,
5924               ilt_client->page_size, ilt_client->flags,
5925               ilog2(ilt_client->page_size >> 12));
5926     }
5927 
5928     if (CNIC_SUPPORT(sc)) {
5929         /* SRC */
5930         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5931         ilt_client->client_num = ILT_CLIENT_SRC;
5932         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5933         ilt_client->flags = 0;
5934         ilt_client->start = line;
5935         line += SRC_ILT_LINES;
5936         ilt_client->end = (line - 1);
5937 
5938         BLOGD(sc, DBG_LOAD,
5939               "ilt client[SRC]: start %d, end %d, "
5940               "psz 0x%x, flags 0x%x, hw psz %d\n",
5941               ilt_client->start, ilt_client->end,
5942               ilt_client->page_size, ilt_client->flags,
5943               ilog2(ilt_client->page_size >> 12));
5944 
5945         /* TM */
5946         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5947         ilt_client->client_num = ILT_CLIENT_TM;
5948         ilt_client->page_size = TM_ILT_PAGE_SZ;
5949         ilt_client->flags = 0;
5950         ilt_client->start = line;
5951         line += TM_ILT_LINES;
5952         ilt_client->end = (line - 1);
5953 
5954         BLOGD(sc, DBG_LOAD,
5955               "ilt client[TM]: start %d, end %d, "
5956               "psz 0x%x, flags 0x%x, hw psz %d\n",
5957               ilt_client->start, ilt_client->end,
5958               ilt_client->page_size, ilt_client->flags,
5959               ilog2(ilt_client->page_size >> 12));
5960     }
5961 
5962     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5963 }
5964 
5965 static void
5966 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5967 {
5968     int i;
5969     uint32_t rx_buf_size;
5970 
5971     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5972 
5973     for (i = 0; i < sc->num_queues; i++) {
5974         if(rx_buf_size <= MCLBYTES){
5975             sc->fp[i].rx_buf_size = rx_buf_size;
5976             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5977         }else if (rx_buf_size <= MJUMPAGESIZE){
5978             sc->fp[i].rx_buf_size = rx_buf_size;
5979             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5980         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5981             sc->fp[i].rx_buf_size = MCLBYTES;
5982             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5983         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5984             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5985             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5986         }else {
5987             sc->fp[i].rx_buf_size = MCLBYTES;
5988             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5989         }
5990     }
5991 }
5992 
5993 static int
5994 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5995 {
5996     int rc = 0;
5997 
5998     if ((sc->ilt =
5999          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6000                                     M_BXE_ILT,
6001                                     (M_NOWAIT | M_ZERO))) == NULL) {
6002         rc = 1;
6003     }
6004 
6005     return (rc);
6006 }
6007 
6008 static int
6009 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6010 {
6011     int rc = 0;
6012 
6013     if ((sc->ilt->lines =
6014          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6015                                     M_BXE_ILT,
6016                                     (M_NOWAIT | M_ZERO))) == NULL) {
6017         rc = 1;
6018     }
6019 
6020     return (rc);
6021 }
6022 
6023 static void
6024 bxe_free_ilt_mem(struct bxe_softc *sc)
6025 {
6026     if (sc->ilt != NULL) {
6027         free(sc->ilt, M_BXE_ILT);
6028         sc->ilt = NULL;
6029     }
6030 }
6031 
6032 static void
6033 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6034 {
6035     if (sc->ilt->lines != NULL) {
6036         free(sc->ilt->lines, M_BXE_ILT);
6037         sc->ilt->lines = NULL;
6038     }
6039 }
6040 
6041 static void
6042 bxe_free_mem(struct bxe_softc *sc)
6043 {
6044     int i;
6045 
6046     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6047         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6048         sc->context[i].vcxt = NULL;
6049         sc->context[i].size = 0;
6050     }
6051 
6052     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6053 
6054     bxe_free_ilt_lines_mem(sc);
6055 
6056 }
6057 
6058 static int
6059 bxe_alloc_mem(struct bxe_softc *sc)
6060 {
6061 
6062     int context_size;
6063     int allocated;
6064     int i;
6065 
6066     /*
6067      * Allocate memory for CDU context:
6068      * This memory is allocated separately and not in the generic ILT
6069      * functions because CDU differs in few aspects:
6070      * 1. There can be multiple entities allocating memory for context -
6071      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6072      * its own ILT lines.
6073      * 2. Since CDU page-size is not a single 4KB page (which is the case
6074      * for the other ILT clients), to be efficient we want to support
6075      * allocation of sub-page-size in the last entry.
6076      * 3. Context pointers are used by the driver to pass to FW / update
6077      * the context (for the other ILT clients the pointers are used just to
6078      * free the memory during unload).
6079      */
6080     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6081     for (i = 0, allocated = 0; allocated < context_size; i++) {
6082         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6083                                   (context_size - allocated));
6084 
6085         if (bxe_dma_alloc(sc, sc->context[i].size,
6086                           &sc->context[i].vcxt_dma,
6087                           "cdu context") != 0) {
6088             bxe_free_mem(sc);
6089             return (-1);
6090         }
6091 
6092         sc->context[i].vcxt =
6093             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6094 
6095         allocated += sc->context[i].size;
6096     }
6097 
6098     bxe_alloc_ilt_lines_mem(sc);
6099 
6100     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6101           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6102     {
6103         for (i = 0; i < 4; i++) {
6104             BLOGD(sc, DBG_LOAD,
6105                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6106                   i,
6107                   sc->ilt->clients[i].page_size,
6108                   sc->ilt->clients[i].start,
6109                   sc->ilt->clients[i].end,
6110                   sc->ilt->clients[i].client_num,
6111                   sc->ilt->clients[i].flags);
6112         }
6113     }
6114     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6115         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6116         bxe_free_mem(sc);
6117         return (-1);
6118     }
6119 
6120     return (0);
6121 }
6122 
6123 static void
6124 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6125 {
6126     struct bxe_softc *sc;
6127     int i;
6128 
6129     sc = fp->sc;
6130 
6131     if (fp->rx_mbuf_tag == NULL) {
6132         return;
6133     }
6134 
6135     /* free all mbufs and unload all maps */
6136     for (i = 0; i < RX_BD_TOTAL; i++) {
6137         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6138             bus_dmamap_sync(fp->rx_mbuf_tag,
6139                             fp->rx_mbuf_chain[i].m_map,
6140                             BUS_DMASYNC_POSTREAD);
6141             bus_dmamap_unload(fp->rx_mbuf_tag,
6142                               fp->rx_mbuf_chain[i].m_map);
6143         }
6144 
6145         if (fp->rx_mbuf_chain[i].m != NULL) {
6146             m_freem(fp->rx_mbuf_chain[i].m);
6147             fp->rx_mbuf_chain[i].m = NULL;
6148             fp->eth_q_stats.mbuf_alloc_rx--;
6149         }
6150     }
6151 }
6152 
6153 static void
6154 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6155 {
6156     struct bxe_softc *sc;
6157     int i, max_agg_queues;
6158 
6159     sc = fp->sc;
6160 
6161     if (fp->rx_mbuf_tag == NULL) {
6162         return;
6163     }
6164 
6165     max_agg_queues = MAX_AGG_QS(sc);
6166 
6167     /* release all mbufs and unload all DMA maps in the TPA pool */
6168     for (i = 0; i < max_agg_queues; i++) {
6169         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6170             bus_dmamap_sync(fp->rx_mbuf_tag,
6171                             fp->rx_tpa_info[i].bd.m_map,
6172                             BUS_DMASYNC_POSTREAD);
6173             bus_dmamap_unload(fp->rx_mbuf_tag,
6174                               fp->rx_tpa_info[i].bd.m_map);
6175         }
6176 
6177         if (fp->rx_tpa_info[i].bd.m != NULL) {
6178             m_freem(fp->rx_tpa_info[i].bd.m);
6179             fp->rx_tpa_info[i].bd.m = NULL;
6180             fp->eth_q_stats.mbuf_alloc_tpa--;
6181         }
6182     }
6183 }
6184 
6185 static void
6186 bxe_free_sge_chain(struct bxe_fastpath *fp)
6187 {
6188     struct bxe_softc *sc;
6189     int i;
6190 
6191     sc = fp->sc;
6192 
6193     if (fp->rx_sge_mbuf_tag == NULL) {
6194         return;
6195     }
6196 
6197     /* rree all mbufs and unload all maps */
6198     for (i = 0; i < RX_SGE_TOTAL; i++) {
6199         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6200             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6201                             fp->rx_sge_mbuf_chain[i].m_map,
6202                             BUS_DMASYNC_POSTREAD);
6203             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6204                               fp->rx_sge_mbuf_chain[i].m_map);
6205         }
6206 
6207         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6208             m_freem(fp->rx_sge_mbuf_chain[i].m);
6209             fp->rx_sge_mbuf_chain[i].m = NULL;
6210             fp->eth_q_stats.mbuf_alloc_sge--;
6211         }
6212     }
6213 }
6214 
6215 static void
6216 bxe_free_fp_buffers(struct bxe_softc *sc)
6217 {
6218     struct bxe_fastpath *fp;
6219     int i;
6220 
6221     for (i = 0; i < sc->num_queues; i++) {
6222         fp = &sc->fp[i];
6223 
6224 #if __FreeBSD_version >= 901504
6225         if (fp->tx_br != NULL) {
6226             /* just in case bxe_mq_flush() wasn't called */
6227             if (mtx_initialized(&fp->tx_mtx)) {
6228                 struct mbuf *m;
6229 
6230                 BXE_FP_TX_LOCK(fp);
6231                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6232                     m_freem(m);
6233                 BXE_FP_TX_UNLOCK(fp);
6234             }
6235         }
6236 #endif
6237 
6238         /* free all RX buffers */
6239         bxe_free_rx_bd_chain(fp);
6240         bxe_free_tpa_pool(fp);
6241         bxe_free_sge_chain(fp);
6242 
6243         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6244             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6245                   fp->eth_q_stats.mbuf_alloc_rx);
6246         }
6247 
6248         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6249             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6250                   fp->eth_q_stats.mbuf_alloc_sge);
6251         }
6252 
6253         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6254             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6255                   fp->eth_q_stats.mbuf_alloc_tpa);
6256         }
6257 
6258         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6259             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6260                   fp->eth_q_stats.mbuf_alloc_tx);
6261         }
6262 
6263         /* XXX verify all mbufs were reclaimed */
6264     }
6265 }
6266 
6267 static int
6268 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6269                      uint16_t            prev_index,
6270                      uint16_t            index)
6271 {
6272     struct bxe_sw_rx_bd *rx_buf;
6273     struct eth_rx_bd *rx_bd;
6274     bus_dma_segment_t segs[1];
6275     bus_dmamap_t map;
6276     struct mbuf *m;
6277     int nsegs, rc;
6278 
6279     rc = 0;
6280 
6281     /* allocate the new RX BD mbuf */
6282     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6283     if (__predict_false(m == NULL)) {
6284         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6285         return (ENOBUFS);
6286     }
6287 
6288     fp->eth_q_stats.mbuf_alloc_rx++;
6289 
6290     /* initialize the mbuf buffer length */
6291     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6292 
6293     /* map the mbuf into non-paged pool */
6294     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6295                                  fp->rx_mbuf_spare_map,
6296                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6297     if (__predict_false(rc != 0)) {
6298         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6299         m_freem(m);
6300         fp->eth_q_stats.mbuf_alloc_rx--;
6301         return (rc);
6302     }
6303 
6304     /* all mbufs must map to a single segment */
6305     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6306 
6307     /* release any existing RX BD mbuf mappings */
6308 
6309     if (prev_index != index) {
6310         rx_buf = &fp->rx_mbuf_chain[prev_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         /*
6319          * We only get here from bxe_rxeof() when the maximum number
6320          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6321          * holds the mbuf in the prev_index so it's OK to NULL it out
6322          * here without concern of a memory leak.
6323          */
6324         fp->rx_mbuf_chain[prev_index].m = NULL;
6325     }
6326 
6327     rx_buf = &fp->rx_mbuf_chain[index];
6328 
6329     if (rx_buf->m_map != NULL) {
6330         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6331                         BUS_DMASYNC_POSTREAD);
6332         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6333     }
6334 
6335     /* save the mbuf and mapping info for a future packet */
6336     map = (prev_index != index) ?
6337               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6338     rx_buf->m_map = fp->rx_mbuf_spare_map;
6339     fp->rx_mbuf_spare_map = map;
6340     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6341                     BUS_DMASYNC_PREREAD);
6342     rx_buf->m = m;
6343 
6344     rx_bd = &fp->rx_chain[index];
6345     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6346     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6347 
6348     return (rc);
6349 }
6350 
6351 static int
6352 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6353                       int                 queue)
6354 {
6355     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6356     bus_dma_segment_t segs[1];
6357     bus_dmamap_t map;
6358     struct mbuf *m;
6359     int nsegs;
6360     int rc = 0;
6361 
6362     /* allocate the new TPA mbuf */
6363     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6364     if (__predict_false(m == NULL)) {
6365         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6366         return (ENOBUFS);
6367     }
6368 
6369     fp->eth_q_stats.mbuf_alloc_tpa++;
6370 
6371     /* initialize the mbuf buffer length */
6372     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6373 
6374     /* map the mbuf into non-paged pool */
6375     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6376                                  fp->rx_tpa_info_mbuf_spare_map,
6377                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6378     if (__predict_false(rc != 0)) {
6379         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6380         m_free(m);
6381         fp->eth_q_stats.mbuf_alloc_tpa--;
6382         return (rc);
6383     }
6384 
6385     /* all mbufs must map to a single segment */
6386     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6387 
6388     /* release any existing TPA mbuf mapping */
6389     if (tpa_info->bd.m_map != NULL) {
6390         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6391                         BUS_DMASYNC_POSTREAD);
6392         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6393     }
6394 
6395     /* save the mbuf and mapping info for the TPA mbuf */
6396     map = tpa_info->bd.m_map;
6397     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6398     fp->rx_tpa_info_mbuf_spare_map = map;
6399     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6400                     BUS_DMASYNC_PREREAD);
6401     tpa_info->bd.m = m;
6402     tpa_info->seg = segs[0];
6403 
6404     return (rc);
6405 }
6406 
6407 /*
6408  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6409  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6410  * chain.
6411  */
6412 static int
6413 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6414                       uint16_t            index)
6415 {
6416     struct bxe_sw_rx_bd *sge_buf;
6417     struct eth_rx_sge *sge;
6418     bus_dma_segment_t segs[1];
6419     bus_dmamap_t map;
6420     struct mbuf *m;
6421     int nsegs;
6422     int rc = 0;
6423 
6424     /* allocate a new SGE mbuf */
6425     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6426     if (__predict_false(m == NULL)) {
6427         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6428         return (ENOMEM);
6429     }
6430 
6431     fp->eth_q_stats.mbuf_alloc_sge++;
6432 
6433     /* initialize the mbuf buffer length */
6434     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6435 
6436     /* map the SGE mbuf into non-paged pool */
6437     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6438                                  fp->rx_sge_mbuf_spare_map,
6439                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6440     if (__predict_false(rc != 0)) {
6441         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6442         m_freem(m);
6443         fp->eth_q_stats.mbuf_alloc_sge--;
6444         return (rc);
6445     }
6446 
6447     /* all mbufs must map to a single segment */
6448     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6449 
6450     sge_buf = &fp->rx_sge_mbuf_chain[index];
6451 
6452     /* release any existing SGE mbuf mapping */
6453     if (sge_buf->m_map != NULL) {
6454         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6455                         BUS_DMASYNC_POSTREAD);
6456         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6457     }
6458 
6459     /* save the mbuf and mapping info for a future packet */
6460     map = sge_buf->m_map;
6461     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6462     fp->rx_sge_mbuf_spare_map = map;
6463     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6464                     BUS_DMASYNC_PREREAD);
6465     sge_buf->m = m;
6466 
6467     sge = &fp->rx_sge_chain[index];
6468     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6469     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6470 
6471     return (rc);
6472 }
6473 
6474 static __noinline int
6475 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6476 {
6477     struct bxe_fastpath *fp;
6478     int i, j, rc = 0;
6479     int ring_prod, cqe_ring_prod;
6480     int max_agg_queues;
6481 
6482     for (i = 0; i < sc->num_queues; i++) {
6483         fp = &sc->fp[i];
6484 
6485         ring_prod = cqe_ring_prod = 0;
6486         fp->rx_bd_cons = 0;
6487         fp->rx_cq_cons = 0;
6488 
6489         /* allocate buffers for the RX BDs in RX BD chain */
6490         for (j = 0; j < sc->max_rx_bufs; j++) {
6491             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6492             if (rc != 0) {
6493                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6494                       i, rc);
6495                 goto bxe_alloc_fp_buffers_error;
6496             }
6497 
6498             ring_prod     = RX_BD_NEXT(ring_prod);
6499             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6500         }
6501 
6502         fp->rx_bd_prod = ring_prod;
6503         fp->rx_cq_prod = cqe_ring_prod;
6504         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6505 
6506         max_agg_queues = MAX_AGG_QS(sc);
6507 
6508         fp->tpa_enable = TRUE;
6509 
6510         /* fill the TPA pool */
6511         for (j = 0; j < max_agg_queues; j++) {
6512             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6513             if (rc != 0) {
6514                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6515                           i, j);
6516                 fp->tpa_enable = FALSE;
6517                 goto bxe_alloc_fp_buffers_error;
6518             }
6519 
6520             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6521         }
6522 
6523         if (fp->tpa_enable) {
6524             /* fill the RX SGE chain */
6525             ring_prod = 0;
6526             for (j = 0; j < RX_SGE_USABLE; j++) {
6527                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6528                 if (rc != 0) {
6529                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6530                               i, ring_prod);
6531                     fp->tpa_enable = FALSE;
6532                     ring_prod = 0;
6533                     goto bxe_alloc_fp_buffers_error;
6534                 }
6535 
6536                 ring_prod = RX_SGE_NEXT(ring_prod);
6537             }
6538 
6539             fp->rx_sge_prod = ring_prod;
6540         }
6541     }
6542 
6543     return (0);
6544 
6545 bxe_alloc_fp_buffers_error:
6546 
6547     /* unwind what was already allocated */
6548     bxe_free_rx_bd_chain(fp);
6549     bxe_free_tpa_pool(fp);
6550     bxe_free_sge_chain(fp);
6551 
6552     return (ENOBUFS);
6553 }
6554 
6555 static void
6556 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6557 {
6558     bxe_dma_free(sc, &sc->fw_stats_dma);
6559 
6560     sc->fw_stats_num = 0;
6561 
6562     sc->fw_stats_req_size = 0;
6563     sc->fw_stats_req = NULL;
6564     sc->fw_stats_req_mapping = 0;
6565 
6566     sc->fw_stats_data_size = 0;
6567     sc->fw_stats_data = NULL;
6568     sc->fw_stats_data_mapping = 0;
6569 }
6570 
6571 static int
6572 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6573 {
6574     uint8_t num_queue_stats;
6575     int num_groups;
6576 
6577     /* number of queues for statistics is number of eth queues */
6578     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6579 
6580     /*
6581      * Total number of FW statistics requests =
6582      *   1 for port stats + 1 for PF stats + num of queues
6583      */
6584     sc->fw_stats_num = (2 + num_queue_stats);
6585 
6586     /*
6587      * Request is built from stats_query_header and an array of
6588      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6589      * rules. The real number or requests is configured in the
6590      * stats_query_header.
6591      */
6592     num_groups =
6593         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6594          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6595 
6596     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6597           sc->fw_stats_num, num_groups);
6598 
6599     sc->fw_stats_req_size =
6600         (sizeof(struct stats_query_header) +
6601          (num_groups * sizeof(struct stats_query_cmd_group)));
6602 
6603     /*
6604      * Data for statistics requests + stats_counter.
6605      * stats_counter holds per-STORM counters that are incremented when
6606      * STORM has finished with the current request. Memory for FCoE
6607      * offloaded statistics are counted anyway, even if they will not be sent.
6608      * VF stats are not accounted for here as the data of VF stats is stored
6609      * in memory allocated by the VF, not here.
6610      */
6611     sc->fw_stats_data_size =
6612         (sizeof(struct stats_counter) +
6613          sizeof(struct per_port_stats) +
6614          sizeof(struct per_pf_stats) +
6615          /* sizeof(struct fcoe_statistics_params) + */
6616          (sizeof(struct per_queue_stats) * num_queue_stats));
6617 
6618     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6619                       &sc->fw_stats_dma, "fw stats") != 0) {
6620         bxe_free_fw_stats_mem(sc);
6621         return (-1);
6622     }
6623 
6624     /* set up the shortcuts */
6625 
6626     sc->fw_stats_req =
6627         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6628     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6629 
6630     sc->fw_stats_data =
6631         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6632                                      sc->fw_stats_req_size);
6633     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6634                                  sc->fw_stats_req_size);
6635 
6636     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6637           (uintmax_t)sc->fw_stats_req_mapping);
6638 
6639     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6640           (uintmax_t)sc->fw_stats_data_mapping);
6641 
6642     return (0);
6643 }
6644 
6645 /*
6646  * Bits map:
6647  * 0-7  - Engine0 load counter.
6648  * 8-15 - Engine1 load counter.
6649  * 16   - Engine0 RESET_IN_PROGRESS bit.
6650  * 17   - Engine1 RESET_IN_PROGRESS bit.
6651  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6652  *        function on the engine
6653  * 19   - Engine1 ONE_IS_LOADED.
6654  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6655  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6656  *        for just the one belonging to its engine).
6657  */
6658 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6659 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6660 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6661 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6662 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6663 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6664 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6665 #define BXE_GLOBAL_RESET_BIT      0x00040000
6666 
6667 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6668 static void
6669 bxe_set_reset_global(struct bxe_softc *sc)
6670 {
6671     uint32_t val;
6672     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6673     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6674     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6675     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6676 }
6677 
6678 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6679 static void
6680 bxe_clear_reset_global(struct bxe_softc *sc)
6681 {
6682     uint32_t val;
6683     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6684     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6685     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6686     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6687 }
6688 
6689 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6690 static uint8_t
6691 bxe_reset_is_global(struct bxe_softc *sc)
6692 {
6693     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6694     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6695     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6696 }
6697 
6698 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6699 static void
6700 bxe_set_reset_done(struct bxe_softc *sc)
6701 {
6702     uint32_t val;
6703     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6704                                  BXE_PATH0_RST_IN_PROG_BIT;
6705 
6706     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6707 
6708     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6709     /* Clear the bit */
6710     val &= ~bit;
6711     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6712 
6713     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6714 }
6715 
6716 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6717 static void
6718 bxe_set_reset_in_progress(struct bxe_softc *sc)
6719 {
6720     uint32_t val;
6721     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6722                                  BXE_PATH0_RST_IN_PROG_BIT;
6723 
6724     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6725 
6726     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6727     /* Set the bit */
6728     val |= bit;
6729     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6730 
6731     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6732 }
6733 
6734 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6735 static uint8_t
6736 bxe_reset_is_done(struct bxe_softc *sc,
6737                   int              engine)
6738 {
6739     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6740     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6741                             BXE_PATH0_RST_IN_PROG_BIT;
6742 
6743     /* return false if bit is set */
6744     return (val & bit) ? FALSE : TRUE;
6745 }
6746 
6747 /* get the load status for an engine, should be run under rtnl lock */
6748 static uint8_t
6749 bxe_get_load_status(struct bxe_softc *sc,
6750                     int              engine)
6751 {
6752     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6753                              BXE_PATH0_LOAD_CNT_MASK;
6754     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6755                               BXE_PATH0_LOAD_CNT_SHIFT;
6756     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6757 
6758     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6759 
6760     val = ((val & mask) >> shift);
6761 
6762     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6763 
6764     return (val != 0);
6765 }
6766 
6767 /* set pf load mark */
6768 /* XXX needs to be under rtnl lock */
6769 static void
6770 bxe_set_pf_load(struct bxe_softc *sc)
6771 {
6772     uint32_t val;
6773     uint32_t val1;
6774     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6775                                   BXE_PATH0_LOAD_CNT_MASK;
6776     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6777                                    BXE_PATH0_LOAD_CNT_SHIFT;
6778 
6779     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6780 
6781     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6782     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6783 
6784     /* get the current counter value */
6785     val1 = ((val & mask) >> shift);
6786 
6787     /* set bit of this PF */
6788     val1 |= (1 << SC_ABS_FUNC(sc));
6789 
6790     /* clear the old value */
6791     val &= ~mask;
6792 
6793     /* set the new one */
6794     val |= ((val1 << shift) & mask);
6795 
6796     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6797 
6798     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6799 }
6800 
6801 /* clear pf load mark */
6802 /* XXX needs to be under rtnl lock */
6803 static uint8_t
6804 bxe_clear_pf_load(struct bxe_softc *sc)
6805 {
6806     uint32_t val1, val;
6807     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6808                                   BXE_PATH0_LOAD_CNT_MASK;
6809     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6810                                    BXE_PATH0_LOAD_CNT_SHIFT;
6811 
6812     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6813     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6814     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6815 
6816     /* get the current counter value */
6817     val1 = (val & mask) >> shift;
6818 
6819     /* clear bit of that PF */
6820     val1 &= ~(1 << SC_ABS_FUNC(sc));
6821 
6822     /* clear the old value */
6823     val &= ~mask;
6824 
6825     /* set the new one */
6826     val |= ((val1 << shift) & mask);
6827 
6828     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6829     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6830     return (val1 != 0);
6831 }
6832 
6833 /* send load requrest to mcp and analyze response */
6834 static int
6835 bxe_nic_load_request(struct bxe_softc *sc,
6836                      uint32_t         *load_code)
6837 {
6838     /* init fw_seq */
6839     sc->fw_seq =
6840         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6841          DRV_MSG_SEQ_NUMBER_MASK);
6842 
6843     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6844 
6845     /* get the current FW pulse sequence */
6846     sc->fw_drv_pulse_wr_seq =
6847         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6848          DRV_PULSE_SEQ_MASK);
6849 
6850     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6851           sc->fw_drv_pulse_wr_seq);
6852 
6853     /* load request */
6854     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6855                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6856 
6857     /* if the MCP fails to respond we must abort */
6858     if (!(*load_code)) {
6859         BLOGE(sc, "MCP response failure!\n");
6860         return (-1);
6861     }
6862 
6863     /* if MCP refused then must abort */
6864     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6865         BLOGE(sc, "MCP refused load request\n");
6866         return (-1);
6867     }
6868 
6869     return (0);
6870 }
6871 
6872 /*
6873  * Check whether another PF has already loaded FW to chip. In virtualized
6874  * environments a pf from anoth VM may have already initialized the device
6875  * including loading FW.
6876  */
6877 static int
6878 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6879                          uint32_t         load_code)
6880 {
6881     uint32_t my_fw, loaded_fw;
6882 
6883     /* is another pf loaded on this engine? */
6884     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6885         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6886         /* build my FW version dword */
6887         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6888                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6889                  (BCM_5710_FW_REVISION_VERSION << 16) +
6890                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6891 
6892         /* read loaded FW from chip */
6893         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6894         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6895               loaded_fw, my_fw);
6896 
6897         /* abort nic load if version mismatch */
6898         if (my_fw != loaded_fw) {
6899             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6900                   loaded_fw, my_fw);
6901             return (-1);
6902         }
6903     }
6904 
6905     return (0);
6906 }
6907 
6908 /* mark PMF if applicable */
6909 static void
6910 bxe_nic_load_pmf(struct bxe_softc *sc,
6911                  uint32_t         load_code)
6912 {
6913     uint32_t ncsi_oem_data_addr;
6914 
6915     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6916         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6917         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6918         /*
6919          * Barrier here for ordering between the writing to sc->port.pmf here
6920          * and reading it from the periodic task.
6921          */
6922         sc->port.pmf = 1;
6923         mb();
6924     } else {
6925         sc->port.pmf = 0;
6926     }
6927 
6928     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6929 
6930     /* XXX needed? */
6931     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6932         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6933             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6934             if (ncsi_oem_data_addr) {
6935                 REG_WR(sc,
6936                        (ncsi_oem_data_addr +
6937                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6938                        0);
6939             }
6940         }
6941     }
6942 }
6943 
6944 static void
6945 bxe_read_mf_cfg(struct bxe_softc *sc)
6946 {
6947     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6948     int abs_func;
6949     int vn;
6950 
6951     if (BXE_NOMCP(sc)) {
6952         return; /* what should be the default bvalue in this case */
6953     }
6954 
6955     /*
6956      * The formula for computing the absolute function number is...
6957      * For 2 port configuration (4 functions per port):
6958      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6959      * For 4 port configuration (2 functions per port):
6960      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6961      */
6962     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6963         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6964         if (abs_func >= E1H_FUNC_MAX) {
6965             break;
6966         }
6967         sc->devinfo.mf_info.mf_config[vn] =
6968             MFCFG_RD(sc, func_mf_config[abs_func].config);
6969     }
6970 
6971     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6972         FUNC_MF_CFG_FUNC_DISABLED) {
6973         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6974         sc->flags |= BXE_MF_FUNC_DIS;
6975     } else {
6976         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6977         sc->flags &= ~BXE_MF_FUNC_DIS;
6978     }
6979 }
6980 
6981 /* acquire split MCP access lock register */
6982 static int bxe_acquire_alr(struct bxe_softc *sc)
6983 {
6984     uint32_t j, val;
6985 
6986     for (j = 0; j < 1000; j++) {
6987         val = (1UL << 31);
6988         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6989         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6990         if (val & (1L << 31))
6991             break;
6992 
6993         DELAY(5000);
6994     }
6995 
6996     if (!(val & (1L << 31))) {
6997         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6998         return (-1);
6999     }
7000 
7001     return (0);
7002 }
7003 
7004 /* release split MCP access lock register */
7005 static void bxe_release_alr(struct bxe_softc *sc)
7006 {
7007     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7008 }
7009 
7010 static void
7011 bxe_fan_failure(struct bxe_softc *sc)
7012 {
7013     int port = SC_PORT(sc);
7014     uint32_t ext_phy_config;
7015 
7016     /* mark the failure */
7017     ext_phy_config =
7018         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7019 
7020     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7021     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7022     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7023              ext_phy_config);
7024 
7025     /* log the failure */
7026     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7027               "the card to prevent permanent damage. "
7028               "Please contact OEM Support for assistance\n");
7029 
7030     /* XXX */
7031 #if 1
7032     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7033 #else
7034     /*
7035      * Schedule device reset (unload)
7036      * This is due to some boards consuming sufficient power when driver is
7037      * up to overheat if fan fails.
7038      */
7039     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7040     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7041 #endif
7042 }
7043 
7044 /* this function is called upon a link interrupt */
7045 static void
7046 bxe_link_attn(struct bxe_softc *sc)
7047 {
7048     uint32_t pause_enabled = 0;
7049     struct host_port_stats *pstats;
7050     int cmng_fns;
7051     struct bxe_fastpath *fp;
7052     int i;
7053 
7054     /* Make sure that we are synced with the current statistics */
7055     bxe_stats_handle(sc, STATS_EVENT_STOP);
7056     BLOGD(sc, DBG_LOAD, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7057     elink_link_update(&sc->link_params, &sc->link_vars);
7058 
7059     if (sc->link_vars.link_up) {
7060 
7061         /* dropless flow control */
7062         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7063             pause_enabled = 0;
7064 
7065             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7066                 pause_enabled = 1;
7067             }
7068 
7069             REG_WR(sc,
7070                    (BAR_USTRORM_INTMEM +
7071                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7072                    pause_enabled);
7073         }
7074 
7075         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7076             pstats = BXE_SP(sc, port_stats);
7077             /* reset old mac stats */
7078             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7079         }
7080 
7081         if (sc->state == BXE_STATE_OPEN) {
7082             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7083 	    /* Restart tx when the link comes back. */
7084 	    FOR_EACH_ETH_QUEUE(sc, i) {
7085 		fp = &sc->fp[i];
7086 		taskqueue_enqueue(fp->tq, &fp->tx_task);
7087 	    }
7088         }
7089 
7090     }
7091 
7092     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7093         cmng_fns = bxe_get_cmng_fns_mode(sc);
7094 
7095         if (cmng_fns != CMNG_FNS_NONE) {
7096             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7097             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7098         } else {
7099             /* rate shaping and fairness are disabled */
7100             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7101         }
7102     }
7103 
7104     bxe_link_report_locked(sc);
7105 
7106     if (IS_MF(sc)) {
7107         ; // XXX bxe_link_sync_notify(sc);
7108     }
7109 }
7110 
7111 static void
7112 bxe_attn_int_asserted(struct bxe_softc *sc,
7113                       uint32_t         asserted)
7114 {
7115     int port = SC_PORT(sc);
7116     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7117                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7118     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7119                                         NIG_REG_MASK_INTERRUPT_PORT0;
7120     uint32_t aeu_mask;
7121     uint32_t nig_mask = 0;
7122     uint32_t reg_addr;
7123     uint32_t igu_acked;
7124     uint32_t cnt;
7125 
7126     if (sc->attn_state & asserted) {
7127         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7128     }
7129 
7130     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7131 
7132     aeu_mask = REG_RD(sc, aeu_addr);
7133 
7134     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7135           aeu_mask, asserted);
7136 
7137     aeu_mask &= ~(asserted & 0x3ff);
7138 
7139     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7140 
7141     REG_WR(sc, aeu_addr, aeu_mask);
7142 
7143     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7144 
7145     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7146     sc->attn_state |= asserted;
7147     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7148 
7149     if (asserted & ATTN_HARD_WIRED_MASK) {
7150         if (asserted & ATTN_NIG_FOR_FUNC) {
7151 
7152 	    bxe_acquire_phy_lock(sc);
7153             /* save nig interrupt mask */
7154             nig_mask = REG_RD(sc, nig_int_mask_addr);
7155 
7156             /* If nig_mask is not set, no need to call the update function */
7157             if (nig_mask) {
7158                 REG_WR(sc, nig_int_mask_addr, 0);
7159 
7160                 bxe_link_attn(sc);
7161             }
7162 
7163             /* handle unicore attn? */
7164         }
7165 
7166         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7167             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7168         }
7169 
7170         if (asserted & GPIO_2_FUNC) {
7171             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7172         }
7173 
7174         if (asserted & GPIO_3_FUNC) {
7175             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7176         }
7177 
7178         if (asserted & GPIO_4_FUNC) {
7179             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7180         }
7181 
7182         if (port == 0) {
7183             if (asserted & ATTN_GENERAL_ATTN_1) {
7184                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7185                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7186             }
7187             if (asserted & ATTN_GENERAL_ATTN_2) {
7188                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7189                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7190             }
7191             if (asserted & ATTN_GENERAL_ATTN_3) {
7192                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7193                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7194             }
7195         } else {
7196             if (asserted & ATTN_GENERAL_ATTN_4) {
7197                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7198                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7199             }
7200             if (asserted & ATTN_GENERAL_ATTN_5) {
7201                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7202                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7203             }
7204             if (asserted & ATTN_GENERAL_ATTN_6) {
7205                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7206                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7207             }
7208         }
7209     } /* hardwired */
7210 
7211     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7212         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7213     } else {
7214         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7215     }
7216 
7217     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7218           asserted,
7219           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7220     REG_WR(sc, reg_addr, asserted);
7221 
7222     /* now set back the mask */
7223     if (asserted & ATTN_NIG_FOR_FUNC) {
7224         /*
7225          * Verify that IGU ack through BAR was written before restoring
7226          * NIG mask. This loop should exit after 2-3 iterations max.
7227          */
7228         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7229             cnt = 0;
7230 
7231             do {
7232                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7233             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7234                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7235 
7236             if (!igu_acked) {
7237                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7238             }
7239 
7240             mb();
7241         }
7242 
7243         REG_WR(sc, nig_int_mask_addr, nig_mask);
7244 
7245 	bxe_release_phy_lock(sc);
7246     }
7247 }
7248 
7249 static void
7250 bxe_print_next_block(struct bxe_softc *sc,
7251                      int              idx,
7252                      const char       *blk)
7253 {
7254     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7255 }
7256 
7257 static int
7258 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7259                               uint32_t         sig,
7260                               int              par_num,
7261                               uint8_t          print)
7262 {
7263     uint32_t cur_bit = 0;
7264     int i = 0;
7265 
7266     for (i = 0; sig; i++) {
7267         cur_bit = ((uint32_t)0x1 << i);
7268         if (sig & cur_bit) {
7269             switch (cur_bit) {
7270             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7271                 if (print)
7272                     bxe_print_next_block(sc, par_num++, "BRB");
7273                 break;
7274             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7275                 if (print)
7276                     bxe_print_next_block(sc, par_num++, "PARSER");
7277                 break;
7278             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7279                 if (print)
7280                     bxe_print_next_block(sc, par_num++, "TSDM");
7281                 break;
7282             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7283                 if (print)
7284                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7285                 break;
7286             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7287                 if (print)
7288                     bxe_print_next_block(sc, par_num++, "TCM");
7289                 break;
7290             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7291                 if (print)
7292                     bxe_print_next_block(sc, par_num++, "TSEMI");
7293                 break;
7294             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7295                 if (print)
7296                     bxe_print_next_block(sc, par_num++, "XPB");
7297                 break;
7298             }
7299 
7300             /* Clear the bit */
7301             sig &= ~cur_bit;
7302         }
7303     }
7304 
7305     return (par_num);
7306 }
7307 
7308 static int
7309 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7310                               uint32_t         sig,
7311                               int              par_num,
7312                               uint8_t          *global,
7313                               uint8_t          print)
7314 {
7315     int i = 0;
7316     uint32_t cur_bit = 0;
7317     for (i = 0; sig; i++) {
7318         cur_bit = ((uint32_t)0x1 << i);
7319         if (sig & cur_bit) {
7320             switch (cur_bit) {
7321             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7322                 if (print)
7323                     bxe_print_next_block(sc, par_num++, "PBF");
7324                 break;
7325             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7326                 if (print)
7327                     bxe_print_next_block(sc, par_num++, "QM");
7328                 break;
7329             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7330                 if (print)
7331                     bxe_print_next_block(sc, par_num++, "TM");
7332                 break;
7333             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7334                 if (print)
7335                     bxe_print_next_block(sc, par_num++, "XSDM");
7336                 break;
7337             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7338                 if (print)
7339                     bxe_print_next_block(sc, par_num++, "XCM");
7340                 break;
7341             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7342                 if (print)
7343                     bxe_print_next_block(sc, par_num++, "XSEMI");
7344                 break;
7345             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7346                 if (print)
7347                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7348                 break;
7349             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7350                 if (print)
7351                     bxe_print_next_block(sc, par_num++, "NIG");
7352                 break;
7353             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7354                 if (print)
7355                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7356                 *global = TRUE;
7357                 break;
7358             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7359                 if (print)
7360                     bxe_print_next_block(sc, par_num++, "DEBUG");
7361                 break;
7362             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7363                 if (print)
7364                     bxe_print_next_block(sc, par_num++, "USDM");
7365                 break;
7366             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7367                 if (print)
7368                     bxe_print_next_block(sc, par_num++, "UCM");
7369                 break;
7370             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7371                 if (print)
7372                     bxe_print_next_block(sc, par_num++, "USEMI");
7373                 break;
7374             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7375                 if (print)
7376                     bxe_print_next_block(sc, par_num++, "UPB");
7377                 break;
7378             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7379                 if (print)
7380                     bxe_print_next_block(sc, par_num++, "CSDM");
7381                 break;
7382             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7383                 if (print)
7384                     bxe_print_next_block(sc, par_num++, "CCM");
7385                 break;
7386             }
7387 
7388             /* Clear the bit */
7389             sig &= ~cur_bit;
7390         }
7391     }
7392 
7393     return (par_num);
7394 }
7395 
7396 static int
7397 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7398                               uint32_t         sig,
7399                               int              par_num,
7400                               uint8_t          print)
7401 {
7402     uint32_t cur_bit = 0;
7403     int i = 0;
7404 
7405     for (i = 0; sig; i++) {
7406         cur_bit = ((uint32_t)0x1 << i);
7407         if (sig & cur_bit) {
7408             switch (cur_bit) {
7409             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7410                 if (print)
7411                     bxe_print_next_block(sc, par_num++, "CSEMI");
7412                 break;
7413             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7414                 if (print)
7415                     bxe_print_next_block(sc, par_num++, "PXP");
7416                 break;
7417             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7418                 if (print)
7419                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7420                 break;
7421             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7422                 if (print)
7423                     bxe_print_next_block(sc, par_num++, "CFC");
7424                 break;
7425             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7426                 if (print)
7427                     bxe_print_next_block(sc, par_num++, "CDU");
7428                 break;
7429             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7430                 if (print)
7431                     bxe_print_next_block(sc, par_num++, "DMAE");
7432                 break;
7433             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7434                 if (print)
7435                     bxe_print_next_block(sc, par_num++, "IGU");
7436                 break;
7437             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7438                 if (print)
7439                     bxe_print_next_block(sc, par_num++, "MISC");
7440                 break;
7441             }
7442 
7443             /* Clear the bit */
7444             sig &= ~cur_bit;
7445         }
7446     }
7447 
7448     return (par_num);
7449 }
7450 
7451 static int
7452 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7453                               uint32_t         sig,
7454                               int              par_num,
7455                               uint8_t          *global,
7456                               uint8_t          print)
7457 {
7458     uint32_t cur_bit = 0;
7459     int i = 0;
7460 
7461     for (i = 0; sig; i++) {
7462         cur_bit = ((uint32_t)0x1 << i);
7463         if (sig & cur_bit) {
7464             switch (cur_bit) {
7465             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7466                 if (print)
7467                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7468                 *global = TRUE;
7469                 break;
7470             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7471                 if (print)
7472                     bxe_print_next_block(sc, par_num++,
7473                               "MCP UMP RX");
7474                 *global = TRUE;
7475                 break;
7476             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7477                 if (print)
7478                     bxe_print_next_block(sc, par_num++,
7479                               "MCP UMP TX");
7480                 *global = TRUE;
7481                 break;
7482             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7483                 if (print)
7484                     bxe_print_next_block(sc, par_num++,
7485                               "MCP SCPAD");
7486                 *global = TRUE;
7487                 break;
7488             }
7489 
7490             /* Clear the bit */
7491             sig &= ~cur_bit;
7492         }
7493     }
7494 
7495     return (par_num);
7496 }
7497 
7498 static int
7499 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7500                               uint32_t         sig,
7501                               int              par_num,
7502                               uint8_t          print)
7503 {
7504     uint32_t cur_bit = 0;
7505     int i = 0;
7506 
7507     for (i = 0; sig; i++) {
7508         cur_bit = ((uint32_t)0x1 << i);
7509         if (sig & cur_bit) {
7510             switch (cur_bit) {
7511             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7512                 if (print)
7513                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7514                 break;
7515             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7516                 if (print)
7517                     bxe_print_next_block(sc, par_num++, "ATC");
7518                 break;
7519             }
7520 
7521             /* Clear the bit */
7522             sig &= ~cur_bit;
7523         }
7524     }
7525 
7526     return (par_num);
7527 }
7528 
7529 static uint8_t
7530 bxe_parity_attn(struct bxe_softc *sc,
7531                 uint8_t          *global,
7532                 uint8_t          print,
7533                 uint32_t         *sig)
7534 {
7535     int par_num = 0;
7536 
7537     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7538         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7539         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7540         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7541         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7542         BLOGE(sc, "Parity error: HW block parity attention:\n"
7543                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7544               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7545               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7546               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7547               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7548               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7549 
7550         if (print)
7551             BLOGI(sc, "Parity errors detected in blocks: ");
7552 
7553         par_num =
7554             bxe_check_blocks_with_parity0(sc, sig[0] &
7555                                           HW_PRTY_ASSERT_SET_0,
7556                                           par_num, print);
7557         par_num =
7558             bxe_check_blocks_with_parity1(sc, sig[1] &
7559                                           HW_PRTY_ASSERT_SET_1,
7560                                           par_num, global, print);
7561         par_num =
7562             bxe_check_blocks_with_parity2(sc, sig[2] &
7563                                           HW_PRTY_ASSERT_SET_2,
7564                                           par_num, print);
7565         par_num =
7566             bxe_check_blocks_with_parity3(sc, sig[3] &
7567                                           HW_PRTY_ASSERT_SET_3,
7568                                           par_num, global, print);
7569         par_num =
7570             bxe_check_blocks_with_parity4(sc, sig[4] &
7571                                           HW_PRTY_ASSERT_SET_4,
7572                                           par_num, print);
7573 
7574         if (print)
7575             BLOGI(sc, "\n");
7576 
7577 	if( *global == TRUE ) {
7578                 BXE_SET_ERROR_BIT(sc, BXE_ERR_GLOBAL);
7579         }
7580 
7581         return (TRUE);
7582     }
7583 
7584     return (FALSE);
7585 }
7586 
7587 static uint8_t
7588 bxe_chk_parity_attn(struct bxe_softc *sc,
7589                     uint8_t          *global,
7590                     uint8_t          print)
7591 {
7592     struct attn_route attn = { {0} };
7593     int port = SC_PORT(sc);
7594 
7595     if(sc->state != BXE_STATE_OPEN)
7596         return FALSE;
7597 
7598     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7599     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7600     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7601     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7602 
7603     /*
7604      * Since MCP attentions can't be disabled inside the block, we need to
7605      * read AEU registers to see whether they're currently disabled
7606      */
7607     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7608                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7609                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7610                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7611 
7612 
7613     if (!CHIP_IS_E1x(sc))
7614         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7615 
7616     return (bxe_parity_attn(sc, global, print, attn.sig));
7617 }
7618 
7619 static void
7620 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7621                          uint32_t         attn)
7622 {
7623     uint32_t val;
7624     boolean_t err_flg = FALSE;
7625 
7626     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7627         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7628         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7629         err_flg = TRUE;
7630         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7631             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7632         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7633             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7634         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7635             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7636         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7637             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7638         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7639             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7640         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7641             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7642         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7643             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7644         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7645             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7646         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7647             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7648     }
7649 
7650     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7651         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7652         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7653 	err_flg = TRUE;
7654         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7655             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7656         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7657             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7658         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7659             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7660         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7661             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7662         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7663             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7664         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7665             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7666     }
7667 
7668     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7669                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7670         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7671               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7672                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7673 	err_flg = TRUE;
7674     }
7675     if (err_flg) {
7676 	BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
7677 	taskqueue_enqueue_timeout(taskqueue_thread,
7678 	    &sc->sp_err_timeout_task, hz/10);
7679     }
7680 
7681 }
7682 
7683 static void
7684 bxe_e1h_disable(struct bxe_softc *sc)
7685 {
7686     int port = SC_PORT(sc);
7687 
7688     bxe_tx_disable(sc);
7689 
7690     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7691 }
7692 
7693 static void
7694 bxe_e1h_enable(struct bxe_softc *sc)
7695 {
7696     int port = SC_PORT(sc);
7697 
7698     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7699 
7700     // XXX bxe_tx_enable(sc);
7701 }
7702 
7703 /*
7704  * called due to MCP event (on pmf):
7705  *   reread new bandwidth configuration
7706  *   configure FW
7707  *   notify others function about the change
7708  */
7709 static void
7710 bxe_config_mf_bw(struct bxe_softc *sc)
7711 {
7712     if (sc->link_vars.link_up) {
7713         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7714         // XXX bxe_link_sync_notify(sc);
7715     }
7716 
7717     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7718 }
7719 
7720 static void
7721 bxe_set_mf_bw(struct bxe_softc *sc)
7722 {
7723     bxe_config_mf_bw(sc);
7724     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7725 }
7726 
7727 static void
7728 bxe_handle_eee_event(struct bxe_softc *sc)
7729 {
7730     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7731     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7732 }
7733 
7734 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7735 
7736 static void
7737 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7738 {
7739     struct eth_stats_info *ether_stat =
7740         &sc->sp->drv_info_to_mcp.ether_stat;
7741 
7742     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7743             ETH_STAT_INFO_VERSION_LEN);
7744 
7745     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7746     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7747                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7748                                           ether_stat->mac_local + MAC_PAD,
7749                                           MAC_PAD, ETH_ALEN);
7750 
7751     ether_stat->mtu_size = sc->mtu;
7752 
7753     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7754     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7755         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7756     }
7757 
7758     // XXX ether_stat->feature_flags |= ???;
7759 
7760     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7761 
7762     ether_stat->txq_size = sc->tx_ring_size;
7763     ether_stat->rxq_size = sc->rx_ring_size;
7764 }
7765 
7766 static void
7767 bxe_handle_drv_info_req(struct bxe_softc *sc)
7768 {
7769     enum drv_info_opcode op_code;
7770     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7771 
7772     /* if drv_info version supported by MFW doesn't match - send NACK */
7773     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7774         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7775         return;
7776     }
7777 
7778     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7779                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7780 
7781     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7782 
7783     switch (op_code) {
7784     case ETH_STATS_OPCODE:
7785         bxe_drv_info_ether_stat(sc);
7786         break;
7787     case FCOE_STATS_OPCODE:
7788     case ISCSI_STATS_OPCODE:
7789     default:
7790         /* if op code isn't supported - send NACK */
7791         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7792         return;
7793     }
7794 
7795     /*
7796      * If we got drv_info attn from MFW then these fields are defined in
7797      * shmem2 for sure
7798      */
7799     SHMEM2_WR(sc, drv_info_host_addr_lo,
7800               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7801     SHMEM2_WR(sc, drv_info_host_addr_hi,
7802               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7803 
7804     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7805 }
7806 
7807 static void
7808 bxe_dcc_event(struct bxe_softc *sc,
7809               uint32_t         dcc_event)
7810 {
7811     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7812 
7813     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7814         /*
7815          * This is the only place besides the function initialization
7816          * where the sc->flags can change so it is done without any
7817          * locks
7818          */
7819         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7820             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7821             sc->flags |= BXE_MF_FUNC_DIS;
7822             bxe_e1h_disable(sc);
7823         } else {
7824             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7825             sc->flags &= ~BXE_MF_FUNC_DIS;
7826             bxe_e1h_enable(sc);
7827         }
7828         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7829     }
7830 
7831     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7832         bxe_config_mf_bw(sc);
7833         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7834     }
7835 
7836     /* Report results to MCP */
7837     if (dcc_event)
7838         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7839     else
7840         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7841 }
7842 
7843 static void
7844 bxe_pmf_update(struct bxe_softc *sc)
7845 {
7846     int port = SC_PORT(sc);
7847     uint32_t val;
7848 
7849     sc->port.pmf = 1;
7850     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7851 
7852     /*
7853      * We need the mb() to ensure the ordering between the writing to
7854      * sc->port.pmf here and reading it from the bxe_periodic_task().
7855      */
7856     mb();
7857 
7858     /* queue a periodic task */
7859     // XXX schedule task...
7860 
7861     // XXX bxe_dcbx_pmf_update(sc);
7862 
7863     /* enable nig attention */
7864     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7865     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7866         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7867         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7868     } else if (!CHIP_IS_E1x(sc)) {
7869         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7870         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7871     }
7872 
7873     bxe_stats_handle(sc, STATS_EVENT_PMF);
7874 }
7875 
7876 static int
7877 bxe_mc_assert(struct bxe_softc *sc)
7878 {
7879     char last_idx;
7880     int i, rc = 0;
7881     uint32_t row0, row1, row2, row3;
7882 
7883     /* XSTORM */
7884     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7885     if (last_idx)
7886         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7887 
7888     /* print the asserts */
7889     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7890 
7891         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7892         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7893         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7894         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7895 
7896         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7897             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7898                   i, row3, row2, row1, row0);
7899             rc++;
7900         } else {
7901             break;
7902         }
7903     }
7904 
7905     /* TSTORM */
7906     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7907     if (last_idx) {
7908         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7909     }
7910 
7911     /* print the asserts */
7912     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7913 
7914         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7915         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7916         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7917         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7918 
7919         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7920             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7921                   i, row3, row2, row1, row0);
7922             rc++;
7923         } else {
7924             break;
7925         }
7926     }
7927 
7928     /* CSTORM */
7929     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7930     if (last_idx) {
7931         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7932     }
7933 
7934     /* print the asserts */
7935     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7936 
7937         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7938         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7939         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7940         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7941 
7942         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7943             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7944                   i, row3, row2, row1, row0);
7945             rc++;
7946         } else {
7947             break;
7948         }
7949     }
7950 
7951     /* USTORM */
7952     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7953     if (last_idx) {
7954         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7955     }
7956 
7957     /* print the asserts */
7958     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7959 
7960         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7961         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7962         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7963         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7964 
7965         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7966             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7967                   i, row3, row2, row1, row0);
7968             rc++;
7969         } else {
7970             break;
7971         }
7972     }
7973 
7974     return (rc);
7975 }
7976 
7977 static void
7978 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7979                          uint32_t         attn)
7980 {
7981     int func = SC_FUNC(sc);
7982     uint32_t val;
7983 
7984     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7985 
7986         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7987 
7988             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7989             bxe_read_mf_cfg(sc);
7990             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7991                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7992             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7993 
7994             if (val & DRV_STATUS_DCC_EVENT_MASK)
7995                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7996 
7997             if (val & DRV_STATUS_SET_MF_BW)
7998                 bxe_set_mf_bw(sc);
7999 
8000             if (val & DRV_STATUS_DRV_INFO_REQ)
8001                 bxe_handle_drv_info_req(sc);
8002 
8003             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8004                 bxe_pmf_update(sc);
8005 
8006             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8007                 bxe_handle_eee_event(sc);
8008 
8009             if (sc->link_vars.periodic_flags &
8010                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8011                 /* sync with link */
8012 		bxe_acquire_phy_lock(sc);
8013                 sc->link_vars.periodic_flags &=
8014                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8015 		bxe_release_phy_lock(sc);
8016                 if (IS_MF(sc))
8017                     ; // XXX bxe_link_sync_notify(sc);
8018                 bxe_link_report(sc);
8019             }
8020 
8021             /*
8022              * Always call it here: bxe_link_report() will
8023              * prevent the link indication duplication.
8024              */
8025             bxe_link_status_update(sc);
8026 
8027         } else if (attn & BXE_MC_ASSERT_BITS) {
8028 
8029             BLOGE(sc, "MC assert!\n");
8030             bxe_mc_assert(sc);
8031             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8032             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8033             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8034             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8035             bxe_int_disable(sc);
8036             BXE_SET_ERROR_BIT(sc, BXE_ERR_MC_ASSERT);
8037             taskqueue_enqueue_timeout(taskqueue_thread,
8038                 &sc->sp_err_timeout_task, hz/10);
8039 
8040         } else if (attn & BXE_MCP_ASSERT) {
8041 
8042             BLOGE(sc, "MCP assert!\n");
8043             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8044             BXE_SET_ERROR_BIT(sc, BXE_ERR_MCP_ASSERT);
8045             taskqueue_enqueue_timeout(taskqueue_thread,
8046                 &sc->sp_err_timeout_task, hz/10);
8047             bxe_int_disable(sc);  /*avoid repetive assert alert */
8048 
8049 
8050         } else {
8051             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8052         }
8053     }
8054 
8055     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8056         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8057         if (attn & BXE_GRC_TIMEOUT) {
8058             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8059             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8060         }
8061         if (attn & BXE_GRC_RSV) {
8062             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8063             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8064         }
8065         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8066     }
8067 }
8068 
8069 static void
8070 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8071                          uint32_t         attn)
8072 {
8073     int port = SC_PORT(sc);
8074     int reg_offset;
8075     uint32_t val0, mask0, val1, mask1;
8076     uint32_t val;
8077     boolean_t err_flg = FALSE;
8078 
8079     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8080         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8081         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8082         /* CFC error attention */
8083         if (val & 0x2) {
8084             BLOGE(sc, "FATAL error from CFC\n");
8085 	    err_flg = TRUE;
8086         }
8087     }
8088 
8089     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8090         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8091         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8092         /* RQ_USDMDP_FIFO_OVERFLOW */
8093         if (val & 0x18000) {
8094             BLOGE(sc, "FATAL error from PXP\n");
8095 	    err_flg = TRUE;
8096         }
8097 
8098         if (!CHIP_IS_E1x(sc)) {
8099             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8100             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8101 	    err_flg = TRUE;
8102         }
8103     }
8104 
8105 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8106 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8107 
8108     if (attn & AEU_PXP2_HW_INT_BIT) {
8109         /*  CQ47854 workaround do not panic on
8110          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8111          */
8112         if (!CHIP_IS_E1x(sc)) {
8113             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8114             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8115             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8116             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8117             /*
8118              * If the only PXP2_EOP_ERROR_BIT is set in
8119              * STS0 and STS1 - clear it
8120              *
8121              * probably we lose additional attentions between
8122              * STS0 and STS_CLR0, in this case user will not
8123              * be notified about them
8124              */
8125             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8126                 !(val1 & mask1))
8127                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8128 
8129             /* print the register, since no one can restore it */
8130             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8131 
8132             /*
8133              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8134              * then notify
8135              */
8136             if (val0 & PXP2_EOP_ERROR_BIT) {
8137                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8138 		err_flg = TRUE;
8139 
8140                 /*
8141                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8142                  * set then clear attention from PXP2 block without panic
8143                  */
8144                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8145                     ((val1 & mask1) == 0))
8146                     attn &= ~AEU_PXP2_HW_INT_BIT;
8147             }
8148         }
8149     }
8150 
8151     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8152         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8153                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8154 
8155         val = REG_RD(sc, reg_offset);
8156         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8157         REG_WR(sc, reg_offset, val);
8158 
8159         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8160               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8161 	err_flg = TRUE;
8162         bxe_panic(sc, ("HW block attention set2\n"));
8163     }
8164     if(err_flg) {
8165         BXE_SET_ERROR_BIT(sc, BXE_ERR_GLOBAL);
8166         taskqueue_enqueue_timeout(taskqueue_thread,
8167            &sc->sp_err_timeout_task, hz/10);
8168     }
8169 
8170 }
8171 
8172 static void
8173 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8174                          uint32_t         attn)
8175 {
8176     int port = SC_PORT(sc);
8177     int reg_offset;
8178     uint32_t val;
8179     boolean_t err_flg = FALSE;
8180 
8181     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8182         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8183         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8184         /* DORQ discard attention */
8185         if (val & 0x2) {
8186             BLOGE(sc, "FATAL error from DORQ\n");
8187 	    err_flg = TRUE;
8188         }
8189     }
8190 
8191     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8192         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8193                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8194 
8195         val = REG_RD(sc, reg_offset);
8196         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8197         REG_WR(sc, reg_offset, val);
8198 
8199         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8200               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8201         err_flg = TRUE;
8202         bxe_panic(sc, ("HW block attention set1\n"));
8203     }
8204     if(err_flg) {
8205         BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
8206         taskqueue_enqueue_timeout(taskqueue_thread,
8207            &sc->sp_err_timeout_task, hz/10);
8208     }
8209 
8210 }
8211 
8212 static void
8213 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8214                          uint32_t         attn)
8215 {
8216     int port = SC_PORT(sc);
8217     int reg_offset;
8218     uint32_t val;
8219 
8220     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8221                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8222 
8223     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8224         val = REG_RD(sc, reg_offset);
8225         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8226         REG_WR(sc, reg_offset, val);
8227 
8228         BLOGW(sc, "SPIO5 hw attention\n");
8229 
8230         /* Fan failure attention */
8231         elink_hw_reset_phy(&sc->link_params);
8232         bxe_fan_failure(sc);
8233     }
8234 
8235     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8236 	bxe_acquire_phy_lock(sc);
8237         elink_handle_module_detect_int(&sc->link_params);
8238 	bxe_release_phy_lock(sc);
8239     }
8240 
8241     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8242         val = REG_RD(sc, reg_offset);
8243         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8244         REG_WR(sc, reg_offset, val);
8245 
8246 
8247         BXE_SET_ERROR_BIT(sc, BXE_ERR_MISC);
8248         taskqueue_enqueue_timeout(taskqueue_thread,
8249            &sc->sp_err_timeout_task, hz/10);
8250 
8251         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8252                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8253     }
8254 }
8255 
8256 static void
8257 bxe_attn_int_deasserted(struct bxe_softc *sc,
8258                         uint32_t         deasserted)
8259 {
8260     struct attn_route attn;
8261     struct attn_route *group_mask;
8262     int port = SC_PORT(sc);
8263     int index;
8264     uint32_t reg_addr;
8265     uint32_t val;
8266     uint32_t aeu_mask;
8267     uint8_t global = FALSE;
8268 
8269     /*
8270      * Need to take HW lock because MCP or other port might also
8271      * try to handle this event.
8272      */
8273     bxe_acquire_alr(sc);
8274 
8275     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8276         /* XXX
8277          * In case of parity errors don't handle attentions so that
8278          * other function would "see" parity errors.
8279          */
8280         // XXX schedule a recovery task...
8281         /* disable HW interrupts */
8282         bxe_int_disable(sc);
8283         BXE_SET_ERROR_BIT(sc, BXE_ERR_PARITY);
8284         taskqueue_enqueue_timeout(taskqueue_thread,
8285            &sc->sp_err_timeout_task, hz/10);
8286         bxe_release_alr(sc);
8287         return;
8288     }
8289 
8290     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8291     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8292     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8293     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8294     if (!CHIP_IS_E1x(sc)) {
8295         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8296     } else {
8297         attn.sig[4] = 0;
8298     }
8299 
8300     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8301           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8302 
8303     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8304         if (deasserted & (1 << index)) {
8305             group_mask = &sc->attn_group[index];
8306 
8307             BLOGD(sc, DBG_INTR,
8308                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8309                   group_mask->sig[0], group_mask->sig[1],
8310                   group_mask->sig[2], group_mask->sig[3],
8311                   group_mask->sig[4]);
8312 
8313             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8314             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8315             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8316             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8317             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8318         }
8319     }
8320 
8321     bxe_release_alr(sc);
8322 
8323     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8324         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8325                     COMMAND_REG_ATTN_BITS_CLR);
8326     } else {
8327         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8328     }
8329 
8330     val = ~deasserted;
8331     BLOGD(sc, DBG_INTR,
8332           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8333           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8334     REG_WR(sc, reg_addr, val);
8335 
8336     if (~sc->attn_state & deasserted) {
8337         BLOGE(sc, "IGU error\n");
8338     }
8339 
8340     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8341                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8342 
8343     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8344 
8345     aeu_mask = REG_RD(sc, reg_addr);
8346 
8347     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8348           aeu_mask, deasserted);
8349     aeu_mask |= (deasserted & 0x3ff);
8350     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8351 
8352     REG_WR(sc, reg_addr, aeu_mask);
8353     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8354 
8355     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8356     sc->attn_state &= ~deasserted;
8357     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8358 }
8359 
8360 static void
8361 bxe_attn_int(struct bxe_softc *sc)
8362 {
8363     /* read local copy of bits */
8364     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8365     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8366     uint32_t attn_state = sc->attn_state;
8367 
8368     /* look for changed bits */
8369     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8370     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8371 
8372     BLOGD(sc, DBG_INTR,
8373           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8374           attn_bits, attn_ack, asserted, deasserted);
8375 
8376     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8377         BLOGE(sc, "BAD attention state\n");
8378     }
8379 
8380     /* handle bits that were raised */
8381     if (asserted) {
8382         bxe_attn_int_asserted(sc, asserted);
8383     }
8384 
8385     if (deasserted) {
8386         bxe_attn_int_deasserted(sc, deasserted);
8387     }
8388 }
8389 
8390 static uint16_t
8391 bxe_update_dsb_idx(struct bxe_softc *sc)
8392 {
8393     struct host_sp_status_block *def_sb = sc->def_sb;
8394     uint16_t rc = 0;
8395 
8396     mb(); /* status block is written to by the chip */
8397 
8398     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8399         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8400         rc |= BXE_DEF_SB_ATT_IDX;
8401     }
8402 
8403     if (sc->def_idx != def_sb->sp_sb.running_index) {
8404         sc->def_idx = def_sb->sp_sb.running_index;
8405         rc |= BXE_DEF_SB_IDX;
8406     }
8407 
8408     mb();
8409 
8410     return (rc);
8411 }
8412 
8413 static inline struct ecore_queue_sp_obj *
8414 bxe_cid_to_q_obj(struct bxe_softc *sc,
8415                  uint32_t         cid)
8416 {
8417     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8418     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8419 }
8420 
8421 static void
8422 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8423 {
8424     struct ecore_mcast_ramrod_params rparam;
8425     int rc;
8426 
8427     memset(&rparam, 0, sizeof(rparam));
8428 
8429     rparam.mcast_obj = &sc->mcast_obj;
8430 
8431     BXE_MCAST_LOCK(sc);
8432 
8433     /* clear pending state for the last command */
8434     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8435 
8436     /* if there are pending mcast commands - send them */
8437     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8438         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8439         if (rc < 0) {
8440             BLOGD(sc, DBG_SP,
8441                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8442         }
8443     }
8444 
8445     BXE_MCAST_UNLOCK(sc);
8446 }
8447 
8448 static void
8449 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8450                               union event_ring_elem *elem)
8451 {
8452     unsigned long ramrod_flags = 0;
8453     int rc = 0;
8454     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8455     struct ecore_vlan_mac_obj *vlan_mac_obj;
8456 
8457     /* always push next commands out, don't wait here */
8458     bit_set(&ramrod_flags, RAMROD_CONT);
8459 
8460     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8461     case ECORE_FILTER_MAC_PENDING:
8462         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8463         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8464         break;
8465 
8466     case ECORE_FILTER_MCAST_PENDING:
8467         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8468         /*
8469          * This is only relevant for 57710 where multicast MACs are
8470          * configured as unicast MACs using the same ramrod.
8471          */
8472         bxe_handle_mcast_eqe(sc);
8473         return;
8474 
8475     default:
8476         BLOGE(sc, "Unsupported classification command: %d\n",
8477               elem->message.data.eth_event.echo);
8478         return;
8479     }
8480 
8481     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8482 
8483     if (rc < 0) {
8484         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8485     } else if (rc > 0) {
8486         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8487     }
8488 }
8489 
8490 static void
8491 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8492                        union event_ring_elem *elem)
8493 {
8494     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8495 
8496     /* send rx_mode command again if was requested */
8497     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8498                                &sc->sp_state)) {
8499         bxe_set_storm_rx_mode(sc);
8500     }
8501 }
8502 
8503 static void
8504 bxe_update_eq_prod(struct bxe_softc *sc,
8505                    uint16_t         prod)
8506 {
8507     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8508     wmb(); /* keep prod updates ordered */
8509 }
8510 
8511 static void
8512 bxe_eq_int(struct bxe_softc *sc)
8513 {
8514     uint16_t hw_cons, sw_cons, sw_prod;
8515     union event_ring_elem *elem;
8516     uint8_t echo;
8517     uint32_t cid;
8518     uint8_t opcode;
8519     int spqe_cnt = 0;
8520     struct ecore_queue_sp_obj *q_obj;
8521     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8522     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8523 
8524     hw_cons = le16toh(*sc->eq_cons_sb);
8525 
8526     /*
8527      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8528      * when we get to the next-page we need to adjust so the loop
8529      * condition below will be met. The next element is the size of a
8530      * regular element and hence incrementing by 1
8531      */
8532     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8533         hw_cons++;
8534     }
8535 
8536     /*
8537      * This function may never run in parallel with itself for a
8538      * specific sc and no need for a read memory barrier here.
8539      */
8540     sw_cons = sc->eq_cons;
8541     sw_prod = sc->eq_prod;
8542 
8543     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8544           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8545 
8546     for (;
8547          sw_cons != hw_cons;
8548          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8549 
8550         elem = &sc->eq[EQ_DESC(sw_cons)];
8551 
8552         /* elem CID originates from FW, actually LE */
8553         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8554         opcode = elem->message.opcode;
8555 
8556         /* handle eq element */
8557         switch (opcode) {
8558 
8559         case EVENT_RING_OPCODE_STAT_QUERY:
8560             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8561                   sc->stats_comp++);
8562             /* nothing to do with stats comp */
8563             goto next_spqe;
8564 
8565         case EVENT_RING_OPCODE_CFC_DEL:
8566             /* handle according to cid range */
8567             /* we may want to verify here that the sc state is HALTING */
8568             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8569             q_obj = bxe_cid_to_q_obj(sc, cid);
8570             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8571                 break;
8572             }
8573             goto next_spqe;
8574 
8575         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8576             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8577             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8578                 break;
8579             }
8580             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8581             goto next_spqe;
8582 
8583         case EVENT_RING_OPCODE_START_TRAFFIC:
8584             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8585             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8586                 break;
8587             }
8588             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8589             goto next_spqe;
8590 
8591         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8592             echo = elem->message.data.function_update_event.echo;
8593             if (echo == SWITCH_UPDATE) {
8594                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8595                 if (f_obj->complete_cmd(sc, f_obj,
8596                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8597                     break;
8598                 }
8599             }
8600             else {
8601                 BLOGD(sc, DBG_SP,
8602                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8603             }
8604             goto next_spqe;
8605 
8606         case EVENT_RING_OPCODE_FORWARD_SETUP:
8607             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8608             if (q_obj->complete_cmd(sc, q_obj,
8609                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8610                 break;
8611             }
8612             goto next_spqe;
8613 
8614         case EVENT_RING_OPCODE_FUNCTION_START:
8615             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8616             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8617                 break;
8618             }
8619             goto next_spqe;
8620 
8621         case EVENT_RING_OPCODE_FUNCTION_STOP:
8622             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8623             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8624                 break;
8625             }
8626             goto next_spqe;
8627         }
8628 
8629         switch (opcode | sc->state) {
8630         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8631         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8632             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8633             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8634             rss_raw->clear_pending(rss_raw);
8635             break;
8636 
8637         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8638         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8639         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8640         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8641         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8642         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8643             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8644             bxe_handle_classification_eqe(sc, elem);
8645             break;
8646 
8647         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8648         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8649         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8650             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8651             bxe_handle_mcast_eqe(sc);
8652             break;
8653 
8654         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8655         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8656         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8657             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8658             bxe_handle_rx_mode_eqe(sc, elem);
8659             break;
8660 
8661         default:
8662             /* unknown event log error and continue */
8663             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8664                   elem->message.opcode, sc->state);
8665         }
8666 
8667 next_spqe:
8668         spqe_cnt++;
8669     } /* for */
8670 
8671     mb();
8672     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8673 
8674     sc->eq_cons = sw_cons;
8675     sc->eq_prod = sw_prod;
8676 
8677     /* make sure that above mem writes were issued towards the memory */
8678     wmb();
8679 
8680     /* update producer */
8681     bxe_update_eq_prod(sc, sc->eq_prod);
8682 }
8683 
8684 static void
8685 bxe_handle_sp_tq(void *context,
8686                  int  pending)
8687 {
8688     struct bxe_softc *sc = (struct bxe_softc *)context;
8689     uint16_t status;
8690 
8691     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8692 
8693     /* what work needs to be performed? */
8694     status = bxe_update_dsb_idx(sc);
8695 
8696     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8697 
8698     /* HW attentions */
8699     if (status & BXE_DEF_SB_ATT_IDX) {
8700         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8701         bxe_attn_int(sc);
8702         status &= ~BXE_DEF_SB_ATT_IDX;
8703     }
8704 
8705     /* SP events: STAT_QUERY and others */
8706     if (status & BXE_DEF_SB_IDX) {
8707         /* handle EQ completions */
8708         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8709         bxe_eq_int(sc);
8710         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8711                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8712         status &= ~BXE_DEF_SB_IDX;
8713     }
8714 
8715     /* if status is non zero then something went wrong */
8716     if (__predict_false(status)) {
8717         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8718     }
8719 
8720     /* ack status block only if something was actually handled */
8721     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8722                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8723 
8724     /*
8725      * Must be called after the EQ processing (since eq leads to sriov
8726      * ramrod completion flows).
8727      * This flow may have been scheduled by the arrival of a ramrod
8728      * completion, or by the sriov code rescheduling itself.
8729      */
8730     // XXX bxe_iov_sp_task(sc);
8731 
8732 }
8733 
8734 static void
8735 bxe_handle_fp_tq(void *context,
8736                  int  pending)
8737 {
8738     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8739     struct bxe_softc *sc = fp->sc;
8740     uint8_t more_tx = FALSE;
8741     uint8_t more_rx = FALSE;
8742 
8743     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8744 
8745     /* XXX
8746      * IFF_DRV_RUNNING state can't be checked here since we process
8747      * slowpath events on a client queue during setup. Instead
8748      * we need to add a "process/continue" flag here that the driver
8749      * can use to tell the task here not to do anything.
8750      */
8751 #if 0
8752     if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8753         return;
8754     }
8755 #endif
8756 
8757     /* update the fastpath index */
8758     bxe_update_fp_sb_idx(fp);
8759 
8760     /* XXX add loop here if ever support multiple tx CoS */
8761     /* fp->txdata[cos] */
8762     if (bxe_has_tx_work(fp)) {
8763         BXE_FP_TX_LOCK(fp);
8764         more_tx = bxe_txeof(sc, fp);
8765         BXE_FP_TX_UNLOCK(fp);
8766     }
8767 
8768     if (bxe_has_rx_work(fp)) {
8769         more_rx = bxe_rxeof(sc, fp);
8770     }
8771 
8772     if (more_rx /*|| more_tx*/) {
8773         /* still more work to do */
8774         taskqueue_enqueue(fp->tq, &fp->tq_task);
8775         return;
8776     }
8777 
8778     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8779                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8780 }
8781 
8782 static void
8783 bxe_task_fp(struct bxe_fastpath *fp)
8784 {
8785     struct bxe_softc *sc = fp->sc;
8786     uint8_t more_tx = FALSE;
8787     uint8_t more_rx = FALSE;
8788 
8789     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8790 
8791     /* update the fastpath index */
8792     bxe_update_fp_sb_idx(fp);
8793 
8794     /* XXX add loop here if ever support multiple tx CoS */
8795     /* fp->txdata[cos] */
8796     if (bxe_has_tx_work(fp)) {
8797         BXE_FP_TX_LOCK(fp);
8798         more_tx = bxe_txeof(sc, fp);
8799         BXE_FP_TX_UNLOCK(fp);
8800     }
8801 
8802     if (bxe_has_rx_work(fp)) {
8803         more_rx = bxe_rxeof(sc, fp);
8804     }
8805 
8806     if (more_rx /*|| more_tx*/) {
8807         /* still more work to do, bail out if this ISR and process later */
8808         taskqueue_enqueue(fp->tq, &fp->tq_task);
8809         return;
8810     }
8811 
8812     /*
8813      * Here we write the fastpath index taken before doing any tx or rx work.
8814      * It is very well possible other hw events occurred up to this point and
8815      * they were actually processed accordingly above. Since we're going to
8816      * write an older fastpath index, an interrupt is coming which we might
8817      * not do any work in.
8818      */
8819     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8820                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8821 }
8822 
8823 /*
8824  * Legacy interrupt entry point.
8825  *
8826  * Verifies that the controller generated the interrupt and
8827  * then calls a separate routine to handle the various
8828  * interrupt causes: link, RX, and TX.
8829  */
8830 static void
8831 bxe_intr_legacy(void *xsc)
8832 {
8833     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8834     struct bxe_fastpath *fp;
8835     uint16_t status, mask;
8836     int i;
8837 
8838     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8839 
8840     /*
8841      * 0 for ustorm, 1 for cstorm
8842      * the bits returned from ack_int() are 0-15
8843      * bit 0 = attention status block
8844      * bit 1 = fast path status block
8845      * a mask of 0x2 or more = tx/rx event
8846      * a mask of 1 = slow path event
8847      */
8848 
8849     status = bxe_ack_int(sc);
8850 
8851     /* the interrupt is not for us */
8852     if (__predict_false(status == 0)) {
8853         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8854         return;
8855     }
8856 
8857     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8858 
8859     FOR_EACH_ETH_QUEUE(sc, i) {
8860         fp = &sc->fp[i];
8861         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8862         if (status & mask) {
8863             /* acknowledge and disable further fastpath interrupts */
8864             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8865             bxe_task_fp(fp);
8866             status &= ~mask;
8867         }
8868     }
8869 
8870     if (__predict_false(status & 0x1)) {
8871         /* acknowledge and disable further slowpath interrupts */
8872         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8873 
8874         /* schedule slowpath handler */
8875         taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8876 
8877         status &= ~0x1;
8878     }
8879 
8880     if (__predict_false(status)) {
8881         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8882     }
8883 }
8884 
8885 /* slowpath interrupt entry point */
8886 static void
8887 bxe_intr_sp(void *xsc)
8888 {
8889     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8890 
8891     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8892 
8893     /* acknowledge and disable further slowpath interrupts */
8894     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8895 
8896     /* schedule slowpath handler */
8897     taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8898 }
8899 
8900 /* fastpath interrupt entry point */
8901 static void
8902 bxe_intr_fp(void *xfp)
8903 {
8904     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8905     struct bxe_softc *sc = fp->sc;
8906 
8907     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8908 
8909     BLOGD(sc, DBG_INTR,
8910           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8911           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8912 
8913     /* acknowledge and disable further fastpath interrupts */
8914     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8915 
8916     bxe_task_fp(fp);
8917 }
8918 
8919 /* Release all interrupts allocated by the driver. */
8920 static void
8921 bxe_interrupt_free(struct bxe_softc *sc)
8922 {
8923     int i;
8924 
8925     switch (sc->interrupt_mode) {
8926     case INTR_MODE_INTX:
8927         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8928         if (sc->intr[0].resource != NULL) {
8929             bus_release_resource(sc->dev,
8930                                  SYS_RES_IRQ,
8931                                  sc->intr[0].rid,
8932                                  sc->intr[0].resource);
8933         }
8934         break;
8935     case INTR_MODE_MSI:
8936         for (i = 0; i < sc->intr_count; i++) {
8937             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8938             if (sc->intr[i].resource && sc->intr[i].rid) {
8939                 bus_release_resource(sc->dev,
8940                                      SYS_RES_IRQ,
8941                                      sc->intr[i].rid,
8942                                      sc->intr[i].resource);
8943             }
8944         }
8945         pci_release_msi(sc->dev);
8946         break;
8947     case INTR_MODE_MSIX:
8948         for (i = 0; i < sc->intr_count; i++) {
8949             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8950             if (sc->intr[i].resource && sc->intr[i].rid) {
8951                 bus_release_resource(sc->dev,
8952                                      SYS_RES_IRQ,
8953                                      sc->intr[i].rid,
8954                                      sc->intr[i].resource);
8955             }
8956         }
8957         pci_release_msi(sc->dev);
8958         break;
8959     default:
8960         /* nothing to do as initial allocation failed */
8961         break;
8962     }
8963 }
8964 
8965 /*
8966  * This function determines and allocates the appropriate
8967  * interrupt based on system capabilites and user request.
8968  *
8969  * The user may force a particular interrupt mode, specify
8970  * the number of receive queues, specify the method for
8971  * distribuitng received frames to receive queues, or use
8972  * the default settings which will automatically select the
8973  * best supported combination.  In addition, the OS may or
8974  * may not support certain combinations of these settings.
8975  * This routine attempts to reconcile the settings requested
8976  * by the user with the capabilites available from the system
8977  * to select the optimal combination of features.
8978  *
8979  * Returns:
8980  *   0 = Success, !0 = Failure.
8981  */
8982 static int
8983 bxe_interrupt_alloc(struct bxe_softc *sc)
8984 {
8985     int msix_count = 0;
8986     int msi_count = 0;
8987     int num_requested = 0;
8988     int num_allocated = 0;
8989     int rid, i, j;
8990     int rc;
8991 
8992     /* get the number of available MSI/MSI-X interrupts from the OS */
8993     if (sc->interrupt_mode > 0) {
8994         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8995             msix_count = pci_msix_count(sc->dev);
8996         }
8997 
8998         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8999             msi_count = pci_msi_count(sc->dev);
9000         }
9001 
9002         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
9003               msi_count, msix_count);
9004     }
9005 
9006     do { /* try allocating MSI-X interrupt resources (at least 2) */
9007         if (sc->interrupt_mode != INTR_MODE_MSIX) {
9008             break;
9009         }
9010 
9011         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
9012             (msix_count < 2)) {
9013             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9014             break;
9015         }
9016 
9017         /* ask for the necessary number of MSI-X vectors */
9018         num_requested = min((sc->num_queues + 1), msix_count);
9019 
9020         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9021 
9022         num_allocated = num_requested;
9023         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9024             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9025             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9026             break;
9027         }
9028 
9029         if (num_allocated < 2) { /* possible? */
9030             BLOGE(sc, "MSI-X allocation less than 2!\n");
9031             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9032             pci_release_msi(sc->dev);
9033             break;
9034         }
9035 
9036         BLOGI(sc, "MSI-X 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 - 1;
9042 
9043         rid = 1; /* initial resource identifier */
9044 
9045         /* allocate the MSI-X vectors */
9046         for (i = 0; i < num_allocated; i++) {
9047             sc->intr[i].rid = (rid + i);
9048 
9049             if ((sc->intr[i].resource =
9050                  bus_alloc_resource_any(sc->dev,
9051                                         SYS_RES_IRQ,
9052                                         &sc->intr[i].rid,
9053                                         RF_ACTIVE)) == NULL) {
9054                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9055                       i, (rid + i));
9056 
9057                 for (j = (i - 1); j >= 0; j--) {
9058                     bus_release_resource(sc->dev,
9059                                          SYS_RES_IRQ,
9060                                          sc->intr[j].rid,
9061                                          sc->intr[j].resource);
9062                 }
9063 
9064                 sc->intr_count = 0;
9065                 sc->num_queues = 0;
9066                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9067                 pci_release_msi(sc->dev);
9068                 break;
9069             }
9070 
9071             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9072         }
9073     } while (0);
9074 
9075     do { /* try allocating MSI vector resources (at least 2) */
9076         if (sc->interrupt_mode != INTR_MODE_MSI) {
9077             break;
9078         }
9079 
9080         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9081             (msi_count < 1)) {
9082             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9083             break;
9084         }
9085 
9086         /* ask for a single MSI vector */
9087         num_requested = 1;
9088 
9089         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9090 
9091         num_allocated = num_requested;
9092         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9093             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9094             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9095             break;
9096         }
9097 
9098         if (num_allocated != 1) { /* possible? */
9099             BLOGE(sc, "MSI allocation is not 1!\n");
9100             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9101             pci_release_msi(sc->dev);
9102             break;
9103         }
9104 
9105         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9106               num_requested, num_allocated);
9107 
9108         /* best effort so use the number of vectors allocated to us */
9109         sc->intr_count = num_allocated;
9110         sc->num_queues = num_allocated;
9111 
9112         rid = 1; /* initial resource identifier */
9113 
9114         sc->intr[0].rid = rid;
9115 
9116         if ((sc->intr[0].resource =
9117              bus_alloc_resource_any(sc->dev,
9118                                     SYS_RES_IRQ,
9119                                     &sc->intr[0].rid,
9120                                     RF_ACTIVE)) == NULL) {
9121             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9122             sc->intr_count = 0;
9123             sc->num_queues = 0;
9124             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9125             pci_release_msi(sc->dev);
9126             break;
9127         }
9128 
9129         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9130     } while (0);
9131 
9132     do { /* try allocating INTx vector resources */
9133         if (sc->interrupt_mode != INTR_MODE_INTX) {
9134             break;
9135         }
9136 
9137         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9138 
9139         /* only one vector for INTx */
9140         sc->intr_count = 1;
9141         sc->num_queues = 1;
9142 
9143         rid = 0; /* initial resource identifier */
9144 
9145         sc->intr[0].rid = rid;
9146 
9147         if ((sc->intr[0].resource =
9148              bus_alloc_resource_any(sc->dev,
9149                                     SYS_RES_IRQ,
9150                                     &sc->intr[0].rid,
9151                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9152             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9153             sc->intr_count = 0;
9154             sc->num_queues = 0;
9155             sc->interrupt_mode = -1; /* Failed! */
9156             break;
9157         }
9158 
9159         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9160     } while (0);
9161 
9162     if (sc->interrupt_mode == -1) {
9163         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9164         rc = 1;
9165     } else {
9166         BLOGD(sc, DBG_LOAD,
9167               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9168               sc->interrupt_mode, sc->num_queues);
9169         rc = 0;
9170     }
9171 
9172     return (rc);
9173 }
9174 
9175 static void
9176 bxe_interrupt_detach(struct bxe_softc *sc)
9177 {
9178     struct bxe_fastpath *fp;
9179     int i;
9180 
9181     /* release interrupt resources */
9182     for (i = 0; i < sc->intr_count; i++) {
9183         if (sc->intr[i].resource && sc->intr[i].tag) {
9184             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9185             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9186         }
9187     }
9188 
9189     for (i = 0; i < sc->num_queues; i++) {
9190         fp = &sc->fp[i];
9191         if (fp->tq) {
9192             taskqueue_drain(fp->tq, &fp->tq_task);
9193             taskqueue_drain(fp->tq, &fp->tx_task);
9194             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9195                 NULL))
9196                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9197         }
9198 
9199         for (i = 0; i < sc->num_queues; i++) {
9200             fp = &sc->fp[i];
9201             if (fp->tq != NULL) {
9202                 taskqueue_free(fp->tq);
9203                 fp->tq = NULL;
9204             }
9205         }
9206     }
9207 
9208     if (sc->sp_tq) {
9209         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9210         taskqueue_free(sc->sp_tq);
9211         sc->sp_tq = NULL;
9212     }
9213 }
9214 
9215 /*
9216  * Enables interrupts and attach to the ISR.
9217  *
9218  * When using multiple MSI/MSI-X vectors the first vector
9219  * is used for slowpath operations while all remaining
9220  * vectors are used for fastpath operations.  If only a
9221  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9222  * ISR must look for both slowpath and fastpath completions.
9223  */
9224 static int
9225 bxe_interrupt_attach(struct bxe_softc *sc)
9226 {
9227     struct bxe_fastpath *fp;
9228     int rc = 0;
9229     int i;
9230 
9231     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9232              "bxe%d_sp_tq", sc->unit);
9233     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9234     sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9235                                  taskqueue_thread_enqueue,
9236                                  &sc->sp_tq);
9237     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9238                             "%s", sc->sp_tq_name);
9239 
9240 
9241     for (i = 0; i < sc->num_queues; i++) {
9242         fp = &sc->fp[i];
9243         snprintf(fp->tq_name, sizeof(fp->tq_name),
9244                  "bxe%d_fp%d_tq", sc->unit, i);
9245         NET_TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9246         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9247         fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9248                                   taskqueue_thread_enqueue,
9249                                   &fp->tq);
9250         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9251                           bxe_tx_mq_start_deferred, fp);
9252         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9253                                 "%s", fp->tq_name);
9254     }
9255 
9256     /* setup interrupt handlers */
9257     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9258         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9259 
9260         /*
9261          * Setup the interrupt handler. Note that we pass the driver instance
9262          * to the interrupt handler for the slowpath.
9263          */
9264         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9265                                  (INTR_TYPE_NET | INTR_MPSAFE),
9266                                  NULL, bxe_intr_sp, sc,
9267                                  &sc->intr[0].tag)) != 0) {
9268             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9269             goto bxe_interrupt_attach_exit;
9270         }
9271 
9272         bus_describe_intr(sc->dev, sc->intr[0].resource,
9273                           sc->intr[0].tag, "sp");
9274 
9275         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9276 
9277         /* initialize the fastpath vectors (note the first was used for sp) */
9278         for (i = 0; i < sc->num_queues; i++) {
9279             fp = &sc->fp[i];
9280             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9281 
9282             /*
9283              * Setup the interrupt handler. Note that we pass the
9284              * fastpath context to the interrupt handler in this
9285              * case.
9286              */
9287             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9288                                      (INTR_TYPE_NET | INTR_MPSAFE),
9289                                      NULL, bxe_intr_fp, fp,
9290                                      &sc->intr[i + 1].tag)) != 0) {
9291                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9292                       (i + 1), rc);
9293                 goto bxe_interrupt_attach_exit;
9294             }
9295 
9296             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9297                               sc->intr[i + 1].tag, "fp%02d", i);
9298 
9299             /* bind the fastpath instance to a cpu */
9300             if (sc->num_queues > 1) {
9301                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9302             }
9303 
9304             fp->state = BXE_FP_STATE_IRQ;
9305         }
9306     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9307         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9308 
9309         /*
9310          * Setup the interrupt handler. Note that we pass the
9311          * driver instance to the interrupt handler which
9312          * will handle both the slowpath and fastpath.
9313          */
9314         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9315                                  (INTR_TYPE_NET | INTR_MPSAFE),
9316                                  NULL, bxe_intr_legacy, sc,
9317                                  &sc->intr[0].tag)) != 0) {
9318             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9319             goto bxe_interrupt_attach_exit;
9320         }
9321 
9322     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9323         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9324 
9325         /*
9326          * Setup the interrupt handler. Note that we pass the
9327          * driver instance to the interrupt handler which
9328          * will handle both the slowpath and fastpath.
9329          */
9330         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9331                                  (INTR_TYPE_NET | INTR_MPSAFE),
9332                                  NULL, bxe_intr_legacy, sc,
9333                                  &sc->intr[0].tag)) != 0) {
9334             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9335             goto bxe_interrupt_attach_exit;
9336         }
9337     }
9338 
9339 bxe_interrupt_attach_exit:
9340 
9341     return (rc);
9342 }
9343 
9344 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9345 static int  bxe_init_hw_common(struct bxe_softc *sc);
9346 static int  bxe_init_hw_port(struct bxe_softc *sc);
9347 static int  bxe_init_hw_func(struct bxe_softc *sc);
9348 static void bxe_reset_common(struct bxe_softc *sc);
9349 static void bxe_reset_port(struct bxe_softc *sc);
9350 static void bxe_reset_func(struct bxe_softc *sc);
9351 static int  bxe_gunzip_init(struct bxe_softc *sc);
9352 static void bxe_gunzip_end(struct bxe_softc *sc);
9353 static int  bxe_init_firmware(struct bxe_softc *sc);
9354 static void bxe_release_firmware(struct bxe_softc *sc);
9355 
9356 static struct
9357 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9358     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9359     .init_hw_cmn      = bxe_init_hw_common,
9360     .init_hw_port     = bxe_init_hw_port,
9361     .init_hw_func     = bxe_init_hw_func,
9362 
9363     .reset_hw_cmn     = bxe_reset_common,
9364     .reset_hw_port    = bxe_reset_port,
9365     .reset_hw_func    = bxe_reset_func,
9366 
9367     .gunzip_init      = bxe_gunzip_init,
9368     .gunzip_end       = bxe_gunzip_end,
9369 
9370     .init_fw          = bxe_init_firmware,
9371     .release_fw       = bxe_release_firmware,
9372 };
9373 
9374 static void
9375 bxe_init_func_obj(struct bxe_softc *sc)
9376 {
9377     sc->dmae_ready = 0;
9378 
9379     ecore_init_func_obj(sc,
9380                         &sc->func_obj,
9381                         BXE_SP(sc, func_rdata),
9382                         BXE_SP_MAPPING(sc, func_rdata),
9383                         BXE_SP(sc, func_afex_rdata),
9384                         BXE_SP_MAPPING(sc, func_afex_rdata),
9385                         &bxe_func_sp_drv);
9386 }
9387 
9388 static int
9389 bxe_init_hw(struct bxe_softc *sc,
9390             uint32_t         load_code)
9391 {
9392     struct ecore_func_state_params func_params = { NULL };
9393     int rc;
9394 
9395     /* prepare the parameters for function state transitions */
9396     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9397 
9398     func_params.f_obj = &sc->func_obj;
9399     func_params.cmd = ECORE_F_CMD_HW_INIT;
9400 
9401     func_params.params.hw_init.load_phase = load_code;
9402 
9403     /*
9404      * Via a plethora of function pointers, we will eventually reach
9405      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9406      */
9407     rc = ecore_func_state_change(sc, &func_params);
9408 
9409     return (rc);
9410 }
9411 
9412 static void
9413 bxe_fill(struct bxe_softc *sc,
9414          uint32_t         addr,
9415          int              fill,
9416          uint32_t         len)
9417 {
9418     uint32_t i;
9419 
9420     if (!(len % 4) && !(addr % 4)) {
9421         for (i = 0; i < len; i += 4) {
9422             REG_WR(sc, (addr + i), fill);
9423         }
9424     } else {
9425         for (i = 0; i < len; i++) {
9426             REG_WR8(sc, (addr + i), fill);
9427         }
9428     }
9429 }
9430 
9431 /* writes FP SP data to FW - data_size in dwords */
9432 static void
9433 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9434                   int              fw_sb_id,
9435                   uint32_t         *sb_data_p,
9436                   uint32_t         data_size)
9437 {
9438     int index;
9439 
9440     for (index = 0; index < data_size; index++) {
9441         REG_WR(sc,
9442                (BAR_CSTRORM_INTMEM +
9443                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9444                 (sizeof(uint32_t) * index)),
9445                *(sb_data_p + index));
9446     }
9447 }
9448 
9449 static void
9450 bxe_zero_fp_sb(struct bxe_softc *sc,
9451                int              fw_sb_id)
9452 {
9453     struct hc_status_block_data_e2 sb_data_e2;
9454     struct hc_status_block_data_e1x sb_data_e1x;
9455     uint32_t *sb_data_p;
9456     uint32_t data_size = 0;
9457 
9458     if (!CHIP_IS_E1x(sc)) {
9459         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9460         sb_data_e2.common.state = SB_DISABLED;
9461         sb_data_e2.common.p_func.vf_valid = FALSE;
9462         sb_data_p = (uint32_t *)&sb_data_e2;
9463         data_size = (sizeof(struct hc_status_block_data_e2) /
9464                      sizeof(uint32_t));
9465     } else {
9466         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9467         sb_data_e1x.common.state = SB_DISABLED;
9468         sb_data_e1x.common.p_func.vf_valid = FALSE;
9469         sb_data_p = (uint32_t *)&sb_data_e1x;
9470         data_size = (sizeof(struct hc_status_block_data_e1x) /
9471                      sizeof(uint32_t));
9472     }
9473 
9474     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9475 
9476     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9477              0, CSTORM_STATUS_BLOCK_SIZE);
9478     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9479              0, CSTORM_SYNC_BLOCK_SIZE);
9480 }
9481 
9482 static void
9483 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9484                   struct hc_sp_status_block_data *sp_sb_data)
9485 {
9486     int i;
9487 
9488     for (i = 0;
9489          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9490          i++) {
9491         REG_WR(sc,
9492                (BAR_CSTRORM_INTMEM +
9493                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9494                 (i * sizeof(uint32_t))),
9495                *((uint32_t *)sp_sb_data + i));
9496     }
9497 }
9498 
9499 static void
9500 bxe_zero_sp_sb(struct bxe_softc *sc)
9501 {
9502     struct hc_sp_status_block_data sp_sb_data;
9503 
9504     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9505 
9506     sp_sb_data.state           = SB_DISABLED;
9507     sp_sb_data.p_func.vf_valid = FALSE;
9508 
9509     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9510 
9511     bxe_fill(sc,
9512              (BAR_CSTRORM_INTMEM +
9513               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9514               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9515     bxe_fill(sc,
9516              (BAR_CSTRORM_INTMEM +
9517               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9518               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9519 }
9520 
9521 static void
9522 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9523                              int                       igu_sb_id,
9524                              int                       igu_seg_id)
9525 {
9526     hc_sm->igu_sb_id      = igu_sb_id;
9527     hc_sm->igu_seg_id     = igu_seg_id;
9528     hc_sm->timer_value    = 0xFF;
9529     hc_sm->time_to_expire = 0xFFFFFFFF;
9530 }
9531 
9532 static void
9533 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9534 {
9535     /* zero out state machine indices */
9536 
9537     /* rx indices */
9538     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9539 
9540     /* tx indices */
9541     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9542     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9543     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9544     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9545 
9546     /* map indices */
9547 
9548     /* rx indices */
9549     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9550         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9551 
9552     /* tx indices */
9553     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9554         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9555     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9556         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9557     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9558         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9559     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9560         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9561 }
9562 
9563 static void
9564 bxe_init_sb(struct bxe_softc *sc,
9565             bus_addr_t       busaddr,
9566             int              vfid,
9567             uint8_t          vf_valid,
9568             int              fw_sb_id,
9569             int              igu_sb_id)
9570 {
9571     struct hc_status_block_data_e2  sb_data_e2;
9572     struct hc_status_block_data_e1x sb_data_e1x;
9573     struct hc_status_block_sm       *hc_sm_p;
9574     uint32_t *sb_data_p;
9575     int igu_seg_id;
9576     int data_size;
9577 
9578     if (CHIP_INT_MODE_IS_BC(sc)) {
9579         igu_seg_id = HC_SEG_ACCESS_NORM;
9580     } else {
9581         igu_seg_id = IGU_SEG_ACCESS_NORM;
9582     }
9583 
9584     bxe_zero_fp_sb(sc, fw_sb_id);
9585 
9586     if (!CHIP_IS_E1x(sc)) {
9587         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9588         sb_data_e2.common.state = SB_ENABLED;
9589         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9590         sb_data_e2.common.p_func.vf_id = vfid;
9591         sb_data_e2.common.p_func.vf_valid = vf_valid;
9592         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9593         sb_data_e2.common.same_igu_sb_1b = TRUE;
9594         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9595         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9596         hc_sm_p = sb_data_e2.common.state_machine;
9597         sb_data_p = (uint32_t *)&sb_data_e2;
9598         data_size = (sizeof(struct hc_status_block_data_e2) /
9599                      sizeof(uint32_t));
9600         bxe_map_sb_state_machines(sb_data_e2.index_data);
9601     } else {
9602         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9603         sb_data_e1x.common.state = SB_ENABLED;
9604         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9605         sb_data_e1x.common.p_func.vf_id = 0xff;
9606         sb_data_e1x.common.p_func.vf_valid = FALSE;
9607         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9608         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9609         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9610         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9611         hc_sm_p = sb_data_e1x.common.state_machine;
9612         sb_data_p = (uint32_t *)&sb_data_e1x;
9613         data_size = (sizeof(struct hc_status_block_data_e1x) /
9614                      sizeof(uint32_t));
9615         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9616     }
9617 
9618     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9619     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9620 
9621     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9622 
9623     /* write indices to HW - PCI guarantees endianity of regpairs */
9624     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9625 }
9626 
9627 static inline uint8_t
9628 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9629 {
9630     if (CHIP_IS_E1x(fp->sc)) {
9631         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9632     } else {
9633         return (fp->cl_id);
9634     }
9635 }
9636 
9637 static inline uint32_t
9638 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9639                            struct bxe_fastpath *fp)
9640 {
9641     uint32_t offset = BAR_USTRORM_INTMEM;
9642 
9643     if (!CHIP_IS_E1x(sc)) {
9644         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9645     } else {
9646         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9647     }
9648 
9649     return (offset);
9650 }
9651 
9652 static void
9653 bxe_init_eth_fp(struct bxe_softc *sc,
9654                 int              idx)
9655 {
9656     struct bxe_fastpath *fp = &sc->fp[idx];
9657     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9658     unsigned long q_type = 0;
9659     int cos;
9660 
9661     fp->sc    = sc;
9662     fp->index = idx;
9663 
9664     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9665     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9666 
9667     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9668                     (SC_L_ID(sc) + idx) :
9669                     /* want client ID same as IGU SB ID for non-E1 */
9670                     fp->igu_sb_id;
9671     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9672 
9673     /* setup sb indices */
9674     if (!CHIP_IS_E1x(sc)) {
9675         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9676         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9677     } else {
9678         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9679         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9680     }
9681 
9682     /* init shortcut */
9683     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9684 
9685     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9686 
9687     /*
9688      * XXX If multiple CoS is ever supported then each fastpath structure
9689      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9690      */
9691     for (cos = 0; cos < sc->max_cos; cos++) {
9692         cids[cos] = idx;
9693     }
9694     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9695 
9696     /* nothing more for a VF to do */
9697     if (IS_VF(sc)) {
9698         return;
9699     }
9700 
9701     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9702                 fp->fw_sb_id, fp->igu_sb_id);
9703 
9704     bxe_update_fp_sb_idx(fp);
9705 
9706     /* Configure Queue State object */
9707     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9708     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9709 
9710     ecore_init_queue_obj(sc,
9711                          &sc->sp_objs[idx].q_obj,
9712                          fp->cl_id,
9713                          cids,
9714                          sc->max_cos,
9715                          SC_FUNC(sc),
9716                          BXE_SP(sc, q_rdata),
9717                          BXE_SP_MAPPING(sc, q_rdata),
9718                          q_type);
9719 
9720     /* configure classification DBs */
9721     ecore_init_mac_obj(sc,
9722                        &sc->sp_objs[idx].mac_obj,
9723                        fp->cl_id,
9724                        idx,
9725                        SC_FUNC(sc),
9726                        BXE_SP(sc, mac_rdata),
9727                        BXE_SP_MAPPING(sc, mac_rdata),
9728                        ECORE_FILTER_MAC_PENDING,
9729                        &sc->sp_state,
9730                        ECORE_OBJ_TYPE_RX_TX,
9731                        &sc->macs_pool);
9732 
9733     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9734           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9735 }
9736 
9737 static inline void
9738 bxe_update_rx_prod(struct bxe_softc    *sc,
9739                    struct bxe_fastpath *fp,
9740                    uint16_t            rx_bd_prod,
9741                    uint16_t            rx_cq_prod,
9742                    uint16_t            rx_sge_prod)
9743 {
9744     struct ustorm_eth_rx_producers rx_prods = { 0 };
9745     uint32_t i;
9746 
9747     /* update producers */
9748     rx_prods.bd_prod  = rx_bd_prod;
9749     rx_prods.cqe_prod = rx_cq_prod;
9750     rx_prods.sge_prod = rx_sge_prod;
9751 
9752     /*
9753      * Make sure that the BD and SGE data is updated before updating the
9754      * producers since FW might read the BD/SGE right after the producer
9755      * is updated.
9756      * This is only applicable for weak-ordered memory model archs such
9757      * as IA-64. The following barrier is also mandatory since FW will
9758      * assumes BDs must have buffers.
9759      */
9760     wmb();
9761 
9762     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9763         REG_WR(sc,
9764                (fp->ustorm_rx_prods_offset + (i * 4)),
9765                ((uint32_t *)&rx_prods)[i]);
9766     }
9767 
9768     wmb(); /* keep prod updates ordered */
9769 
9770     BLOGD(sc, DBG_RX,
9771           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9772           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9773 }
9774 
9775 static void
9776 bxe_init_rx_rings(struct bxe_softc *sc)
9777 {
9778     struct bxe_fastpath *fp;
9779     int i;
9780 
9781     for (i = 0; i < sc->num_queues; i++) {
9782         fp = &sc->fp[i];
9783 
9784         fp->rx_bd_cons = 0;
9785 
9786         /*
9787          * Activate the BD ring...
9788          * Warning, this will generate an interrupt (to the TSTORM)
9789          * so this can only be done after the chip is initialized
9790          */
9791         bxe_update_rx_prod(sc, fp,
9792                            fp->rx_bd_prod,
9793                            fp->rx_cq_prod,
9794                            fp->rx_sge_prod);
9795 
9796         if (i != 0) {
9797             continue;
9798         }
9799 
9800         if (CHIP_IS_E1(sc)) {
9801             REG_WR(sc,
9802                    (BAR_USTRORM_INTMEM +
9803                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9804                    U64_LO(fp->rcq_dma.paddr));
9805             REG_WR(sc,
9806                    (BAR_USTRORM_INTMEM +
9807                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9808                    U64_HI(fp->rcq_dma.paddr));
9809         }
9810     }
9811 }
9812 
9813 static void
9814 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9815 {
9816     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9817     fp->tx_db.data.zero_fill1 = 0;
9818     fp->tx_db.data.prod = 0;
9819 
9820     fp->tx_pkt_prod = 0;
9821     fp->tx_pkt_cons = 0;
9822     fp->tx_bd_prod = 0;
9823     fp->tx_bd_cons = 0;
9824     fp->eth_q_stats.tx_pkts = 0;
9825 }
9826 
9827 static inline void
9828 bxe_init_tx_rings(struct bxe_softc *sc)
9829 {
9830     int i;
9831 
9832     for (i = 0; i < sc->num_queues; i++) {
9833         bxe_init_tx_ring_one(&sc->fp[i]);
9834     }
9835 }
9836 
9837 static void
9838 bxe_init_def_sb(struct bxe_softc *sc)
9839 {
9840     struct host_sp_status_block *def_sb = sc->def_sb;
9841     bus_addr_t mapping = sc->def_sb_dma.paddr;
9842     int igu_sp_sb_index;
9843     int igu_seg_id;
9844     int port = SC_PORT(sc);
9845     int func = SC_FUNC(sc);
9846     int reg_offset, reg_offset_en5;
9847     uint64_t section;
9848     int index, sindex;
9849     struct hc_sp_status_block_data sp_sb_data;
9850 
9851     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9852 
9853     if (CHIP_INT_MODE_IS_BC(sc)) {
9854         igu_sp_sb_index = DEF_SB_IGU_ID;
9855         igu_seg_id = HC_SEG_ACCESS_DEF;
9856     } else {
9857         igu_sp_sb_index = sc->igu_dsb_id;
9858         igu_seg_id = IGU_SEG_ACCESS_DEF;
9859     }
9860 
9861     /* attentions */
9862     section = ((uint64_t)mapping +
9863                offsetof(struct host_sp_status_block, atten_status_block));
9864     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9865     sc->attn_state = 0;
9866 
9867     reg_offset = (port) ?
9868                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9869                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9870     reg_offset_en5 = (port) ?
9871                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9872                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9873 
9874     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9875         /* take care of sig[0]..sig[4] */
9876         for (sindex = 0; sindex < 4; sindex++) {
9877             sc->attn_group[index].sig[sindex] =
9878                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9879         }
9880 
9881         if (!CHIP_IS_E1x(sc)) {
9882             /*
9883              * enable5 is separate from the rest of the registers,
9884              * and the address skip is 4 and not 16 between the
9885              * different groups
9886              */
9887             sc->attn_group[index].sig[4] =
9888                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9889         } else {
9890             sc->attn_group[index].sig[4] = 0;
9891         }
9892     }
9893 
9894     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9895         reg_offset = (port) ?
9896                          HC_REG_ATTN_MSG1_ADDR_L :
9897                          HC_REG_ATTN_MSG0_ADDR_L;
9898         REG_WR(sc, reg_offset, U64_LO(section));
9899         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9900     } else if (!CHIP_IS_E1x(sc)) {
9901         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9902         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9903     }
9904 
9905     section = ((uint64_t)mapping +
9906                offsetof(struct host_sp_status_block, sp_sb));
9907 
9908     bxe_zero_sp_sb(sc);
9909 
9910     /* PCI guarantees endianity of regpair */
9911     sp_sb_data.state           = SB_ENABLED;
9912     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9913     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9914     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9915     sp_sb_data.igu_seg_id      = igu_seg_id;
9916     sp_sb_data.p_func.pf_id    = func;
9917     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9918     sp_sb_data.p_func.vf_id    = 0xff;
9919 
9920     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9921 
9922     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9923 }
9924 
9925 static void
9926 bxe_init_sp_ring(struct bxe_softc *sc)
9927 {
9928     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9929     sc->spq_prod_idx = 0;
9930     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9931     sc->spq_prod_bd = sc->spq;
9932     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9933 }
9934 
9935 static void
9936 bxe_init_eq_ring(struct bxe_softc *sc)
9937 {
9938     union event_ring_elem *elem;
9939     int i;
9940 
9941     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9942         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9943 
9944         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9945                                                  BCM_PAGE_SIZE *
9946                                                  (i % NUM_EQ_PAGES)));
9947         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9948                                                  BCM_PAGE_SIZE *
9949                                                  (i % NUM_EQ_PAGES)));
9950     }
9951 
9952     sc->eq_cons    = 0;
9953     sc->eq_prod    = NUM_EQ_DESC;
9954     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9955 
9956     atomic_store_rel_long(&sc->eq_spq_left,
9957                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9958                                NUM_EQ_DESC) - 1));
9959 }
9960 
9961 static void
9962 bxe_init_internal_common(struct bxe_softc *sc)
9963 {
9964     int i;
9965 
9966     /*
9967      * Zero this manually as its initialization is currently missing
9968      * in the initTool.
9969      */
9970     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9971         REG_WR(sc,
9972                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9973                0);
9974     }
9975 
9976     if (!CHIP_IS_E1x(sc)) {
9977         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9978                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9979     }
9980 }
9981 
9982 static void
9983 bxe_init_internal(struct bxe_softc *sc,
9984                   uint32_t         load_code)
9985 {
9986     switch (load_code) {
9987     case FW_MSG_CODE_DRV_LOAD_COMMON:
9988     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9989         bxe_init_internal_common(sc);
9990         /* no break */
9991 
9992     case FW_MSG_CODE_DRV_LOAD_PORT:
9993         /* nothing to do */
9994         /* no break */
9995 
9996     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9997         /* internal memory per function is initialized inside bxe_pf_init */
9998         break;
9999 
10000     default:
10001         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
10002         break;
10003     }
10004 }
10005 
10006 static void
10007 storm_memset_func_cfg(struct bxe_softc                         *sc,
10008                       struct tstorm_eth_function_common_config *tcfg,
10009                       uint16_t                                  abs_fid)
10010 {
10011     uint32_t addr;
10012     size_t size;
10013 
10014     addr = (BAR_TSTRORM_INTMEM +
10015             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10016     size = sizeof(struct tstorm_eth_function_common_config);
10017     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10018 }
10019 
10020 static void
10021 bxe_func_init(struct bxe_softc            *sc,
10022               struct bxe_func_init_params *p)
10023 {
10024     struct tstorm_eth_function_common_config tcfg = { 0 };
10025 
10026     if (CHIP_IS_E1x(sc)) {
10027         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10028     }
10029 
10030     /* Enable the function in the FW */
10031     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10032     storm_memset_func_en(sc, p->func_id, 1);
10033 
10034     /* spq */
10035     if (p->func_flgs & FUNC_FLG_SPQ) {
10036         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10037         REG_WR(sc,
10038                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10039                p->spq_prod);
10040     }
10041 }
10042 
10043 /*
10044  * Calculates the sum of vn_min_rates.
10045  * It's needed for further normalizing of the min_rates.
10046  * Returns:
10047  *   sum of vn_min_rates.
10048  *     or
10049  *   0 - if all the min_rates are 0.
10050  * In the later case fainess algorithm should be deactivated.
10051  * If all min rates are not zero then those that are zeroes will be set to 1.
10052  */
10053 static void
10054 bxe_calc_vn_min(struct bxe_softc       *sc,
10055                 struct cmng_init_input *input)
10056 {
10057     uint32_t vn_cfg;
10058     uint32_t vn_min_rate;
10059     int all_zero = 1;
10060     int vn;
10061 
10062     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10063         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10064         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10065                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10066 
10067         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10068             /* skip hidden VNs */
10069             vn_min_rate = 0;
10070         } else if (!vn_min_rate) {
10071             /* If min rate is zero - set it to 100 */
10072             vn_min_rate = DEF_MIN_RATE;
10073         } else {
10074             all_zero = 0;
10075         }
10076 
10077         input->vnic_min_rate[vn] = vn_min_rate;
10078     }
10079 
10080     /* if ETS or all min rates are zeros - disable fairness */
10081     if (BXE_IS_ETS_ENABLED(sc)) {
10082         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10083         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10084     } else if (all_zero) {
10085         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10086         BLOGD(sc, DBG_LOAD,
10087               "Fariness disabled (all MIN values are zeroes)\n");
10088     } else {
10089         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10090     }
10091 }
10092 
10093 static inline uint16_t
10094 bxe_extract_max_cfg(struct bxe_softc *sc,
10095                     uint32_t         mf_cfg)
10096 {
10097     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10098                         FUNC_MF_CFG_MAX_BW_SHIFT);
10099 
10100     if (!max_cfg) {
10101         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10102         max_cfg = 100;
10103     }
10104 
10105     return (max_cfg);
10106 }
10107 
10108 static void
10109 bxe_calc_vn_max(struct bxe_softc       *sc,
10110                 int                    vn,
10111                 struct cmng_init_input *input)
10112 {
10113     uint16_t vn_max_rate;
10114     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10115     uint32_t max_cfg;
10116 
10117     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10118         vn_max_rate = 0;
10119     } else {
10120         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10121 
10122         if (IS_MF_SI(sc)) {
10123             /* max_cfg in percents of linkspeed */
10124             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10125         } else { /* SD modes */
10126             /* max_cfg is absolute in 100Mb units */
10127             vn_max_rate = (max_cfg * 100);
10128         }
10129     }
10130 
10131     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10132 
10133     input->vnic_max_rate[vn] = vn_max_rate;
10134 }
10135 
10136 static void
10137 bxe_cmng_fns_init(struct bxe_softc *sc,
10138                   uint8_t          read_cfg,
10139                   uint8_t          cmng_type)
10140 {
10141     struct cmng_init_input input;
10142     int vn;
10143 
10144     memset(&input, 0, sizeof(struct cmng_init_input));
10145 
10146     input.port_rate = sc->link_vars.line_speed;
10147 
10148     if (cmng_type == CMNG_FNS_MINMAX) {
10149         /* read mf conf from shmem */
10150         if (read_cfg) {
10151             bxe_read_mf_cfg(sc);
10152         }
10153 
10154         /* get VN min rate and enable fairness if not 0 */
10155         bxe_calc_vn_min(sc, &input);
10156 
10157         /* get VN max rate */
10158         if (sc->port.pmf) {
10159             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10160                 bxe_calc_vn_max(sc, vn, &input);
10161             }
10162         }
10163 
10164         /* always enable rate shaping and fairness */
10165         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10166 
10167         ecore_init_cmng(&input, &sc->cmng);
10168         return;
10169     }
10170 
10171     /* rate shaping and fairness are disabled */
10172     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10173 }
10174 
10175 static int
10176 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10177 {
10178     if (CHIP_REV_IS_SLOW(sc)) {
10179         return (CMNG_FNS_NONE);
10180     }
10181 
10182     if (IS_MF(sc)) {
10183         return (CMNG_FNS_MINMAX);
10184     }
10185 
10186     return (CMNG_FNS_NONE);
10187 }
10188 
10189 static void
10190 storm_memset_cmng(struct bxe_softc *sc,
10191                   struct cmng_init *cmng,
10192                   uint8_t          port)
10193 {
10194     int vn;
10195     int func;
10196     uint32_t addr;
10197     size_t size;
10198 
10199     addr = (BAR_XSTRORM_INTMEM +
10200             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10201     size = sizeof(struct cmng_struct_per_port);
10202     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10203 
10204     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10205         func = func_by_vn(sc, vn);
10206 
10207         addr = (BAR_XSTRORM_INTMEM +
10208                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10209         size = sizeof(struct rate_shaping_vars_per_vn);
10210         ecore_storm_memset_struct(sc, addr, size,
10211                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10212 
10213         addr = (BAR_XSTRORM_INTMEM +
10214                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10215         size = sizeof(struct fairness_vars_per_vn);
10216         ecore_storm_memset_struct(sc, addr, size,
10217                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10218     }
10219 }
10220 
10221 static void
10222 bxe_pf_init(struct bxe_softc *sc)
10223 {
10224     struct bxe_func_init_params func_init = { 0 };
10225     struct event_ring_data eq_data = { { 0 } };
10226     uint16_t flags;
10227 
10228     if (!CHIP_IS_E1x(sc)) {
10229         /* reset IGU PF statistics: MSIX + ATTN */
10230         /* PF */
10231         REG_WR(sc,
10232                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10233                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10234                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10235                0);
10236         /* ATTN */
10237         REG_WR(sc,
10238                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10239                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10240                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10241                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10242                0);
10243     }
10244 
10245     /* function setup flags */
10246     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10247 
10248     /*
10249      * This flag is relevant for E1x only.
10250      * E2 doesn't have a TPA configuration in a function level.
10251      */
10252     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10253 
10254     func_init.func_flgs = flags;
10255     func_init.pf_id     = SC_FUNC(sc);
10256     func_init.func_id   = SC_FUNC(sc);
10257     func_init.spq_map   = sc->spq_dma.paddr;
10258     func_init.spq_prod  = sc->spq_prod_idx;
10259 
10260     bxe_func_init(sc, &func_init);
10261 
10262     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10263 
10264     /*
10265      * Congestion management values depend on the link rate.
10266      * There is no active link so initial link rate is set to 10Gbps.
10267      * When the link comes up the congestion management values are
10268      * re-calculated according to the actual link rate.
10269      */
10270     sc->link_vars.line_speed = SPEED_10000;
10271     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10272 
10273     /* Only the PMF sets the HW */
10274     if (sc->port.pmf) {
10275         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10276     }
10277 
10278     /* init Event Queue - PCI bus guarantees correct endainity */
10279     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10280     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10281     eq_data.producer     = sc->eq_prod;
10282     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10283     eq_data.sb_id        = DEF_SB_ID;
10284     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10285 }
10286 
10287 static void
10288 bxe_hc_int_enable(struct bxe_softc *sc)
10289 {
10290     int port = SC_PORT(sc);
10291     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10292     uint32_t val = REG_RD(sc, addr);
10293     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10294     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10295                            (sc->intr_count == 1)) ? TRUE : FALSE;
10296     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10297 
10298     if (msix) {
10299         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10300                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10301         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10302                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10303         if (single_msix) {
10304             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10305         }
10306     } else if (msi) {
10307         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10308         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10309                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10310                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10311     } else {
10312         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10313                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10314                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10315                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10316 
10317         if (!CHIP_IS_E1(sc)) {
10318             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10319                   val, port, addr);
10320 
10321             REG_WR(sc, addr, val);
10322 
10323             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10324         }
10325     }
10326 
10327     if (CHIP_IS_E1(sc)) {
10328         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10329     }
10330 
10331     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10332           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10333 
10334     REG_WR(sc, addr, val);
10335 
10336     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10337     mb();
10338 
10339     if (!CHIP_IS_E1(sc)) {
10340         /* init leading/trailing edge */
10341         if (IS_MF(sc)) {
10342             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10343             if (sc->port.pmf) {
10344                 /* enable nig and gpio3 attention */
10345                 val |= 0x1100;
10346             }
10347         } else {
10348             val = 0xffff;
10349         }
10350 
10351         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10352         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10353     }
10354 
10355     /* make sure that interrupts are indeed enabled from here on */
10356     mb();
10357 }
10358 
10359 static void
10360 bxe_igu_int_enable(struct bxe_softc *sc)
10361 {
10362     uint32_t val;
10363     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10364     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10365                            (sc->intr_count == 1)) ? TRUE : FALSE;
10366     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10367 
10368     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10369 
10370     if (msix) {
10371         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10372                  IGU_PF_CONF_SINGLE_ISR_EN);
10373         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10374                 IGU_PF_CONF_ATTN_BIT_EN);
10375         if (single_msix) {
10376             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10377         }
10378     } else if (msi) {
10379         val &= ~IGU_PF_CONF_INT_LINE_EN;
10380         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10381                 IGU_PF_CONF_ATTN_BIT_EN |
10382                 IGU_PF_CONF_SINGLE_ISR_EN);
10383     } else {
10384         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10385         val |= (IGU_PF_CONF_INT_LINE_EN |
10386                 IGU_PF_CONF_ATTN_BIT_EN |
10387                 IGU_PF_CONF_SINGLE_ISR_EN);
10388     }
10389 
10390     /* clean previous status - need to configure igu prior to ack*/
10391     if ((!msix) || single_msix) {
10392         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10393         bxe_ack_int(sc);
10394     }
10395 
10396     val |= IGU_PF_CONF_FUNC_EN;
10397 
10398     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10399           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10400 
10401     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10402 
10403     mb();
10404 
10405     /* init leading/trailing edge */
10406     if (IS_MF(sc)) {
10407         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10408         if (sc->port.pmf) {
10409             /* enable nig and gpio3 attention */
10410             val |= 0x1100;
10411         }
10412     } else {
10413         val = 0xffff;
10414     }
10415 
10416     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10417     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10418 
10419     /* make sure that interrupts are indeed enabled from here on */
10420     mb();
10421 }
10422 
10423 static void
10424 bxe_int_enable(struct bxe_softc *sc)
10425 {
10426     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10427         bxe_hc_int_enable(sc);
10428     } else {
10429         bxe_igu_int_enable(sc);
10430     }
10431 }
10432 
10433 static void
10434 bxe_hc_int_disable(struct bxe_softc *sc)
10435 {
10436     int port = SC_PORT(sc);
10437     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10438     uint32_t val = REG_RD(sc, addr);
10439 
10440     /*
10441      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10442      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10443      * block
10444      */
10445     if (CHIP_IS_E1(sc)) {
10446         /*
10447          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10448          * to prevent from HC sending interrupts after we exit the function
10449          */
10450         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10451 
10452         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10453                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10454                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10455     } else {
10456         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10457                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10458                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10459                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10460     }
10461 
10462     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10463 
10464     /* flush all outstanding writes */
10465     mb();
10466 
10467     REG_WR(sc, addr, val);
10468     if (REG_RD(sc, addr) != val) {
10469         BLOGE(sc, "proper val not read from HC IGU!\n");
10470     }
10471 }
10472 
10473 static void
10474 bxe_igu_int_disable(struct bxe_softc *sc)
10475 {
10476     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10477 
10478     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10479              IGU_PF_CONF_INT_LINE_EN |
10480              IGU_PF_CONF_ATTN_BIT_EN);
10481 
10482     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10483 
10484     /* flush all outstanding writes */
10485     mb();
10486 
10487     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10488     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10489         BLOGE(sc, "proper val not read from IGU!\n");
10490     }
10491 }
10492 
10493 static void
10494 bxe_int_disable(struct bxe_softc *sc)
10495 {
10496     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10497         bxe_hc_int_disable(sc);
10498     } else {
10499         bxe_igu_int_disable(sc);
10500     }
10501 }
10502 
10503 static void
10504 bxe_nic_init(struct bxe_softc *sc,
10505              int              load_code)
10506 {
10507     int i;
10508 
10509     for (i = 0; i < sc->num_queues; i++) {
10510         bxe_init_eth_fp(sc, i);
10511     }
10512 
10513     rmb(); /* ensure status block indices were read */
10514 
10515     bxe_init_rx_rings(sc);
10516     bxe_init_tx_rings(sc);
10517 
10518     if (IS_VF(sc)) {
10519         return;
10520     }
10521 
10522     /* initialize MOD_ABS interrupts */
10523     elink_init_mod_abs_int(sc, &sc->link_vars,
10524                            sc->devinfo.chip_id,
10525                            sc->devinfo.shmem_base,
10526                            sc->devinfo.shmem2_base,
10527                            SC_PORT(sc));
10528 
10529     bxe_init_def_sb(sc);
10530     bxe_update_dsb_idx(sc);
10531     bxe_init_sp_ring(sc);
10532     bxe_init_eq_ring(sc);
10533     bxe_init_internal(sc, load_code);
10534     bxe_pf_init(sc);
10535     bxe_stats_init(sc);
10536 
10537     /* flush all before enabling interrupts */
10538     mb();
10539 
10540     bxe_int_enable(sc);
10541 
10542     /* check for SPIO5 */
10543     bxe_attn_int_deasserted0(sc,
10544                              REG_RD(sc,
10545                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10546                                      SC_PORT(sc)*4)) &
10547                              AEU_INPUTS_ATTN_BITS_SPIO5);
10548 }
10549 
10550 static inline void
10551 bxe_init_objs(struct bxe_softc *sc)
10552 {
10553     /* mcast rules must be added to tx if tx switching is enabled */
10554     ecore_obj_type o_type =
10555         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10556                                          ECORE_OBJ_TYPE_RX;
10557 
10558     /* RX_MODE controlling object */
10559     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10560 
10561     /* multicast configuration controlling object */
10562     ecore_init_mcast_obj(sc,
10563                          &sc->mcast_obj,
10564                          sc->fp[0].cl_id,
10565                          sc->fp[0].index,
10566                          SC_FUNC(sc),
10567                          SC_FUNC(sc),
10568                          BXE_SP(sc, mcast_rdata),
10569                          BXE_SP_MAPPING(sc, mcast_rdata),
10570                          ECORE_FILTER_MCAST_PENDING,
10571                          &sc->sp_state,
10572                          o_type);
10573 
10574     /* Setup CAM credit pools */
10575     ecore_init_mac_credit_pool(sc,
10576                                &sc->macs_pool,
10577                                SC_FUNC(sc),
10578                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10579                                                  VNICS_PER_PATH(sc));
10580 
10581     ecore_init_vlan_credit_pool(sc,
10582                                 &sc->vlans_pool,
10583                                 SC_ABS_FUNC(sc) >> 1,
10584                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10585                                                   VNICS_PER_PATH(sc));
10586 
10587     /* RSS configuration object */
10588     ecore_init_rss_config_obj(sc,
10589                               &sc->rss_conf_obj,
10590                               sc->fp[0].cl_id,
10591                               sc->fp[0].index,
10592                               SC_FUNC(sc),
10593                               SC_FUNC(sc),
10594                               BXE_SP(sc, rss_rdata),
10595                               BXE_SP_MAPPING(sc, rss_rdata),
10596                               ECORE_FILTER_RSS_CONF_PENDING,
10597                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10598 }
10599 
10600 /*
10601  * Initialize the function. This must be called before sending CLIENT_SETUP
10602  * for the first client.
10603  */
10604 static inline int
10605 bxe_func_start(struct bxe_softc *sc)
10606 {
10607     struct ecore_func_state_params func_params = { NULL };
10608     struct ecore_func_start_params *start_params = &func_params.params.start;
10609 
10610     /* Prepare parameters for function state transitions */
10611     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10612 
10613     func_params.f_obj = &sc->func_obj;
10614     func_params.cmd = ECORE_F_CMD_START;
10615 
10616     /* Function parameters */
10617     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10618     start_params->sd_vlan_tag = OVLAN(sc);
10619 
10620     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10621         start_params->network_cos_mode = STATIC_COS;
10622     } else { /* CHIP_IS_E1X */
10623         start_params->network_cos_mode = FW_WRR;
10624     }
10625 
10626     //start_params->gre_tunnel_mode = 0;
10627     //start_params->gre_tunnel_rss  = 0;
10628 
10629     return (ecore_func_state_change(sc, &func_params));
10630 }
10631 
10632 static int
10633 bxe_set_power_state(struct bxe_softc *sc,
10634                     uint8_t          state)
10635 {
10636     uint16_t pmcsr;
10637 
10638     /* If there is no power capability, silently succeed */
10639     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10640         BLOGW(sc, "No power capability\n");
10641         return (0);
10642     }
10643 
10644     pmcsr = pci_read_config(sc->dev,
10645                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10646                             2);
10647 
10648     switch (state) {
10649     case PCI_PM_D0:
10650         pci_write_config(sc->dev,
10651                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10652                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10653 
10654         if (pmcsr & PCIM_PSTAT_DMASK) {
10655             /* delay required during transition out of D3hot */
10656             DELAY(20000);
10657         }
10658 
10659         break;
10660 
10661     case PCI_PM_D3hot:
10662         /* XXX if there are other clients above don't shut down the power */
10663 
10664         /* don't shut down the power for emulation and FPGA */
10665         if (CHIP_REV_IS_SLOW(sc)) {
10666             return (0);
10667         }
10668 
10669         pmcsr &= ~PCIM_PSTAT_DMASK;
10670         pmcsr |= PCIM_PSTAT_D3;
10671 
10672         if (sc->wol) {
10673             pmcsr |= PCIM_PSTAT_PMEENABLE;
10674         }
10675 
10676         pci_write_config(sc->dev,
10677                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10678                          pmcsr, 4);
10679 
10680         /*
10681          * No more memory access after this point until device is brought back
10682          * to D0 state.
10683          */
10684         break;
10685 
10686     default:
10687         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10688             state, pmcsr);
10689         return (-1);
10690     }
10691 
10692     return (0);
10693 }
10694 
10695 
10696 /* return true if succeeded to acquire the lock */
10697 static uint8_t
10698 bxe_trylock_hw_lock(struct bxe_softc *sc,
10699                     uint32_t         resource)
10700 {
10701     uint32_t lock_status;
10702     uint32_t resource_bit = (1 << resource);
10703     int func = SC_FUNC(sc);
10704     uint32_t hw_lock_control_reg;
10705 
10706     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10707 
10708     /* Validating that the resource is within range */
10709     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10710         BLOGD(sc, DBG_LOAD,
10711               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10712               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10713         return (FALSE);
10714     }
10715 
10716     if (func <= 5) {
10717         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10718     } else {
10719         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10720     }
10721 
10722     /* try to acquire the lock */
10723     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10724     lock_status = REG_RD(sc, hw_lock_control_reg);
10725     if (lock_status & resource_bit) {
10726         return (TRUE);
10727     }
10728 
10729     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10730         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10731         lock_status, resource_bit);
10732 
10733     return (FALSE);
10734 }
10735 
10736 /*
10737  * Get the recovery leader resource id according to the engine this function
10738  * belongs to. Currently only only 2 engines is supported.
10739  */
10740 static int
10741 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10742 {
10743     if (SC_PATH(sc)) {
10744         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10745     } else {
10746         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10747     }
10748 }
10749 
10750 /* try to acquire a leader lock for current engine */
10751 static uint8_t
10752 bxe_trylock_leader_lock(struct bxe_softc *sc)
10753 {
10754     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10755 }
10756 
10757 static int
10758 bxe_release_leader_lock(struct bxe_softc *sc)
10759 {
10760     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10761 }
10762 
10763 /* close gates #2, #3 and #4 */
10764 static void
10765 bxe_set_234_gates(struct bxe_softc *sc,
10766                   uint8_t          close)
10767 {
10768     uint32_t val;
10769 
10770     /* gates #2 and #4a are closed/opened for "not E1" only */
10771     if (!CHIP_IS_E1(sc)) {
10772         /* #4 */
10773         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10774         /* #2 */
10775         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10776     }
10777 
10778     /* #3 */
10779     if (CHIP_IS_E1x(sc)) {
10780         /* prevent interrupts from HC on both ports */
10781         val = REG_RD(sc, HC_REG_CONFIG_1);
10782         REG_WR(sc, HC_REG_CONFIG_1,
10783                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10784                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10785 
10786         val = REG_RD(sc, HC_REG_CONFIG_0);
10787         REG_WR(sc, HC_REG_CONFIG_0,
10788                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10789                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10790     } else {
10791         /* Prevent incoming interrupts in IGU */
10792         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10793 
10794         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10795                (!close) ?
10796                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10797                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10798     }
10799 
10800     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10801           close ? "closing" : "opening");
10802 
10803     wmb();
10804 }
10805 
10806 /* poll for pending writes bit, it should get cleared in no more than 1s */
10807 static int
10808 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10809 {
10810     uint32_t cnt = 1000;
10811     uint32_t pend_bits = 0;
10812 
10813     do {
10814         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10815 
10816         if (pend_bits == 0) {
10817             break;
10818         }
10819 
10820         DELAY(1000);
10821     } while (--cnt > 0);
10822 
10823     if (cnt == 0) {
10824         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10825         return (-1);
10826     }
10827 
10828     return (0);
10829 }
10830 
10831 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10832 
10833 static void
10834 bxe_clp_reset_prep(struct bxe_softc *sc,
10835                    uint32_t         *magic_val)
10836 {
10837     /* Do some magic... */
10838     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10839     *magic_val = val & SHARED_MF_CLP_MAGIC;
10840     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10841 }
10842 
10843 /* restore the value of the 'magic' bit */
10844 static void
10845 bxe_clp_reset_done(struct bxe_softc *sc,
10846                    uint32_t         magic_val)
10847 {
10848     /* Restore the 'magic' bit value... */
10849     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10850     MFCFG_WR(sc, shared_mf_config.clp_mb,
10851               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10852 }
10853 
10854 /* prepare for MCP reset, takes care of CLP configurations */
10855 static void
10856 bxe_reset_mcp_prep(struct bxe_softc *sc,
10857                    uint32_t         *magic_val)
10858 {
10859     uint32_t shmem;
10860     uint32_t validity_offset;
10861 
10862     /* set `magic' bit in order to save MF config */
10863     if (!CHIP_IS_E1(sc)) {
10864         bxe_clp_reset_prep(sc, magic_val);
10865     }
10866 
10867     /* get shmem offset */
10868     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10869     validity_offset =
10870         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10871 
10872     /* Clear validity map flags */
10873     if (shmem > 0) {
10874         REG_WR(sc, shmem + validity_offset, 0);
10875     }
10876 }
10877 
10878 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10879 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10880 
10881 static void
10882 bxe_mcp_wait_one(struct bxe_softc *sc)
10883 {
10884     /* special handling for emulation and FPGA (10 times longer) */
10885     if (CHIP_REV_IS_SLOW(sc)) {
10886         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10887     } else {
10888         DELAY((MCP_ONE_TIMEOUT) * 1000);
10889     }
10890 }
10891 
10892 /* initialize shmem_base and waits for validity signature to appear */
10893 static int
10894 bxe_init_shmem(struct bxe_softc *sc)
10895 {
10896     int cnt = 0;
10897     uint32_t val = 0;
10898 
10899     do {
10900         sc->devinfo.shmem_base     =
10901         sc->link_params.shmem_base =
10902             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10903 
10904         if (sc->devinfo.shmem_base) {
10905             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10906             if (val & SHR_MEM_VALIDITY_MB)
10907                 return (0);
10908         }
10909 
10910         bxe_mcp_wait_one(sc);
10911 
10912     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10913 
10914     BLOGE(sc, "BAD MCP validity signature\n");
10915 
10916     return (-1);
10917 }
10918 
10919 static int
10920 bxe_reset_mcp_comp(struct bxe_softc *sc,
10921                    uint32_t         magic_val)
10922 {
10923     int rc = bxe_init_shmem(sc);
10924 
10925     /* Restore the `magic' bit value */
10926     if (!CHIP_IS_E1(sc)) {
10927         bxe_clp_reset_done(sc, magic_val);
10928     }
10929 
10930     return (rc);
10931 }
10932 
10933 static void
10934 bxe_pxp_prep(struct bxe_softc *sc)
10935 {
10936     if (!CHIP_IS_E1(sc)) {
10937         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10938         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10939         wmb();
10940     }
10941 }
10942 
10943 /*
10944  * Reset the whole chip except for:
10945  *      - PCIE core
10946  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10947  *      - IGU
10948  *      - MISC (including AEU)
10949  *      - GRC
10950  *      - RBCN, RBCP
10951  */
10952 static void
10953 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10954                             uint8_t          global)
10955 {
10956     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10957     uint32_t global_bits2, stay_reset2;
10958 
10959     /*
10960      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10961      * (per chip) blocks.
10962      */
10963     global_bits2 =
10964         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10965         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10966 
10967     /*
10968      * Don't reset the following blocks.
10969      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10970      *            reset, as in 4 port device they might still be owned
10971      *            by the MCP (there is only one leader per path).
10972      */
10973     not_reset_mask1 =
10974         MISC_REGISTERS_RESET_REG_1_RST_HC |
10975         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10976         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10977 
10978     not_reset_mask2 =
10979         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10980         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10981         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10982         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10983         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10984         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10985         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10986         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10987         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10988         MISC_REGISTERS_RESET_REG_2_PGLC |
10989         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10990         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10991         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10992         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10993         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10994         MISC_REGISTERS_RESET_REG_2_UMAC1;
10995 
10996     /*
10997      * Keep the following blocks in reset:
10998      *  - all xxMACs are handled by the elink code.
10999      */
11000     stay_reset2 =
11001         MISC_REGISTERS_RESET_REG_2_XMAC |
11002         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
11003 
11004     /* Full reset masks according to the chip */
11005     reset_mask1 = 0xffffffff;
11006 
11007     if (CHIP_IS_E1(sc))
11008         reset_mask2 = 0xffff;
11009     else if (CHIP_IS_E1H(sc))
11010         reset_mask2 = 0x1ffff;
11011     else if (CHIP_IS_E2(sc))
11012         reset_mask2 = 0xfffff;
11013     else /* CHIP_IS_E3 */
11014         reset_mask2 = 0x3ffffff;
11015 
11016     /* Don't reset global blocks unless we need to */
11017     if (!global)
11018         reset_mask2 &= ~global_bits2;
11019 
11020     /*
11021      * In case of attention in the QM, we need to reset PXP
11022      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11023      * because otherwise QM reset would release 'close the gates' shortly
11024      * before resetting the PXP, then the PSWRQ would send a write
11025      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11026      * read the payload data from PSWWR, but PSWWR would not
11027      * respond. The write queue in PGLUE would stuck, dmae commands
11028      * would not return. Therefore it's important to reset the second
11029      * reset register (containing the
11030      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11031      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11032      * bit).
11033      */
11034     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11035            reset_mask2 & (~not_reset_mask2));
11036 
11037     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11038            reset_mask1 & (~not_reset_mask1));
11039 
11040     mb();
11041     wmb();
11042 
11043     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11044            reset_mask2 & (~stay_reset2));
11045 
11046     mb();
11047     wmb();
11048 
11049     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11050     wmb();
11051 }
11052 
11053 static int
11054 bxe_process_kill(struct bxe_softc *sc,
11055                  uint8_t          global)
11056 {
11057     int cnt = 1000;
11058     uint32_t val = 0;
11059     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11060     uint32_t tags_63_32 = 0;
11061 
11062     /* Empty the Tetris buffer, wait for 1s */
11063     do {
11064         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11065         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11066         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11067         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11068         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11069         if (CHIP_IS_E3(sc)) {
11070             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11071         }
11072 
11073         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11074             ((port_is_idle_0 & 0x1) == 0x1) &&
11075             ((port_is_idle_1 & 0x1) == 0x1) &&
11076             (pgl_exp_rom2 == 0xffffffff) &&
11077             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11078             break;
11079         DELAY(1000);
11080     } while (cnt-- > 0);
11081 
11082     if (cnt <= 0) {
11083         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11084                   "are still outstanding read requests after 1s! "
11085                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11086                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11087               sr_cnt, blk_cnt, port_is_idle_0,
11088               port_is_idle_1, pgl_exp_rom2);
11089         return (-1);
11090     }
11091 
11092     mb();
11093 
11094     /* Close gates #2, #3 and #4 */
11095     bxe_set_234_gates(sc, TRUE);
11096 
11097     /* Poll for IGU VQs for 57712 and newer chips */
11098     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11099         return (-1);
11100     }
11101 
11102     /* XXX indicate that "process kill" is in progress to MCP */
11103 
11104     /* clear "unprepared" bit */
11105     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11106     mb();
11107 
11108     /* Make sure all is written to the chip before the reset */
11109     wmb();
11110 
11111     /*
11112      * Wait for 1ms to empty GLUE and PCI-E core queues,
11113      * PSWHST, GRC and PSWRD Tetris buffer.
11114      */
11115     DELAY(1000);
11116 
11117     /* Prepare to chip reset: */
11118     /* MCP */
11119     if (global) {
11120         bxe_reset_mcp_prep(sc, &val);
11121     }
11122 
11123     /* PXP */
11124     bxe_pxp_prep(sc);
11125     mb();
11126 
11127     /* reset the chip */
11128     bxe_process_kill_chip_reset(sc, global);
11129     mb();
11130 
11131     /* clear errors in PGB */
11132     if (!CHIP_IS_E1(sc))
11133         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11134 
11135     /* Recover after reset: */
11136     /* MCP */
11137     if (global && bxe_reset_mcp_comp(sc, val)) {
11138         return (-1);
11139     }
11140 
11141     /* XXX add resetting the NO_MCP mode DB here */
11142 
11143     /* Open the gates #2, #3 and #4 */
11144     bxe_set_234_gates(sc, FALSE);
11145 
11146     /* XXX
11147      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11148      * re-enable attentions
11149      */
11150 
11151     return (0);
11152 }
11153 
11154 static int
11155 bxe_leader_reset(struct bxe_softc *sc)
11156 {
11157     int rc = 0;
11158     uint8_t global = bxe_reset_is_global(sc);
11159     uint32_t load_code;
11160 
11161     /*
11162      * If not going to reset MCP, load "fake" driver to reset HW while
11163      * driver is owner of the HW.
11164      */
11165     if (!global && !BXE_NOMCP(sc)) {
11166         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11167                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11168         if (!load_code) {
11169             BLOGE(sc, "MCP response failure, aborting\n");
11170             rc = -1;
11171             goto exit_leader_reset;
11172         }
11173 
11174         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11175             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11176             BLOGE(sc, "MCP unexpected response, aborting\n");
11177             rc = -1;
11178             goto exit_leader_reset2;
11179         }
11180 
11181         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11182         if (!load_code) {
11183             BLOGE(sc, "MCP response failure, aborting\n");
11184             rc = -1;
11185             goto exit_leader_reset2;
11186         }
11187     }
11188 
11189     /* try to recover after the failure */
11190     if (bxe_process_kill(sc, global)) {
11191         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11192         rc = -1;
11193         goto exit_leader_reset2;
11194     }
11195 
11196     /*
11197      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11198      * state.
11199      */
11200     bxe_set_reset_done(sc);
11201     if (global) {
11202         bxe_clear_reset_global(sc);
11203     }
11204 
11205 exit_leader_reset2:
11206 
11207     /* unload "fake driver" if it was loaded */
11208     if (!global && !BXE_NOMCP(sc)) {
11209         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11210         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11211     }
11212 
11213 exit_leader_reset:
11214 
11215     sc->is_leader = 0;
11216     bxe_release_leader_lock(sc);
11217 
11218     mb();
11219     return (rc);
11220 }
11221 
11222 /*
11223  * prepare INIT transition, parameters configured:
11224  *   - HC configuration
11225  *   - Queue's CDU context
11226  */
11227 static void
11228 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11229                    struct bxe_fastpath            *fp,
11230                    struct ecore_queue_init_params *init_params)
11231 {
11232     uint8_t cos;
11233     int cxt_index, cxt_offset;
11234 
11235     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11236     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11237 
11238     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11239     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11240 
11241     /* HC rate */
11242     init_params->rx.hc_rate =
11243         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11244     init_params->tx.hc_rate =
11245         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11246 
11247     /* FW SB ID */
11248     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11249 
11250     /* CQ index among the SB indices */
11251     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11252     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11253 
11254     /* set maximum number of COSs supported by this queue */
11255     init_params->max_cos = sc->max_cos;
11256 
11257     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11258           fp->index, init_params->max_cos);
11259 
11260     /* set the context pointers queue object */
11261     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11262         /* XXX change index/cid here if ever support multiple tx CoS */
11263         /* fp->txdata[cos]->cid */
11264         cxt_index = fp->index / ILT_PAGE_CIDS;
11265         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11266         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11267     }
11268 }
11269 
11270 /* set flags that are common for the Tx-only and not normal connections */
11271 static unsigned long
11272 bxe_get_common_flags(struct bxe_softc    *sc,
11273                      struct bxe_fastpath *fp,
11274                      uint8_t             zero_stats)
11275 {
11276     unsigned long flags = 0;
11277 
11278     /* PF driver will always initialize the Queue to an ACTIVE state */
11279     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11280 
11281     /*
11282      * tx only connections collect statistics (on the same index as the
11283      * parent connection). The statistics are zeroed when the parent
11284      * connection is initialized.
11285      */
11286 
11287     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11288     if (zero_stats) {
11289         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11290     }
11291 
11292     /*
11293      * tx only connections can support tx-switching, though their
11294      * CoS-ness doesn't survive the loopback
11295      */
11296     if (sc->flags & BXE_TX_SWITCHING) {
11297         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11298     }
11299 
11300     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11301 
11302     return (flags);
11303 }
11304 
11305 static unsigned long
11306 bxe_get_q_flags(struct bxe_softc    *sc,
11307                 struct bxe_fastpath *fp,
11308                 uint8_t             leading)
11309 {
11310     unsigned long flags = 0;
11311 
11312     if (IS_MF_SD(sc)) {
11313         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11314     }
11315 
11316     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11317         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11318 #if __FreeBSD_version >= 800000
11319         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11320 #endif
11321     }
11322 
11323     if (leading) {
11324         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11325         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11326     }
11327 
11328     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11329 
11330     /* merge with common flags */
11331     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11332 }
11333 
11334 static void
11335 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11336                       struct bxe_fastpath               *fp,
11337                       struct ecore_general_setup_params *gen_init,
11338                       uint8_t                           cos)
11339 {
11340     gen_init->stat_id = bxe_stats_id(fp);
11341     gen_init->spcl_id = fp->cl_id;
11342     gen_init->mtu = sc->mtu;
11343     gen_init->cos = cos;
11344 }
11345 
11346 static void
11347 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11348                  struct bxe_fastpath           *fp,
11349                  struct rxq_pause_params       *pause,
11350                  struct ecore_rxq_setup_params *rxq_init)
11351 {
11352     uint8_t max_sge = 0;
11353     uint16_t sge_sz = 0;
11354     uint16_t tpa_agg_size = 0;
11355 
11356     pause->sge_th_lo = SGE_TH_LO(sc);
11357     pause->sge_th_hi = SGE_TH_HI(sc);
11358 
11359     /* validate SGE ring has enough to cross high threshold */
11360     if (sc->dropless_fc &&
11361             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11362             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11363         BLOGW(sc, "sge ring threshold limit\n");
11364     }
11365 
11366     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11367     tpa_agg_size = (2 * sc->mtu);
11368     if (tpa_agg_size < sc->max_aggregation_size) {
11369         tpa_agg_size = sc->max_aggregation_size;
11370     }
11371 
11372     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11373     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11374                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11375     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11376 
11377     /* pause - not for e1 */
11378     if (!CHIP_IS_E1(sc)) {
11379         pause->bd_th_lo = BD_TH_LO(sc);
11380         pause->bd_th_hi = BD_TH_HI(sc);
11381 
11382         pause->rcq_th_lo = RCQ_TH_LO(sc);
11383         pause->rcq_th_hi = RCQ_TH_HI(sc);
11384 
11385         /* validate rings have enough entries to cross high thresholds */
11386         if (sc->dropless_fc &&
11387             pause->bd_th_hi + FW_PREFETCH_CNT >
11388             sc->rx_ring_size) {
11389             BLOGW(sc, "rx bd ring threshold limit\n");
11390         }
11391 
11392         if (sc->dropless_fc &&
11393             pause->rcq_th_hi + FW_PREFETCH_CNT >
11394             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11395             BLOGW(sc, "rcq ring threshold limit\n");
11396         }
11397 
11398         pause->pri_map = 1;
11399     }
11400 
11401     /* rxq setup */
11402     rxq_init->dscr_map   = fp->rx_dma.paddr;
11403     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11404     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11405     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11406 
11407     /*
11408      * This should be a maximum number of data bytes that may be
11409      * placed on the BD (not including paddings).
11410      */
11411     rxq_init->buf_sz = (fp->rx_buf_size -
11412                         IP_HEADER_ALIGNMENT_PADDING);
11413 
11414     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11415     rxq_init->tpa_agg_sz      = tpa_agg_size;
11416     rxq_init->sge_buf_sz      = sge_sz;
11417     rxq_init->max_sges_pkt    = max_sge;
11418     rxq_init->rss_engine_id   = SC_FUNC(sc);
11419     rxq_init->mcast_engine_id = SC_FUNC(sc);
11420 
11421     /*
11422      * Maximum number or simultaneous TPA aggregation for this Queue.
11423      * For PF Clients it should be the maximum available number.
11424      * VF driver(s) may want to define it to a smaller value.
11425      */
11426     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11427 
11428     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11429     rxq_init->fw_sb_id = fp->fw_sb_id;
11430 
11431     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11432 
11433     /*
11434      * configure silent vlan removal
11435      * if multi function mode is afex, then mask default vlan
11436      */
11437     if (IS_MF_AFEX(sc)) {
11438         rxq_init->silent_removal_value =
11439             sc->devinfo.mf_info.afex_def_vlan_tag;
11440         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11441     }
11442 }
11443 
11444 static void
11445 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11446                  struct bxe_fastpath           *fp,
11447                  struct ecore_txq_setup_params *txq_init,
11448                  uint8_t                       cos)
11449 {
11450     /*
11451      * XXX If multiple CoS is ever supported then each fastpath structure
11452      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11453      * fp->txdata[cos]->tx_dma.paddr;
11454      */
11455     txq_init->dscr_map     = fp->tx_dma.paddr;
11456     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11457     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11458     txq_init->fw_sb_id     = fp->fw_sb_id;
11459 
11460     /*
11461      * set the TSS leading client id for TX classfication to the
11462      * leading RSS client id
11463      */
11464     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11465 }
11466 
11467 /*
11468  * This function performs 2 steps in a queue state machine:
11469  *   1) RESET->INIT
11470  *   2) INIT->SETUP
11471  */
11472 static int
11473 bxe_setup_queue(struct bxe_softc    *sc,
11474                 struct bxe_fastpath *fp,
11475                 uint8_t             leading)
11476 {
11477     struct ecore_queue_state_params q_params = { NULL };
11478     struct ecore_queue_setup_params *setup_params =
11479                         &q_params.params.setup;
11480     int rc;
11481 
11482     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11483 
11484     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11485 
11486     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11487 
11488     /* we want to wait for completion in this context */
11489     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11490 
11491     /* prepare the INIT parameters */
11492     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11493 
11494     /* Set the command */
11495     q_params.cmd = ECORE_Q_CMD_INIT;
11496 
11497     /* Change the state to INIT */
11498     rc = ecore_queue_state_change(sc, &q_params);
11499     if (rc) {
11500         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11501         return (rc);
11502     }
11503 
11504     BLOGD(sc, DBG_LOAD, "init complete\n");
11505 
11506     /* now move the Queue to the SETUP state */
11507     memset(setup_params, 0, sizeof(*setup_params));
11508 
11509     /* set Queue flags */
11510     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11511 
11512     /* set general SETUP parameters */
11513     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11514                           FIRST_TX_COS_INDEX);
11515 
11516     bxe_pf_rx_q_prep(sc, fp,
11517                      &setup_params->pause_params,
11518                      &setup_params->rxq_params);
11519 
11520     bxe_pf_tx_q_prep(sc, fp,
11521                      &setup_params->txq_params,
11522                      FIRST_TX_COS_INDEX);
11523 
11524     /* Set the command */
11525     q_params.cmd = ECORE_Q_CMD_SETUP;
11526 
11527     /* change the state to SETUP */
11528     rc = ecore_queue_state_change(sc, &q_params);
11529     if (rc) {
11530         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11531         return (rc);
11532     }
11533 
11534     return (rc);
11535 }
11536 
11537 static int
11538 bxe_setup_leading(struct bxe_softc *sc)
11539 {
11540     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11541 }
11542 
11543 static int
11544 bxe_config_rss_pf(struct bxe_softc            *sc,
11545                   struct ecore_rss_config_obj *rss_obj,
11546                   uint8_t                     config_hash)
11547 {
11548     struct ecore_config_rss_params params = { NULL };
11549     int i;
11550 
11551     /*
11552      * Although RSS is meaningless when there is a single HW queue we
11553      * still need it enabled in order to have HW Rx hash generated.
11554      */
11555 
11556     params.rss_obj = rss_obj;
11557 
11558     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11559 
11560     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11561 
11562     /* RSS configuration */
11563     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11564     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11565     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11566     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11567     if (rss_obj->udp_rss_v4) {
11568         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11569     }
11570     if (rss_obj->udp_rss_v6) {
11571         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11572     }
11573 
11574     /* Hash bits */
11575     params.rss_result_mask = MULTI_MASK;
11576 
11577     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11578 
11579     if (config_hash) {
11580         /* RSS keys */
11581         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11582             params.rss_key[i] = arc4random();
11583         }
11584 
11585         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11586     }
11587 
11588     return (ecore_config_rss(sc, &params));
11589 }
11590 
11591 static int
11592 bxe_config_rss_eth(struct bxe_softc *sc,
11593                    uint8_t          config_hash)
11594 {
11595     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11596 }
11597 
11598 static int
11599 bxe_init_rss_pf(struct bxe_softc *sc)
11600 {
11601     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11602     int i;
11603 
11604     /*
11605      * Prepare the initial contents of the indirection table if
11606      * RSS is enabled
11607      */
11608     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11609         sc->rss_conf_obj.ind_table[i] =
11610             (sc->fp->cl_id + (i % num_eth_queues));
11611     }
11612 
11613     if (sc->udp_rss) {
11614         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11615     }
11616 
11617     /*
11618      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11619      * per-port, so if explicit configuration is needed, do it only
11620      * for a PMF.
11621      *
11622      * For 57712 and newer it's a per-function configuration.
11623      */
11624     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11625 }
11626 
11627 static int
11628 bxe_set_mac_one(struct bxe_softc          *sc,
11629                 uint8_t                   *mac,
11630                 struct ecore_vlan_mac_obj *obj,
11631                 uint8_t                   set,
11632                 int                       mac_type,
11633                 unsigned long             *ramrod_flags)
11634 {
11635     struct ecore_vlan_mac_ramrod_params ramrod_param;
11636     int rc;
11637 
11638     memset(&ramrod_param, 0, sizeof(ramrod_param));
11639 
11640     /* fill in general parameters */
11641     ramrod_param.vlan_mac_obj = obj;
11642     ramrod_param.ramrod_flags = *ramrod_flags;
11643 
11644     /* fill a user request section if needed */
11645     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11646         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11647 
11648         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11649 
11650         /* Set the command: ADD or DEL */
11651         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11652                                             ECORE_VLAN_MAC_DEL;
11653     }
11654 
11655     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11656 
11657     if (rc == ECORE_EXISTS) {
11658         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11659         /* do not treat adding same MAC as error */
11660         rc = 0;
11661     } else if (rc < 0) {
11662         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11663     }
11664 
11665     return (rc);
11666 }
11667 
11668 static int
11669 bxe_set_eth_mac(struct bxe_softc *sc,
11670                 uint8_t          set)
11671 {
11672     unsigned long ramrod_flags = 0;
11673 
11674     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11675 
11676     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11677 
11678     /* Eth MAC is set on RSS leading client (fp[0]) */
11679     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11680                             &sc->sp_objs->mac_obj,
11681                             set, ECORE_ETH_MAC, &ramrod_flags));
11682 }
11683 
11684 static int
11685 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11686 {
11687     uint32_t sel_phy_idx = 0;
11688 
11689     if (sc->link_params.num_phys <= 1) {
11690         return (ELINK_INT_PHY);
11691     }
11692 
11693     if (sc->link_vars.link_up) {
11694         sel_phy_idx = ELINK_EXT_PHY1;
11695         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11696         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11697             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11698              ELINK_SUPPORTED_FIBRE))
11699             sel_phy_idx = ELINK_EXT_PHY2;
11700     } else {
11701         switch (elink_phy_selection(&sc->link_params)) {
11702         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11703         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11704         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11705                sel_phy_idx = ELINK_EXT_PHY1;
11706                break;
11707         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11708         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11709                sel_phy_idx = ELINK_EXT_PHY2;
11710                break;
11711         }
11712     }
11713 
11714     return (sel_phy_idx);
11715 }
11716 
11717 static int
11718 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11719 {
11720     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11721 
11722     /*
11723      * The selected activated PHY is always after swapping (in case PHY
11724      * swapping is enabled). So when swapping is enabled, we need to reverse
11725      * the configuration
11726      */
11727 
11728     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11729         if (sel_phy_idx == ELINK_EXT_PHY1)
11730             sel_phy_idx = ELINK_EXT_PHY2;
11731         else if (sel_phy_idx == ELINK_EXT_PHY2)
11732             sel_phy_idx = ELINK_EXT_PHY1;
11733     }
11734 
11735     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11736 }
11737 
11738 static void
11739 bxe_set_requested_fc(struct bxe_softc *sc)
11740 {
11741     /*
11742      * Initialize link parameters structure variables
11743      * It is recommended to turn off RX FC for jumbo frames
11744      * for better performance
11745      */
11746     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11747         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11748     } else {
11749         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11750     }
11751 }
11752 
11753 static void
11754 bxe_calc_fc_adv(struct bxe_softc *sc)
11755 {
11756     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11757 
11758 
11759     sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11760                                            ADVERTISED_Pause);
11761 
11762     switch (sc->link_vars.ieee_fc &
11763             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11764 
11765     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11766         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11767                                           ADVERTISED_Pause);
11768         break;
11769 
11770     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11771         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11772         break;
11773 
11774     default:
11775         break;
11776 
11777     }
11778 }
11779 
11780 static uint16_t
11781 bxe_get_mf_speed(struct bxe_softc *sc)
11782 {
11783     uint16_t line_speed = sc->link_vars.line_speed;
11784     if (IS_MF(sc)) {
11785         uint16_t maxCfg =
11786             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11787 
11788         /* calculate the current MAX line speed limit for the MF devices */
11789         if (IS_MF_SI(sc)) {
11790             line_speed = (line_speed * maxCfg) / 100;
11791         } else { /* SD mode */
11792             uint16_t vn_max_rate = maxCfg * 100;
11793 
11794             if (vn_max_rate < line_speed) {
11795                 line_speed = vn_max_rate;
11796             }
11797         }
11798     }
11799 
11800     return (line_speed);
11801 }
11802 
11803 static void
11804 bxe_fill_report_data(struct bxe_softc            *sc,
11805                      struct bxe_link_report_data *data)
11806 {
11807     uint16_t line_speed = bxe_get_mf_speed(sc);
11808 
11809     memset(data, 0, sizeof(*data));
11810 
11811     /* fill the report data with the effective line speed */
11812     data->line_speed = line_speed;
11813 
11814     /* Link is down */
11815     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11816         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11817     }
11818 
11819     /* Full DUPLEX */
11820     if (sc->link_vars.duplex == DUPLEX_FULL) {
11821         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11822     }
11823 
11824     /* Rx Flow Control is ON */
11825     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11826         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11827     }
11828 
11829     /* Tx Flow Control is ON */
11830     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11831         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11832     }
11833 }
11834 
11835 /* report link status to OS, should be called under phy_lock */
11836 static void
11837 bxe_link_report_locked(struct bxe_softc *sc)
11838 {
11839     struct bxe_link_report_data cur_data;
11840 
11841     /* reread mf_cfg */
11842     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11843         bxe_read_mf_cfg(sc);
11844     }
11845 
11846     /* Read the current link report info */
11847     bxe_fill_report_data(sc, &cur_data);
11848 
11849     /* Don't report link down or exactly the same link status twice */
11850     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11851         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11852                       &sc->last_reported_link.link_report_flags) &&
11853          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11854                       &cur_data.link_report_flags))) {
11855         return;
11856     }
11857 
11858 	ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11859 					cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11860     sc->link_cnt++;
11861 
11862 	ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11863     /* report new link params and remember the state for the next time */
11864     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11865 
11866     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11867                      &cur_data.link_report_flags)) {
11868         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11869     } else {
11870         const char *duplex;
11871         const char *flow;
11872 
11873         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11874                                    &cur_data.link_report_flags)) {
11875             duplex = "full";
11876 			ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11877         } else {
11878             duplex = "half";
11879 			ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11880         }
11881 
11882         /*
11883          * Handle the FC at the end so that only these flags would be
11884          * possibly set. This way we may easily check if there is no FC
11885          * enabled.
11886          */
11887         if (cur_data.link_report_flags) {
11888             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11889                              &cur_data.link_report_flags) &&
11890                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11891                              &cur_data.link_report_flags)) {
11892                 flow = "ON - receive & transmit";
11893             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11894                                     &cur_data.link_report_flags) &&
11895                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11896                                      &cur_data.link_report_flags)) {
11897                 flow = "ON - receive";
11898             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11899                                      &cur_data.link_report_flags) &&
11900                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11901                                     &cur_data.link_report_flags)) {
11902                 flow = "ON - transmit";
11903             } else {
11904                 flow = "none"; /* possible? */
11905             }
11906         } else {
11907             flow = "none";
11908         }
11909 
11910         if_link_state_change(sc->ifp, LINK_STATE_UP);
11911         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11912               cur_data.line_speed, duplex, flow);
11913     }
11914 }
11915 
11916 static void
11917 bxe_link_report(struct bxe_softc *sc)
11918 {
11919     bxe_acquire_phy_lock(sc);
11920     bxe_link_report_locked(sc);
11921     bxe_release_phy_lock(sc);
11922 }
11923 
11924 static void
11925 bxe_link_status_update(struct bxe_softc *sc)
11926 {
11927     if (sc->state != BXE_STATE_OPEN) {
11928         return;
11929     }
11930 
11931     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11932         elink_link_status_update(&sc->link_params, &sc->link_vars);
11933     } else {
11934         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11935                                   ELINK_SUPPORTED_10baseT_Full |
11936                                   ELINK_SUPPORTED_100baseT_Half |
11937                                   ELINK_SUPPORTED_100baseT_Full |
11938                                   ELINK_SUPPORTED_1000baseT_Full |
11939                                   ELINK_SUPPORTED_2500baseX_Full |
11940                                   ELINK_SUPPORTED_10000baseT_Full |
11941                                   ELINK_SUPPORTED_TP |
11942                                   ELINK_SUPPORTED_FIBRE |
11943                                   ELINK_SUPPORTED_Autoneg |
11944                                   ELINK_SUPPORTED_Pause |
11945                                   ELINK_SUPPORTED_Asym_Pause);
11946         sc->port.advertising[0] = sc->port.supported[0];
11947 
11948         sc->link_params.sc                = sc;
11949         sc->link_params.port              = SC_PORT(sc);
11950         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11951         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11952         sc->link_params.req_line_speed[0] = SPEED_10000;
11953         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11954         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11955 
11956         if (CHIP_REV_IS_FPGA(sc)) {
11957             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11958             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11959             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11960                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11961         } else {
11962             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11963             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11964             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11965                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11966         }
11967 
11968         sc->link_vars.link_up = 1;
11969 
11970         sc->link_vars.duplex    = DUPLEX_FULL;
11971         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11972 
11973         if (IS_PF(sc)) {
11974             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11975             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11976             bxe_link_report(sc);
11977         }
11978     }
11979 
11980     if (IS_PF(sc)) {
11981         if (sc->link_vars.link_up) {
11982             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11983         } else {
11984             bxe_stats_handle(sc, STATS_EVENT_STOP);
11985         }
11986         bxe_link_report(sc);
11987     } else {
11988         bxe_link_report(sc);
11989         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11990     }
11991 }
11992 
11993 static int
11994 bxe_initial_phy_init(struct bxe_softc *sc,
11995                      int              load_mode)
11996 {
11997     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11998     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11999     struct elink_params *lp = &sc->link_params;
12000 
12001     bxe_set_requested_fc(sc);
12002 
12003     if (CHIP_REV_IS_SLOW(sc)) {
12004         uint32_t bond = CHIP_BOND_ID(sc);
12005         uint32_t feat = 0;
12006 
12007         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
12008             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12009         } else if (bond & 0x4) {
12010             if (CHIP_IS_E3(sc)) {
12011                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
12012             } else {
12013                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
12014             }
12015         } else if (bond & 0x8) {
12016             if (CHIP_IS_E3(sc)) {
12017                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
12018             } else {
12019                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12020             }
12021         }
12022 
12023         /* disable EMAC for E3 and above */
12024         if (bond & 0x2) {
12025             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12026         }
12027 
12028         sc->link_params.feature_config_flags |= feat;
12029     }
12030 
12031     bxe_acquire_phy_lock(sc);
12032 
12033     if (load_mode == LOAD_DIAG) {
12034         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12035         /* Prefer doing PHY loopback at 10G speed, if possible */
12036         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12037             if (lp->speed_cap_mask[cfg_idx] &
12038                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12039                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12040             } else {
12041                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12042             }
12043         }
12044     }
12045 
12046     if (load_mode == LOAD_LOOPBACK_EXT) {
12047         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12048     }
12049 
12050     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12051 
12052     bxe_release_phy_lock(sc);
12053 
12054     bxe_calc_fc_adv(sc);
12055 
12056     if (sc->link_vars.link_up) {
12057         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12058         bxe_link_report(sc);
12059     }
12060 
12061     if (!CHIP_REV_IS_SLOW(sc)) {
12062         bxe_periodic_start(sc);
12063     }
12064 
12065     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12066     return (rc);
12067 }
12068 
12069 static u_int
12070 bxe_push_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
12071 {
12072     struct ecore_mcast_list_elem *mc_mac = arg;
12073 
12074     mc_mac += cnt;
12075     mc_mac->mac = (uint8_t *)LLADDR(sdl);
12076 
12077     return (1);
12078 }
12079 
12080 static int
12081 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12082                          struct ecore_mcast_ramrod_params *p)
12083 {
12084     if_t ifp = sc->ifp;
12085     int mc_count;
12086     struct ecore_mcast_list_elem *mc_mac;
12087 
12088     ECORE_LIST_INIT(&p->mcast_list);
12089     p->mcast_list_len = 0;
12090 
12091     /* XXXGL: multicast count may change later */
12092     mc_count = if_llmaddr_count(ifp);
12093 
12094     if (!mc_count) {
12095         return (0);
12096     }
12097 
12098     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12099                     (M_NOWAIT | M_ZERO));
12100     if (!mc_mac) {
12101         BLOGE(sc, "Failed to allocate temp mcast list\n");
12102         return (-1);
12103     }
12104     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12105     if_foreach_llmaddr(ifp, bxe_push_maddr, mc_mac);
12106 
12107     for (int i = 0; i < mc_count; i ++) {
12108         ECORE_LIST_PUSH_TAIL(&mc_mac[i].link, &p->mcast_list);
12109         BLOGD(sc, DBG_LOAD,
12110               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X and mc_count %d\n",
12111               mc_mac[i].mac[0], mc_mac[i].mac[1], mc_mac[i].mac[2],
12112               mc_mac[i].mac[3], mc_mac[i].mac[4], mc_mac[i].mac[5],
12113               mc_count);
12114     }
12115 
12116     p->mcast_list_len = mc_count;
12117 
12118     return (0);
12119 }
12120 
12121 static void
12122 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12123 {
12124     struct ecore_mcast_list_elem *mc_mac =
12125         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12126                                struct ecore_mcast_list_elem,
12127                                link);
12128 
12129     if (mc_mac) {
12130         /* only a single free as all mc_macs are in the same heap array */
12131         free(mc_mac, M_DEVBUF);
12132     }
12133 }
12134 static int
12135 bxe_set_mc_list(struct bxe_softc *sc)
12136 {
12137     struct ecore_mcast_ramrod_params rparam = { NULL };
12138     int rc = 0;
12139 
12140     rparam.mcast_obj = &sc->mcast_obj;
12141 
12142     BXE_MCAST_LOCK(sc);
12143 
12144     /* first, clear all configured multicast MACs */
12145     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12146     if (rc < 0) {
12147         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12148         /* Manual backport parts of FreeBSD upstream r284470. */
12149         BXE_MCAST_UNLOCK(sc);
12150         return (rc);
12151     }
12152 
12153     /* configure a new MACs list */
12154     rc = bxe_init_mcast_macs_list(sc, &rparam);
12155     if (rc) {
12156         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12157         BXE_MCAST_UNLOCK(sc);
12158         return (rc);
12159     }
12160 
12161     /* Now add the new MACs */
12162     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12163     if (rc < 0) {
12164         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12165     }
12166 
12167     bxe_free_mcast_macs_list(&rparam);
12168 
12169     BXE_MCAST_UNLOCK(sc);
12170 
12171     return (rc);
12172 }
12173 
12174 struct bxe_set_addr_ctx {
12175    struct bxe_softc *sc;
12176    unsigned long ramrod_flags;
12177    int rc;
12178 };
12179 
12180 static u_int
12181 bxe_set_addr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
12182 {
12183     struct bxe_set_addr_ctx *ctx = arg;
12184     struct ecore_vlan_mac_obj *mac_obj = &ctx->sc->sp_objs->mac_obj;
12185     int rc;
12186 
12187     if (ctx->rc < 0)
12188 	return (0);
12189 
12190     rc = bxe_set_mac_one(ctx->sc, (uint8_t *)LLADDR(sdl), mac_obj, TRUE,
12191                          ECORE_UC_LIST_MAC, &ctx->ramrod_flags);
12192 
12193     /* do not treat adding same MAC as an error */
12194     if (rc == -EEXIST)
12195 	BLOGD(ctx->sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12196     else if (rc < 0) {
12197             BLOGE(ctx->sc, "Failed to schedule ADD operations (%d)\n", rc);
12198             ctx->rc = rc;
12199     }
12200 
12201     return (1);
12202 }
12203 
12204 static int
12205 bxe_set_uc_list(struct bxe_softc *sc)
12206 {
12207     if_t ifp = sc->ifp;
12208     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12209     struct bxe_set_addr_ctx ctx = { sc, 0, 0 };
12210     int rc;
12211 
12212     /* first schedule a cleanup up of old configuration */
12213     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12214     if (rc < 0) {
12215         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12216         return (rc);
12217     }
12218 
12219     if_foreach_lladdr(ifp, bxe_set_addr, &ctx);
12220     if (ctx.rc < 0)
12221 	return (ctx.rc);
12222 
12223     /* Execute the pending commands */
12224     bit_set(&ctx.ramrod_flags, RAMROD_CONT);
12225     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12226                             ECORE_UC_LIST_MAC, &ctx.ramrod_flags));
12227 }
12228 
12229 static void
12230 bxe_set_rx_mode(struct bxe_softc *sc)
12231 {
12232     if_t ifp = sc->ifp;
12233     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12234 
12235     if (sc->state != BXE_STATE_OPEN) {
12236         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12237         return;
12238     }
12239 
12240     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12241 
12242     if (if_getflags(ifp) & IFF_PROMISC) {
12243         rx_mode = BXE_RX_MODE_PROMISC;
12244     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12245                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12246                 CHIP_IS_E1(sc))) {
12247         rx_mode = BXE_RX_MODE_ALLMULTI;
12248     } else {
12249         if (IS_PF(sc)) {
12250             /* some multicasts */
12251             if (bxe_set_mc_list(sc) < 0) {
12252                 rx_mode = BXE_RX_MODE_ALLMULTI;
12253             }
12254             if (bxe_set_uc_list(sc) < 0) {
12255                 rx_mode = BXE_RX_MODE_PROMISC;
12256             }
12257         }
12258     }
12259 
12260     sc->rx_mode = rx_mode;
12261 
12262     /* schedule the rx_mode command */
12263     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12264         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12265         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12266         return;
12267     }
12268 
12269     if (IS_PF(sc)) {
12270         bxe_set_storm_rx_mode(sc);
12271     }
12272 }
12273 
12274 
12275 /* update flags in shmem */
12276 static void
12277 bxe_update_drv_flags(struct bxe_softc *sc,
12278                      uint32_t         flags,
12279                      uint32_t         set)
12280 {
12281     uint32_t drv_flags;
12282 
12283     if (SHMEM2_HAS(sc, drv_flags)) {
12284         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12285         drv_flags = SHMEM2_RD(sc, drv_flags);
12286 
12287         if (set) {
12288             SET_FLAGS(drv_flags, flags);
12289         } else {
12290             RESET_FLAGS(drv_flags, flags);
12291         }
12292 
12293         SHMEM2_WR(sc, drv_flags, drv_flags);
12294         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12295 
12296         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12297     }
12298 }
12299 
12300 /* periodic timer callout routine, only runs when the interface is up */
12301 
12302 static void
12303 bxe_periodic_callout_func(void *xsc)
12304 {
12305     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12306     int i;
12307 
12308     if (!BXE_CORE_TRYLOCK(sc)) {
12309         /* just bail and try again next time */
12310 
12311         if ((sc->state == BXE_STATE_OPEN) &&
12312             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12313             /* schedule the next periodic callout */
12314             callout_reset(&sc->periodic_callout, hz,
12315                           bxe_periodic_callout_func, sc);
12316         }
12317 
12318         return;
12319     }
12320 
12321     if ((sc->state != BXE_STATE_OPEN) ||
12322         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12323         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12324         BXE_CORE_UNLOCK(sc);
12325         return;
12326         }
12327 
12328 
12329     /* Check for TX timeouts on any fastpath. */
12330     FOR_EACH_QUEUE(sc, i) {
12331         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12332             /* Ruh-Roh, chip was reset! */
12333             break;
12334         }
12335     }
12336 
12337     if (!CHIP_REV_IS_SLOW(sc)) {
12338         /*
12339          * This barrier is needed to ensure the ordering between the writing
12340          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12341          * the reading here.
12342          */
12343         mb();
12344         if (sc->port.pmf) {
12345 	    bxe_acquire_phy_lock(sc);
12346             elink_period_func(&sc->link_params, &sc->link_vars);
12347 	    bxe_release_phy_lock(sc);
12348         }
12349     }
12350 
12351     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12352         int mb_idx = SC_FW_MB_IDX(sc);
12353         uint32_t drv_pulse;
12354         uint32_t mcp_pulse;
12355 
12356         ++sc->fw_drv_pulse_wr_seq;
12357         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12358 
12359         drv_pulse = sc->fw_drv_pulse_wr_seq;
12360         bxe_drv_pulse(sc);
12361 
12362         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12363                      MCP_PULSE_SEQ_MASK);
12364 
12365         /*
12366          * The delta between driver pulse and mcp response should
12367          * be 1 (before mcp response) or 0 (after mcp response).
12368          */
12369         if ((drv_pulse != mcp_pulse) &&
12370             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12371             /* someone lost a heartbeat... */
12372             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12373                   drv_pulse, mcp_pulse);
12374         }
12375     }
12376 
12377     /* state is BXE_STATE_OPEN */
12378     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12379 
12380     BXE_CORE_UNLOCK(sc);
12381 
12382     if ((sc->state == BXE_STATE_OPEN) &&
12383         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12384         /* schedule the next periodic callout */
12385         callout_reset(&sc->periodic_callout, hz,
12386                       bxe_periodic_callout_func, sc);
12387     }
12388 }
12389 
12390 static void
12391 bxe_periodic_start(struct bxe_softc *sc)
12392 {
12393     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12394     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12395 }
12396 
12397 static void
12398 bxe_periodic_stop(struct bxe_softc *sc)
12399 {
12400     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12401     callout_drain(&sc->periodic_callout);
12402 }
12403 
12404 void
12405 bxe_parity_recover(struct bxe_softc *sc)
12406 {
12407     uint8_t global = FALSE;
12408     uint32_t error_recovered, error_unrecovered;
12409     bool is_parity;
12410 
12411 
12412     if ((sc->recovery_state == BXE_RECOVERY_FAILED) &&
12413         (sc->state == BXE_STATE_ERROR)) {
12414         BLOGE(sc, "RECOVERY failed, "
12415             "stack notified driver is NOT running! "
12416             "Please reboot/power cycle the system.\n");
12417         return;
12418     }
12419 
12420     while (1) {
12421         BLOGD(sc, DBG_SP,
12422            "%s sc=%p state=0x%x rec_state=0x%x error_status=%x\n",
12423             __func__, sc, sc->state, sc->recovery_state, sc->error_status);
12424 
12425         switch(sc->recovery_state) {
12426 
12427         case BXE_RECOVERY_INIT:
12428             is_parity = bxe_chk_parity_attn(sc, &global, FALSE);
12429 
12430             if ((CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ||
12431                 (sc->error_status & BXE_ERR_MCP_ASSERT) ||
12432                 (sc->error_status & BXE_ERR_GLOBAL)) {
12433 
12434                 BXE_CORE_LOCK(sc);
12435                 if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12436                     bxe_periodic_stop(sc);
12437                 }
12438                 bxe_nic_unload(sc, UNLOAD_RECOVERY, false);
12439                 sc->state = BXE_STATE_ERROR;
12440                 sc->recovery_state = BXE_RECOVERY_FAILED;
12441                 BLOGE(sc, " No Recovery tried for error 0x%x"
12442                     " stack notified driver is NOT running!"
12443                     " Please reboot/power cycle the system.\n",
12444                     sc->error_status);
12445                 BXE_CORE_UNLOCK(sc);
12446                 return;
12447             }
12448 
12449 
12450            /* Try to get a LEADER_LOCK HW lock */
12451             if (bxe_trylock_leader_lock(sc)) {
12452 
12453                 bxe_set_reset_in_progress(sc);
12454                 /*
12455                  * Check if there is a global attention and if
12456                  * there was a global attention, set the global
12457                  * reset bit.
12458                  */
12459                 if (global) {
12460                     bxe_set_reset_global(sc);
12461                 }
12462                 sc->is_leader = 1;
12463             }
12464 
12465             /* If interface has been removed - break */
12466 
12467             if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12468                 bxe_periodic_stop(sc);
12469             }
12470 
12471             BXE_CORE_LOCK(sc);
12472             bxe_nic_unload(sc,UNLOAD_RECOVERY, false);
12473             sc->recovery_state = BXE_RECOVERY_WAIT;
12474             BXE_CORE_UNLOCK(sc);
12475 
12476             /*
12477              * Ensure "is_leader", MCP command sequence and
12478              * "recovery_state" update values are seen on other
12479              * CPUs.
12480              */
12481             mb();
12482             break;
12483         case BXE_RECOVERY_WAIT:
12484 
12485             if (sc->is_leader) {
12486                 int other_engine = SC_PATH(sc) ? 0 : 1;
12487                 bool other_load_status =
12488                     bxe_get_load_status(sc, other_engine);
12489                 bool load_status =
12490                     bxe_get_load_status(sc, SC_PATH(sc));
12491                 global = bxe_reset_is_global(sc);
12492 
12493                 /*
12494                  * In case of a parity in a global block, let
12495                  * the first leader that performs a
12496                  * leader_reset() reset the global blocks in
12497                  * order to clear global attentions. Otherwise
12498                  * the gates will remain closed for that
12499                  * engine.
12500                  */
12501                 if (load_status ||
12502                     (global && other_load_status)) {
12503                     /*
12504                      * Wait until all other functions get
12505                      * down.
12506                      */
12507                     taskqueue_enqueue_timeout(taskqueue_thread,
12508                         &sc->sp_err_timeout_task, hz/10);
12509                     return;
12510                 } else {
12511                     /*
12512                      * If all other functions got down
12513                      * try to bring the chip back to
12514                      * normal. In any case it's an exit
12515                      * point for a leader.
12516                      */
12517                     if (bxe_leader_reset(sc)) {
12518                         BLOGE(sc, "RECOVERY failed, "
12519                             "stack notified driver is NOT running!\n");
12520                         sc->recovery_state = BXE_RECOVERY_FAILED;
12521                         sc->state = BXE_STATE_ERROR;
12522                         mb();
12523                         return;
12524                     }
12525 
12526                     /*
12527                      * If we are here, means that the
12528                      * leader has succeeded and doesn't
12529                      * want to be a leader any more. Try
12530                      * to continue as a none-leader.
12531                      */
12532                 break;
12533                 }
12534 
12535             } else { /* non-leader */
12536                 if (!bxe_reset_is_done(sc, SC_PATH(sc))) {
12537                     /*
12538                      * Try to get a LEADER_LOCK HW lock as
12539                      * long as a former leader may have
12540                      * been unloaded by the user or
12541                      * released a leadership by another
12542                      * reason.
12543                      */
12544                     if (bxe_trylock_leader_lock(sc)) {
12545                         /*
12546                          * I'm a leader now! Restart a
12547                          * switch case.
12548                          */
12549                         sc->is_leader = 1;
12550                         break;
12551                     }
12552 
12553                     taskqueue_enqueue_timeout(taskqueue_thread,
12554                         &sc->sp_err_timeout_task, hz/10);
12555                     return;
12556 
12557                 } else {
12558                     /*
12559                      * If there was a global attention, wait
12560                      * for it to be cleared.
12561                      */
12562                     if (bxe_reset_is_global(sc)) {
12563                         taskqueue_enqueue_timeout(taskqueue_thread,
12564                             &sc->sp_err_timeout_task, hz/10);
12565                         return;
12566                      }
12567 
12568                      error_recovered =
12569                          sc->eth_stats.recoverable_error;
12570                      error_unrecovered =
12571                          sc->eth_stats.unrecoverable_error;
12572                      BXE_CORE_LOCK(sc);
12573                      sc->recovery_state =
12574                          BXE_RECOVERY_NIC_LOADING;
12575                      if (bxe_nic_load(sc, LOAD_NORMAL)) {
12576                          error_unrecovered++;
12577                          sc->recovery_state = BXE_RECOVERY_FAILED;
12578                          sc->state = BXE_STATE_ERROR;
12579                          BLOGE(sc, "Recovery is NOT successfull, "
12580                             " state=0x%x recovery_state=0x%x error=%x\n",
12581                             sc->state, sc->recovery_state, sc->error_status);
12582                          sc->error_status = 0;
12583                      } else {
12584                          sc->recovery_state =
12585                              BXE_RECOVERY_DONE;
12586                          error_recovered++;
12587                          BLOGI(sc, "Recovery is successfull from errors %x,"
12588                             " state=0x%x"
12589                             " recovery_state=0x%x \n", sc->error_status,
12590                             sc->state, sc->recovery_state);
12591                          mb();
12592                      }
12593                      sc->error_status = 0;
12594                      BXE_CORE_UNLOCK(sc);
12595                      sc->eth_stats.recoverable_error =
12596                          error_recovered;
12597                      sc->eth_stats.unrecoverable_error =
12598                          error_unrecovered;
12599 
12600                      return;
12601                  }
12602              }
12603          default:
12604              return;
12605          }
12606     }
12607 }
12608 void
12609 bxe_handle_error(struct bxe_softc * sc)
12610 {
12611 
12612     if(sc->recovery_state == BXE_RECOVERY_WAIT) {
12613         return;
12614     }
12615     if(sc->error_status) {
12616         if (sc->state == BXE_STATE_OPEN)  {
12617             bxe_int_disable(sc);
12618         }
12619         if (sc->link_vars.link_up) {
12620             if_link_state_change(sc->ifp, LINK_STATE_DOWN);
12621         }
12622         sc->recovery_state = BXE_RECOVERY_INIT;
12623         BLOGI(sc, "bxe%d: Recovery started errors 0x%x recovery state 0x%x\n",
12624             sc->unit, sc->error_status, sc->recovery_state);
12625         bxe_parity_recover(sc);
12626    }
12627 }
12628 
12629 static void
12630 bxe_sp_err_timeout_task(void *arg, int pending)
12631 {
12632 
12633     struct bxe_softc *sc = (struct bxe_softc *)arg;
12634 
12635     BLOGD(sc, DBG_SP,
12636         "%s state = 0x%x rec state=0x%x error_status=%x\n",
12637         __func__, sc->state, sc->recovery_state, sc->error_status);
12638 
12639     if((sc->recovery_state == BXE_RECOVERY_FAILED) &&
12640        (sc->state == BXE_STATE_ERROR)) {
12641         return;
12642     }
12643     /* if can be taken */
12644     if ((sc->error_status) && (sc->trigger_grcdump)) {
12645         bxe_grc_dump(sc);
12646     }
12647     if (sc->recovery_state != BXE_RECOVERY_DONE) {
12648         bxe_handle_error(sc);
12649         bxe_parity_recover(sc);
12650     } else if (sc->error_status) {
12651         bxe_handle_error(sc);
12652     }
12653 
12654     return;
12655 }
12656 
12657 /* start the controller */
12658 static __noinline int
12659 bxe_nic_load(struct bxe_softc *sc,
12660              int              load_mode)
12661 {
12662     uint32_t val;
12663     int load_code = 0;
12664     int i, rc = 0;
12665 
12666     BXE_CORE_LOCK_ASSERT(sc);
12667 
12668     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12669 
12670     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12671 
12672     if (IS_PF(sc)) {
12673         /* must be called before memory allocation and HW init */
12674         bxe_ilt_set_info(sc);
12675     }
12676 
12677     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12678 
12679     bxe_set_fp_rx_buf_size(sc);
12680 
12681     if (bxe_alloc_fp_buffers(sc) != 0) {
12682         BLOGE(sc, "Failed to allocate fastpath memory\n");
12683         sc->state = BXE_STATE_CLOSED;
12684         rc = ENOMEM;
12685         goto bxe_nic_load_error0;
12686     }
12687 
12688     if (bxe_alloc_mem(sc) != 0) {
12689         sc->state = BXE_STATE_CLOSED;
12690         rc = ENOMEM;
12691         goto bxe_nic_load_error0;
12692     }
12693 
12694     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12695         sc->state = BXE_STATE_CLOSED;
12696         rc = ENOMEM;
12697         goto bxe_nic_load_error0;
12698     }
12699 
12700     if (IS_PF(sc)) {
12701         /* set pf load just before approaching the MCP */
12702         bxe_set_pf_load(sc);
12703 
12704         /* if MCP exists send load request and analyze response */
12705         if (!BXE_NOMCP(sc)) {
12706             /* attempt to load pf */
12707             if (bxe_nic_load_request(sc, &load_code) != 0) {
12708                 sc->state = BXE_STATE_CLOSED;
12709                 rc = ENXIO;
12710                 goto bxe_nic_load_error1;
12711             }
12712 
12713             /* what did the MCP say? */
12714             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12715                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12716                 sc->state = BXE_STATE_CLOSED;
12717                 rc = ENXIO;
12718                 goto bxe_nic_load_error2;
12719             }
12720         } else {
12721             BLOGI(sc, "Device has no MCP!\n");
12722             load_code = bxe_nic_load_no_mcp(sc);
12723         }
12724 
12725         /* mark PMF if applicable */
12726         bxe_nic_load_pmf(sc, load_code);
12727 
12728         /* Init Function state controlling object */
12729         bxe_init_func_obj(sc);
12730 
12731         /* Initialize HW */
12732         if (bxe_init_hw(sc, load_code) != 0) {
12733             BLOGE(sc, "HW init failed\n");
12734             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12735             sc->state = BXE_STATE_CLOSED;
12736             rc = ENXIO;
12737             goto bxe_nic_load_error2;
12738         }
12739     }
12740 
12741     /* set ALWAYS_ALIVE bit in shmem */
12742     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12743     bxe_drv_pulse(sc);
12744     sc->flags |= BXE_NO_PULSE;
12745 
12746     /* attach interrupts */
12747     if (bxe_interrupt_attach(sc) != 0) {
12748         sc->state = BXE_STATE_CLOSED;
12749         rc = ENXIO;
12750         goto bxe_nic_load_error2;
12751     }
12752 
12753     bxe_nic_init(sc, load_code);
12754 
12755     /* Init per-function objects */
12756     if (IS_PF(sc)) {
12757         bxe_init_objs(sc);
12758         // XXX bxe_iov_nic_init(sc);
12759 
12760         /* set AFEX default VLAN tag to an invalid value */
12761         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12762         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12763 
12764         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12765         rc = bxe_func_start(sc);
12766         if (rc) {
12767             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12768             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12769             sc->state = BXE_STATE_ERROR;
12770             goto bxe_nic_load_error3;
12771         }
12772 
12773         /* send LOAD_DONE command to MCP */
12774         if (!BXE_NOMCP(sc)) {
12775             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12776             if (!load_code) {
12777                 BLOGE(sc, "MCP response failure, aborting\n");
12778                 sc->state = BXE_STATE_ERROR;
12779                 rc = ENXIO;
12780                 goto bxe_nic_load_error3;
12781             }
12782         }
12783 
12784         rc = bxe_setup_leading(sc);
12785         if (rc) {
12786             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12787             sc->state = BXE_STATE_ERROR;
12788             goto bxe_nic_load_error3;
12789         }
12790 
12791         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12792             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12793             if (rc) {
12794                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12795                 sc->state = BXE_STATE_ERROR;
12796                 goto bxe_nic_load_error3;
12797             }
12798         }
12799 
12800         rc = bxe_init_rss_pf(sc);
12801         if (rc) {
12802             BLOGE(sc, "PF RSS init failed\n");
12803             sc->state = BXE_STATE_ERROR;
12804             goto bxe_nic_load_error3;
12805         }
12806     }
12807     /* XXX VF */
12808 
12809     /* now when Clients are configured we are ready to work */
12810     sc->state = BXE_STATE_OPEN;
12811 
12812     /* Configure a ucast MAC */
12813     if (IS_PF(sc)) {
12814         rc = bxe_set_eth_mac(sc, TRUE);
12815     }
12816     if (rc) {
12817         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12818         sc->state = BXE_STATE_ERROR;
12819         goto bxe_nic_load_error3;
12820     }
12821 
12822     if (sc->port.pmf) {
12823         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12824         if (rc) {
12825             sc->state = BXE_STATE_ERROR;
12826             goto bxe_nic_load_error3;
12827         }
12828     }
12829 
12830     sc->link_params.feature_config_flags &=
12831         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12832 
12833     /* start fast path */
12834 
12835     /* Initialize Rx filter */
12836     bxe_set_rx_mode(sc);
12837 
12838     /* start the Tx */
12839     switch (/* XXX load_mode */LOAD_OPEN) {
12840     case LOAD_NORMAL:
12841     case LOAD_OPEN:
12842         break;
12843 
12844     case LOAD_DIAG:
12845     case LOAD_LOOPBACK_EXT:
12846         sc->state = BXE_STATE_DIAG;
12847         break;
12848 
12849     default:
12850         break;
12851     }
12852 
12853     if (sc->port.pmf) {
12854         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12855     } else {
12856         bxe_link_status_update(sc);
12857     }
12858 
12859     /* start the periodic timer callout */
12860     bxe_periodic_start(sc);
12861 
12862     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12863         /* mark driver is loaded in shmem2 */
12864         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12865         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12866                   (val |
12867                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12868                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12869     }
12870 
12871     /* wait for all pending SP commands to complete */
12872     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12873         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12874         bxe_periodic_stop(sc);
12875         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12876         return (ENXIO);
12877     }
12878 
12879     /* Tell the stack the driver is running! */
12880     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12881 
12882     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12883 
12884     return (0);
12885 
12886 bxe_nic_load_error3:
12887 
12888     if (IS_PF(sc)) {
12889         bxe_int_disable_sync(sc, 1);
12890 
12891         /* clean out queued objects */
12892         bxe_squeeze_objects(sc);
12893     }
12894 
12895     bxe_interrupt_detach(sc);
12896 
12897 bxe_nic_load_error2:
12898 
12899     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12900         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12901         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12902     }
12903 
12904     sc->port.pmf = 0;
12905 
12906 bxe_nic_load_error1:
12907 
12908     /* clear pf_load status, as it was already set */
12909     if (IS_PF(sc)) {
12910         bxe_clear_pf_load(sc);
12911     }
12912 
12913 bxe_nic_load_error0:
12914 
12915     bxe_free_fw_stats_mem(sc);
12916     bxe_free_fp_buffers(sc);
12917     bxe_free_mem(sc);
12918 
12919     return (rc);
12920 }
12921 
12922 static int
12923 bxe_init_locked(struct bxe_softc *sc)
12924 {
12925     int other_engine = SC_PATH(sc) ? 0 : 1;
12926     uint8_t other_load_status, load_status;
12927     uint8_t global = FALSE;
12928     int rc;
12929 
12930     BXE_CORE_LOCK_ASSERT(sc);
12931 
12932     /* check if the driver is already running */
12933     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12934         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12935         return (0);
12936     }
12937 
12938     if((sc->state == BXE_STATE_ERROR) &&
12939         (sc->recovery_state == BXE_RECOVERY_FAILED)) {
12940         BLOGE(sc, "Initialization not done, "
12941                   "as previous recovery failed."
12942                   "Reboot/Power-cycle the system\n" );
12943         return (ENXIO);
12944     }
12945 
12946 
12947     bxe_set_power_state(sc, PCI_PM_D0);
12948 
12949     /*
12950      * If parity occurred during the unload, then attentions and/or
12951      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12952      * loaded on the current engine to complete the recovery. Parity recovery
12953      * is only relevant for PF driver.
12954      */
12955     if (IS_PF(sc)) {
12956         other_load_status = bxe_get_load_status(sc, other_engine);
12957         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12958 
12959         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12960             bxe_chk_parity_attn(sc, &global, TRUE)) {
12961             do {
12962                 /*
12963                  * If there are attentions and they are in global blocks, set
12964                  * the GLOBAL_RESET bit regardless whether it will be this
12965                  * function that will complete the recovery or not.
12966                  */
12967                 if (global) {
12968                     bxe_set_reset_global(sc);
12969                 }
12970 
12971                 /*
12972                  * Only the first function on the current engine should try
12973                  * to recover in open. In case of attentions in global blocks
12974                  * only the first in the chip should try to recover.
12975                  */
12976                 if ((!load_status && (!global || !other_load_status)) &&
12977                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12978                     BLOGI(sc, "Recovered during init\n");
12979                     break;
12980                 }
12981 
12982                 /* recovery has failed... */
12983                 bxe_set_power_state(sc, PCI_PM_D3hot);
12984                 sc->recovery_state = BXE_RECOVERY_FAILED;
12985 
12986                 BLOGE(sc, "Recovery flow hasn't properly "
12987                           "completed yet, try again later. "
12988                           "If you still see this message after a "
12989                           "few retries then power cycle is required.\n");
12990 
12991                 rc = ENXIO;
12992                 goto bxe_init_locked_done;
12993             } while (0);
12994         }
12995     }
12996 
12997     sc->recovery_state = BXE_RECOVERY_DONE;
12998 
12999     rc = bxe_nic_load(sc, LOAD_OPEN);
13000 
13001 bxe_init_locked_done:
13002 
13003     if (rc) {
13004         /* Tell the stack the driver is NOT running! */
13005         BLOGE(sc, "Initialization failed, "
13006                   "stack notified driver is NOT running!\n");
13007 	if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
13008     }
13009 
13010     return (rc);
13011 }
13012 
13013 static int
13014 bxe_stop_locked(struct bxe_softc *sc)
13015 {
13016     BXE_CORE_LOCK_ASSERT(sc);
13017     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
13018 }
13019 
13020 /*
13021  * Handles controller initialization when called from an unlocked routine.
13022  * ifconfig calls this function.
13023  *
13024  * Returns:
13025  *   void
13026  */
13027 static void
13028 bxe_init(void *xsc)
13029 {
13030     struct bxe_softc *sc = (struct bxe_softc *)xsc;
13031 
13032     BXE_CORE_LOCK(sc);
13033     bxe_init_locked(sc);
13034     BXE_CORE_UNLOCK(sc);
13035 }
13036 
13037 static int
13038 bxe_init_ifnet(struct bxe_softc *sc)
13039 {
13040     if_t ifp;
13041     int capabilities;
13042 
13043     /* ifconfig entrypoint for media type/status reporting */
13044     ifmedia_init(&sc->ifmedia, IFM_IMASK,
13045                  bxe_ifmedia_update,
13046                  bxe_ifmedia_status);
13047 
13048     /* set the default interface values */
13049     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
13050     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
13051     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
13052 
13053     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
13054 	BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
13055 
13056     /* allocate the ifnet structure */
13057     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
13058         BLOGE(sc, "Interface allocation failed!\n");
13059         return (ENXIO);
13060     }
13061 
13062     if_setsoftc(ifp, sc);
13063     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
13064     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
13065     if_setioctlfn(ifp, bxe_ioctl);
13066     if_setstartfn(ifp, bxe_tx_start);
13067     if_setgetcounterfn(ifp, bxe_get_counter);
13068 #if __FreeBSD_version >= 901504
13069     if_settransmitfn(ifp, bxe_tx_mq_start);
13070     if_setqflushfn(ifp, bxe_mq_flush);
13071 #endif
13072 #ifdef FreeBSD8_0
13073     if_settimer(ifp, 0);
13074 #endif
13075     if_setinitfn(ifp, bxe_init);
13076     if_setmtu(ifp, sc->mtu);
13077     if_sethwassist(ifp, (CSUM_IP      |
13078                         CSUM_TCP      |
13079                         CSUM_UDP      |
13080                         CSUM_TSO      |
13081                         CSUM_TCP_IPV6 |
13082                         CSUM_UDP_IPV6));
13083 
13084     capabilities =
13085 #if __FreeBSD_version < 700000
13086         (IFCAP_VLAN_MTU       |
13087          IFCAP_VLAN_HWTAGGING |
13088          IFCAP_HWCSUM         |
13089          IFCAP_JUMBO_MTU      |
13090          IFCAP_LRO);
13091 #else
13092         (IFCAP_VLAN_MTU       |
13093          IFCAP_VLAN_HWTAGGING |
13094          IFCAP_VLAN_HWTSO     |
13095          IFCAP_VLAN_HWFILTER  |
13096          IFCAP_VLAN_HWCSUM    |
13097          IFCAP_HWCSUM         |
13098          IFCAP_JUMBO_MTU      |
13099          IFCAP_LRO            |
13100          IFCAP_TSO4           |
13101          IFCAP_TSO6           |
13102          IFCAP_WOL_MAGIC);
13103 #endif
13104     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
13105     if_setcapenable(ifp, if_getcapabilities(ifp));
13106     if_setbaudrate(ifp, IF_Gbps(10));
13107 /* XXX */
13108     if_setsendqlen(ifp, sc->tx_ring_size);
13109     if_setsendqready(ifp);
13110 /* XXX */
13111 
13112     sc->ifp = ifp;
13113 
13114     /* attach to the Ethernet interface list */
13115     ether_ifattach(ifp, sc->link_params.mac_addr);
13116 
13117     /* Attach driver debugnet methods. */
13118     DEBUGNET_SET(ifp, bxe);
13119 
13120     return (0);
13121 }
13122 
13123 static void
13124 bxe_deallocate_bars(struct bxe_softc *sc)
13125 {
13126     int i;
13127 
13128     for (i = 0; i < MAX_BARS; i++) {
13129         if (sc->bar[i].resource != NULL) {
13130             bus_release_resource(sc->dev,
13131                                  SYS_RES_MEMORY,
13132                                  sc->bar[i].rid,
13133                                  sc->bar[i].resource);
13134             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
13135                   i, PCIR_BAR(i));
13136         }
13137     }
13138 }
13139 
13140 static int
13141 bxe_allocate_bars(struct bxe_softc *sc)
13142 {
13143     u_int flags;
13144     int i;
13145 
13146     memset(sc->bar, 0, sizeof(sc->bar));
13147 
13148     for (i = 0; i < MAX_BARS; i++) {
13149 
13150         /* memory resources reside at BARs 0, 2, 4 */
13151         /* Run `pciconf -lb` to see mappings */
13152         if ((i != 0) && (i != 2) && (i != 4)) {
13153             continue;
13154         }
13155 
13156         sc->bar[i].rid = PCIR_BAR(i);
13157 
13158         flags = RF_ACTIVE;
13159         if (i == 0) {
13160             flags |= RF_SHAREABLE;
13161         }
13162 
13163         if ((sc->bar[i].resource =
13164              bus_alloc_resource_any(sc->dev,
13165                                     SYS_RES_MEMORY,
13166                                     &sc->bar[i].rid,
13167                                     flags)) == NULL) {
13168             return (0);
13169         }
13170 
13171         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
13172         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
13173         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
13174 
13175         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %#jx-%#jx (%jd) -> %#jx\n",
13176               i, PCIR_BAR(i),
13177               rman_get_start(sc->bar[i].resource),
13178               rman_get_end(sc->bar[i].resource),
13179               rman_get_size(sc->bar[i].resource),
13180               (uintmax_t)sc->bar[i].kva);
13181     }
13182 
13183     return (0);
13184 }
13185 
13186 static void
13187 bxe_get_function_num(struct bxe_softc *sc)
13188 {
13189     uint32_t val = 0;
13190 
13191     /*
13192      * Read the ME register to get the function number. The ME register
13193      * holds the relative-function number and absolute-function number. The
13194      * absolute-function number appears only in E2 and above. Before that
13195      * these bits always contained zero, therefore we cannot blindly use them.
13196      */
13197 
13198     val = REG_RD(sc, BAR_ME_REGISTER);
13199 
13200     sc->pfunc_rel =
13201         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
13202     sc->path_id =
13203         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
13204 
13205     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13206         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
13207     } else {
13208         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
13209     }
13210 
13211     BLOGD(sc, DBG_LOAD,
13212           "Relative function %d, Absolute function %d, Path %d\n",
13213           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
13214 }
13215 
13216 static uint32_t
13217 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
13218 {
13219     uint32_t shmem2_size;
13220     uint32_t offset;
13221     uint32_t mf_cfg_offset_value;
13222 
13223     /* Non 57712 */
13224     offset = (SHMEM_RD(sc, func_mb) +
13225               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
13226 
13227     /* 57712 plus */
13228     if (sc->devinfo.shmem2_base != 0) {
13229         shmem2_size = SHMEM2_RD(sc, size);
13230         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
13231             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
13232             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
13233                 offset = mf_cfg_offset_value;
13234             }
13235         }
13236     }
13237 
13238     return (offset);
13239 }
13240 
13241 static uint32_t
13242 bxe_pcie_capability_read(struct bxe_softc *sc,
13243                          int    reg,
13244                          int    width)
13245 {
13246     int pcie_reg;
13247 
13248     /* ensure PCIe capability is enabled */
13249     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
13250         if (pcie_reg != 0) {
13251             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
13252             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
13253         }
13254     }
13255 
13256     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
13257 
13258     return (0);
13259 }
13260 
13261 static uint8_t
13262 bxe_is_pcie_pending(struct bxe_softc *sc)
13263 {
13264     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
13265             PCIM_EXP_STA_TRANSACTION_PND);
13266 }
13267 
13268 /*
13269  * Walk the PCI capabiites list for the device to find what features are
13270  * supported. These capabilites may be enabled/disabled by firmware so it's
13271  * best to walk the list rather than make assumptions.
13272  */
13273 static void
13274 bxe_probe_pci_caps(struct bxe_softc *sc)
13275 {
13276     uint16_t link_status;
13277     int reg;
13278 
13279     /* check if PCI Power Management is enabled */
13280     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13281         if (reg != 0) {
13282             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13283 
13284             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13285             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13286         }
13287     }
13288 
13289     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13290 
13291     /* handle PCIe 2.0 workarounds for 57710 */
13292     if (CHIP_IS_E1(sc)) {
13293         /* workaround for 57710 errata E4_57710_27462 */
13294         sc->devinfo.pcie_link_speed =
13295             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13296 
13297         /* workaround for 57710 errata E4_57710_27488 */
13298         sc->devinfo.pcie_link_width =
13299             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13300         if (sc->devinfo.pcie_link_speed > 1) {
13301             sc->devinfo.pcie_link_width =
13302                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13303         }
13304     } else {
13305         sc->devinfo.pcie_link_speed =
13306             (link_status & PCIM_LINK_STA_SPEED);
13307         sc->devinfo.pcie_link_width =
13308             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13309     }
13310 
13311     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13312           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13313 
13314     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13315     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13316 
13317     /* check if MSI capability is enabled */
13318     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13319         if (reg != 0) {
13320             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13321 
13322             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13323             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13324         }
13325     }
13326 
13327     /* check if MSI-X capability is enabled */
13328     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13329         if (reg != 0) {
13330             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13331 
13332             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13333             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13334         }
13335     }
13336 }
13337 
13338 static int
13339 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13340 {
13341     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13342     uint32_t val;
13343 
13344     /* get the outer vlan if we're in switch-dependent mode */
13345 
13346     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13347     mf_info->ext_id = (uint16_t)val;
13348 
13349     mf_info->multi_vnics_mode = 1;
13350 
13351     if (!VALID_OVLAN(mf_info->ext_id)) {
13352         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13353         return (1);
13354     }
13355 
13356     /* get the capabilities */
13357     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13358         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13359         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13360     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13361                FUNC_MF_CFG_PROTOCOL_FCOE) {
13362         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13363     } else {
13364         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13365     }
13366 
13367     mf_info->vnics_per_port =
13368         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13369 
13370     return (0);
13371 }
13372 
13373 static uint32_t
13374 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13375 {
13376     uint32_t retval = 0;
13377     uint32_t val;
13378 
13379     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13380 
13381     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13382         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13383             retval |= MF_PROTO_SUPPORT_ETHERNET;
13384         }
13385         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13386             retval |= MF_PROTO_SUPPORT_ISCSI;
13387         }
13388         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13389             retval |= MF_PROTO_SUPPORT_FCOE;
13390         }
13391     }
13392 
13393     return (retval);
13394 }
13395 
13396 static int
13397 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13398 {
13399     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13400     uint32_t val;
13401 
13402     /*
13403      * There is no outer vlan if we're in switch-independent mode.
13404      * If the mac is valid then assume multi-function.
13405      */
13406 
13407     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13408 
13409     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13410 
13411     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13412 
13413     mf_info->vnics_per_port =
13414         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13415 
13416     return (0);
13417 }
13418 
13419 static int
13420 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13421 {
13422     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13423     uint32_t e1hov_tag;
13424     uint32_t func_config;
13425     uint32_t niv_config;
13426 
13427     mf_info->multi_vnics_mode = 1;
13428 
13429     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13430     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13431     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13432 
13433     mf_info->ext_id =
13434         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13435                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13436 
13437     mf_info->default_vlan =
13438         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13439                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13440 
13441     mf_info->niv_allowed_priorities =
13442         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13443                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13444 
13445     mf_info->niv_default_cos =
13446         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13447                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13448 
13449     mf_info->afex_vlan_mode =
13450         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13451          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13452 
13453     mf_info->niv_mba_enabled =
13454         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13455          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13456 
13457     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13458 
13459     mf_info->vnics_per_port =
13460         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13461 
13462     return (0);
13463 }
13464 
13465 static int
13466 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13467 {
13468     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13469     uint32_t mf_cfg1;
13470     uint32_t mf_cfg2;
13471     uint32_t ovlan1;
13472     uint32_t ovlan2;
13473     uint8_t i, j;
13474 
13475     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13476           SC_PORT(sc));
13477     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13478           mf_info->mf_config[SC_VN(sc)]);
13479     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13480           mf_info->multi_vnics_mode);
13481     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13482           mf_info->vnics_per_port);
13483     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13484           mf_info->ext_id);
13485     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13486           mf_info->min_bw[0], mf_info->min_bw[1],
13487           mf_info->min_bw[2], mf_info->min_bw[3]);
13488     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13489           mf_info->max_bw[0], mf_info->max_bw[1],
13490           mf_info->max_bw[2], mf_info->max_bw[3]);
13491     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13492           sc->mac_addr_str);
13493 
13494     /* various MF mode sanity checks... */
13495 
13496     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13497         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13498               SC_PORT(sc));
13499         return (1);
13500     }
13501 
13502     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13503         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13504               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13505         return (1);
13506     }
13507 
13508     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13509         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13510         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13511             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13512                   SC_VN(sc), OVLAN(sc));
13513             return (1);
13514         }
13515 
13516         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13517             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13518                   mf_info->multi_vnics_mode, OVLAN(sc));
13519             return (1);
13520         }
13521 
13522         /*
13523          * Verify all functions are either MF or SF mode. If MF, make sure
13524          * sure that all non-hidden functions have a valid ovlan. If SF,
13525          * make sure that all non-hidden functions have an invalid ovlan.
13526          */
13527         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13528             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13529             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13530             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13531                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13532                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13533                 BLOGE(sc, "mf_mode=SD function %d MF config "
13534                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13535                       i, mf_info->multi_vnics_mode, ovlan1);
13536                 return (1);
13537             }
13538         }
13539 
13540         /* Verify all funcs on the same port each have a different ovlan. */
13541         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13542             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13543             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13544             /* iterate from the next function on the port to the max func */
13545             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13546                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13547                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13548                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13549                     VALID_OVLAN(ovlan1) &&
13550                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13551                     VALID_OVLAN(ovlan2) &&
13552                     (ovlan1 == ovlan2)) {
13553                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13554                               "have the same ovlan (%d)\n",
13555                           i, j, ovlan1);
13556                     return (1);
13557                 }
13558             }
13559         }
13560     } /* MULTI_FUNCTION_SD */
13561 
13562     return (0);
13563 }
13564 
13565 static int
13566 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13567 {
13568     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13569     uint32_t val, mac_upper;
13570     uint8_t i, vnic;
13571 
13572     /* initialize mf_info defaults */
13573     mf_info->vnics_per_port   = 1;
13574     mf_info->multi_vnics_mode = FALSE;
13575     mf_info->path_has_ovlan   = FALSE;
13576     mf_info->mf_mode          = SINGLE_FUNCTION;
13577 
13578     if (!CHIP_IS_MF_CAP(sc)) {
13579         return (0);
13580     }
13581 
13582     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13583         BLOGE(sc, "Invalid mf_cfg_base!\n");
13584         return (1);
13585     }
13586 
13587     /* get the MF mode (switch dependent / independent / single-function) */
13588 
13589     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13590 
13591     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13592     {
13593     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13594 
13595         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13596 
13597         /* check for legal upper mac bytes */
13598         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13599             mf_info->mf_mode = MULTI_FUNCTION_SI;
13600         } else {
13601             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13602         }
13603 
13604         break;
13605 
13606     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13607     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13608 
13609         /* get outer vlan configuration */
13610         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13611 
13612         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13613             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13614             mf_info->mf_mode = MULTI_FUNCTION_SD;
13615         } else {
13616             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13617         }
13618 
13619         break;
13620 
13621     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13622 
13623         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13624         return (0);
13625 
13626     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13627 
13628         /*
13629          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13630          * and the MAC address is valid.
13631          */
13632         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13633 
13634         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13635             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13636             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13637         } else {
13638             BLOGE(sc, "Invalid config for AFEX mode\n");
13639         }
13640 
13641         break;
13642 
13643     default:
13644 
13645         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13646               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13647 
13648         return (1);
13649     }
13650 
13651     /* set path mf_mode (which could be different than function mf_mode) */
13652     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13653         mf_info->path_has_ovlan = TRUE;
13654     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13655         /*
13656          * Decide on path multi vnics mode. If we're not in MF mode and in
13657          * 4-port mode, this is good enough to check vnic-0 of the other port
13658          * on the same path
13659          */
13660         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13661             uint8_t other_port = !(PORT_ID(sc) & 1);
13662             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13663 
13664             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13665 
13666             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13667         }
13668     }
13669 
13670     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13671         /* invalid MF config */
13672         if (SC_VN(sc) >= 1) {
13673             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13674             return (1);
13675         }
13676 
13677         return (0);
13678     }
13679 
13680     /* get the MF configuration */
13681     mf_info->mf_config[SC_VN(sc)] =
13682         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13683 
13684     switch(mf_info->mf_mode)
13685     {
13686     case MULTI_FUNCTION_SD:
13687 
13688         bxe_get_shmem_mf_cfg_info_sd(sc);
13689         break;
13690 
13691     case MULTI_FUNCTION_SI:
13692 
13693         bxe_get_shmem_mf_cfg_info_si(sc);
13694         break;
13695 
13696     case MULTI_FUNCTION_AFEX:
13697 
13698         bxe_get_shmem_mf_cfg_info_niv(sc);
13699         break;
13700 
13701     default:
13702 
13703         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13704               mf_info->mf_mode);
13705         return (1);
13706     }
13707 
13708     /* get the congestion management parameters */
13709 
13710     vnic = 0;
13711     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13712         /* get min/max bw */
13713         val = MFCFG_RD(sc, func_mf_config[i].config);
13714         mf_info->min_bw[vnic] =
13715             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13716         mf_info->max_bw[vnic] =
13717             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13718         vnic++;
13719     }
13720 
13721     return (bxe_check_valid_mf_cfg(sc));
13722 }
13723 
13724 static int
13725 bxe_get_shmem_info(struct bxe_softc *sc)
13726 {
13727     int port;
13728     uint32_t mac_hi, mac_lo, val;
13729 
13730     port = SC_PORT(sc);
13731     mac_hi = mac_lo = 0;
13732 
13733     sc->link_params.sc   = sc;
13734     sc->link_params.port = port;
13735 
13736     /* get the hardware config info */
13737     sc->devinfo.hw_config =
13738         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13739     sc->devinfo.hw_config2 =
13740         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13741 
13742     sc->link_params.hw_led_mode =
13743         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13744          SHARED_HW_CFG_LED_MODE_SHIFT);
13745 
13746     /* get the port feature config */
13747     sc->port.config =
13748         SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13749 
13750     /* get the link params */
13751     sc->link_params.speed_cap_mask[0] =
13752         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13753     sc->link_params.speed_cap_mask[1] =
13754         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13755 
13756     /* get the lane config */
13757     sc->link_params.lane_config =
13758         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13759 
13760     /* get the link config */
13761     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13762     sc->port.link_config[ELINK_INT_PHY] = val;
13763     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13764     sc->port.link_config[ELINK_EXT_PHY1] =
13765         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13766 
13767     /* get the override preemphasis flag and enable it or turn it off */
13768     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13769     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13770         sc->link_params.feature_config_flags |=
13771             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13772     } else {
13773         sc->link_params.feature_config_flags &=
13774             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13775     }
13776 
13777     /* get the initial value of the link params */
13778     sc->link_params.multi_phy_config =
13779         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13780 
13781     /* get external phy info */
13782     sc->port.ext_phy_config =
13783         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13784 
13785     /* get the multifunction configuration */
13786     bxe_get_mf_cfg_info(sc);
13787 
13788     /* get the mac address */
13789     if (IS_MF(sc)) {
13790         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13791         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13792     } else {
13793         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13794         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13795     }
13796 
13797     if ((mac_lo == 0) && (mac_hi == 0)) {
13798         *sc->mac_addr_str = 0;
13799         BLOGE(sc, "No Ethernet address programmed!\n");
13800     } else {
13801         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13802         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13803         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13804         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13805         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13806         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13807         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13808                  "%02x:%02x:%02x:%02x:%02x:%02x",
13809                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13810                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13811                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13812         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13813     }
13814 
13815     return (0);
13816 }
13817 
13818 static void
13819 bxe_get_tunable_params(struct bxe_softc *sc)
13820 {
13821     /* sanity checks */
13822 
13823     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13824         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13825         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13826         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13827         bxe_interrupt_mode = INTR_MODE_MSIX;
13828     }
13829 
13830     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13831         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13832         bxe_queue_count = 0;
13833     }
13834 
13835     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13836         if (bxe_max_rx_bufs == 0) {
13837             bxe_max_rx_bufs = RX_BD_USABLE;
13838         } else {
13839             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13840             bxe_max_rx_bufs = 2048;
13841         }
13842     }
13843 
13844     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13845         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13846         bxe_hc_rx_ticks = 25;
13847     }
13848 
13849     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13850         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13851         bxe_hc_tx_ticks = 50;
13852     }
13853 
13854     if (bxe_max_aggregation_size == 0) {
13855         bxe_max_aggregation_size = TPA_AGG_SIZE;
13856     }
13857 
13858     if (bxe_max_aggregation_size > 0xffff) {
13859         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13860               bxe_max_aggregation_size);
13861         bxe_max_aggregation_size = TPA_AGG_SIZE;
13862     }
13863 
13864     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13865         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13866         bxe_mrrs = -1;
13867     }
13868 
13869     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13870         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13871         bxe_autogreeen = 0;
13872     }
13873 
13874     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13875         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13876         bxe_udp_rss = 0;
13877     }
13878 
13879     /* pull in user settings */
13880 
13881     sc->interrupt_mode       = bxe_interrupt_mode;
13882     sc->max_rx_bufs          = bxe_max_rx_bufs;
13883     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13884     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13885     sc->max_aggregation_size = bxe_max_aggregation_size;
13886     sc->mrrs                 = bxe_mrrs;
13887     sc->autogreeen           = bxe_autogreeen;
13888     sc->udp_rss              = bxe_udp_rss;
13889 
13890     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13891         sc->num_queues = 1;
13892     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13893         sc->num_queues =
13894             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13895                 MAX_RSS_CHAINS);
13896         if (sc->num_queues > mp_ncpus) {
13897             sc->num_queues = mp_ncpus;
13898         }
13899     }
13900 
13901     BLOGD(sc, DBG_LOAD,
13902           "User Config: "
13903           "debug=0x%lx "
13904           "interrupt_mode=%d "
13905           "queue_count=%d "
13906           "hc_rx_ticks=%d "
13907           "hc_tx_ticks=%d "
13908           "rx_budget=%d "
13909           "max_aggregation_size=%d "
13910           "mrrs=%d "
13911           "autogreeen=%d "
13912           "udp_rss=%d\n",
13913           bxe_debug,
13914           sc->interrupt_mode,
13915           sc->num_queues,
13916           sc->hc_rx_ticks,
13917           sc->hc_tx_ticks,
13918           bxe_rx_budget,
13919           sc->max_aggregation_size,
13920           sc->mrrs,
13921           sc->autogreeen,
13922           sc->udp_rss);
13923 }
13924 
13925 static int
13926 bxe_media_detect(struct bxe_softc *sc)
13927 {
13928     int port_type;
13929     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13930 
13931     switch (sc->link_params.phy[phy_idx].media_type) {
13932     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13933     case ELINK_ETH_PHY_XFP_FIBER:
13934         BLOGI(sc, "Found 10Gb Fiber media.\n");
13935         sc->media = IFM_10G_SR;
13936         port_type = PORT_FIBRE;
13937         break;
13938     case ELINK_ETH_PHY_SFP_1G_FIBER:
13939         BLOGI(sc, "Found 1Gb Fiber media.\n");
13940         sc->media = IFM_1000_SX;
13941         port_type = PORT_FIBRE;
13942         break;
13943     case ELINK_ETH_PHY_KR:
13944     case ELINK_ETH_PHY_CX4:
13945         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13946         sc->media = IFM_10G_CX4;
13947         port_type = PORT_FIBRE;
13948         break;
13949     case ELINK_ETH_PHY_DA_TWINAX:
13950         BLOGI(sc, "Found 10Gb Twinax media.\n");
13951         sc->media = IFM_10G_TWINAX;
13952         port_type = PORT_DA;
13953         break;
13954     case ELINK_ETH_PHY_BASE_T:
13955         if (sc->link_params.speed_cap_mask[0] &
13956             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13957             BLOGI(sc, "Found 10GBase-T media.\n");
13958             sc->media = IFM_10G_T;
13959             port_type = PORT_TP;
13960         } else {
13961             BLOGI(sc, "Found 1000Base-T media.\n");
13962             sc->media = IFM_1000_T;
13963             port_type = PORT_TP;
13964         }
13965         break;
13966     case ELINK_ETH_PHY_NOT_PRESENT:
13967         BLOGI(sc, "Media not present.\n");
13968         sc->media = 0;
13969         port_type = PORT_OTHER;
13970         break;
13971     case ELINK_ETH_PHY_UNSPECIFIED:
13972     default:
13973         BLOGI(sc, "Unknown media!\n");
13974         sc->media = 0;
13975         port_type = PORT_OTHER;
13976         break;
13977     }
13978     return port_type;
13979 }
13980 
13981 #define GET_FIELD(value, fname)                     \
13982     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13983 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13984 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13985 
13986 static int
13987 bxe_get_igu_cam_info(struct bxe_softc *sc)
13988 {
13989     int pfid = SC_FUNC(sc);
13990     int igu_sb_id;
13991     uint32_t val;
13992     uint8_t fid, igu_sb_cnt = 0;
13993 
13994     sc->igu_base_sb = 0xff;
13995 
13996     if (CHIP_INT_MODE_IS_BC(sc)) {
13997         int vn = SC_VN(sc);
13998         igu_sb_cnt = sc->igu_sb_cnt;
13999         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
14000                            FP_SB_MAX_E1x);
14001         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
14002                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
14003         return (0);
14004     }
14005 
14006     /* IGU in normal mode - read CAM */
14007     for (igu_sb_id = 0;
14008          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
14009          igu_sb_id++) {
14010         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
14011         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
14012             continue;
14013         }
14014         fid = IGU_FID(val);
14015         if ((fid & IGU_FID_ENCODE_IS_PF)) {
14016             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
14017                 continue;
14018             }
14019             if (IGU_VEC(val) == 0) {
14020                 /* default status block */
14021                 sc->igu_dsb_id = igu_sb_id;
14022             } else {
14023                 if (sc->igu_base_sb == 0xff) {
14024                     sc->igu_base_sb = igu_sb_id;
14025                 }
14026                 igu_sb_cnt++;
14027             }
14028         }
14029     }
14030 
14031     /*
14032      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
14033      * that number of CAM entries will not be equal to the value advertised in
14034      * PCI. Driver should use the minimal value of both as the actual status
14035      * block count
14036      */
14037     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
14038 
14039     if (igu_sb_cnt == 0) {
14040         BLOGE(sc, "CAM configuration error\n");
14041         return (-1);
14042     }
14043 
14044     return (0);
14045 }
14046 
14047 /*
14048  * Gather various information from the device config space, the device itself,
14049  * shmem, and the user input.
14050  */
14051 static int
14052 bxe_get_device_info(struct bxe_softc *sc)
14053 {
14054     uint32_t val;
14055     int rc;
14056 
14057     /* Get the data for the device */
14058     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
14059     sc->devinfo.device_id    = pci_get_device(sc->dev);
14060     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
14061     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
14062 
14063     /* get the chip revision (chip metal comes from pci config space) */
14064     sc->devinfo.chip_id     =
14065     sc->link_params.chip_id =
14066         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
14067          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
14068          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
14069          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
14070 
14071     /* force 57811 according to MISC register */
14072     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
14073         if (CHIP_IS_57810(sc)) {
14074             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
14075                                    (sc->devinfo.chip_id & 0x0000ffff));
14076         } else if (CHIP_IS_57810_MF(sc)) {
14077             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
14078                                    (sc->devinfo.chip_id & 0x0000ffff));
14079         }
14080         sc->devinfo.chip_id |= 0x1;
14081     }
14082 
14083     BLOGD(sc, DBG_LOAD,
14084           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
14085           sc->devinfo.chip_id,
14086           ((sc->devinfo.chip_id >> 16) & 0xffff),
14087           ((sc->devinfo.chip_id >> 12) & 0xf),
14088           ((sc->devinfo.chip_id >>  4) & 0xff),
14089           ((sc->devinfo.chip_id >>  0) & 0xf));
14090 
14091     val = (REG_RD(sc, 0x2874) & 0x55);
14092     if ((sc->devinfo.chip_id & 0x1) ||
14093         (CHIP_IS_E1(sc) && val) ||
14094         (CHIP_IS_E1H(sc) && (val == 0x55))) {
14095         sc->flags |= BXE_ONE_PORT_FLAG;
14096         BLOGD(sc, DBG_LOAD, "single port device\n");
14097     }
14098 
14099     /* set the doorbell size */
14100     sc->doorbell_size = (1 << BXE_DB_SHIFT);
14101 
14102     /* determine whether the device is in 2 port or 4 port mode */
14103     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
14104     if (CHIP_IS_E2E3(sc)) {
14105         /*
14106          * Read port4mode_en_ovwr[0]:
14107          *   If 1, four port mode is in port4mode_en_ovwr[1].
14108          *   If 0, four port mode is in port4mode_en[0].
14109          */
14110         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
14111         if (val & 1) {
14112             val = ((val >> 1) & 1);
14113         } else {
14114             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
14115         }
14116 
14117         sc->devinfo.chip_port_mode =
14118             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
14119 
14120         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
14121     }
14122 
14123     /* get the function and path info for the device */
14124     bxe_get_function_num(sc);
14125 
14126     /* get the shared memory base address */
14127     sc->devinfo.shmem_base     =
14128     sc->link_params.shmem_base =
14129         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
14130     sc->devinfo.shmem2_base =
14131         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
14132                                   MISC_REG_GENERIC_CR_0));
14133 
14134     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
14135           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
14136 
14137     if (!sc->devinfo.shmem_base) {
14138         /* this should ONLY prevent upcoming shmem reads */
14139         BLOGI(sc, "MCP not active\n");
14140         sc->flags |= BXE_NO_MCP_FLAG;
14141         return (0);
14142     }
14143 
14144     /* make sure the shared memory contents are valid */
14145     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
14146     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
14147         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
14148         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
14149         return (0);
14150     }
14151     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
14152 
14153     /* get the bootcode version */
14154     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
14155     snprintf(sc->devinfo.bc_ver_str,
14156              sizeof(sc->devinfo.bc_ver_str),
14157              "%d.%d.%d",
14158              ((sc->devinfo.bc_ver >> 24) & 0xff),
14159              ((sc->devinfo.bc_ver >> 16) & 0xff),
14160              ((sc->devinfo.bc_ver >>  8) & 0xff));
14161     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
14162 
14163     /* get the bootcode shmem address */
14164     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
14165     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
14166 
14167     /* clean indirect addresses as they're not used */
14168     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
14169     if (IS_PF(sc)) {
14170         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
14171         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
14172         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
14173         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
14174         if (CHIP_IS_E1x(sc)) {
14175             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
14176             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
14177             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
14178             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
14179         }
14180 
14181         /*
14182          * Enable internal target-read (in case we are probed after PF
14183          * FLR). Must be done prior to any BAR read access. Only for
14184          * 57712 and up
14185          */
14186         if (!CHIP_IS_E1x(sc)) {
14187             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
14188         }
14189     }
14190 
14191     /* get the nvram size */
14192     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
14193     sc->devinfo.flash_size =
14194         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
14195     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
14196 
14197     /* get PCI capabilites */
14198     bxe_probe_pci_caps(sc);
14199 
14200     bxe_set_power_state(sc, PCI_PM_D0);
14201 
14202     /* get various configuration parameters from shmem */
14203     bxe_get_shmem_info(sc);
14204 
14205     if (sc->devinfo.pcie_msix_cap_reg != 0) {
14206         val = pci_read_config(sc->dev,
14207                               (sc->devinfo.pcie_msix_cap_reg +
14208                                PCIR_MSIX_CTRL),
14209                               2);
14210         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
14211     } else {
14212         sc->igu_sb_cnt = 1;
14213     }
14214 
14215     sc->igu_base_addr = BAR_IGU_INTMEM;
14216 
14217     /* initialize IGU parameters */
14218     if (CHIP_IS_E1x(sc)) {
14219         sc->devinfo.int_block = INT_BLOCK_HC;
14220         sc->igu_dsb_id = DEF_SB_IGU_ID;
14221         sc->igu_base_sb = 0;
14222     } else {
14223         sc->devinfo.int_block = INT_BLOCK_IGU;
14224 
14225         /* do not allow device reset during IGU info preocessing */
14226         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14227 
14228         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
14229 
14230         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14231             int tout = 5000;
14232 
14233             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
14234 
14235             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
14236             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
14237             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
14238 
14239             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14240                 tout--;
14241                 DELAY(1000);
14242             }
14243 
14244             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
14245                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
14246                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14247                 return (-1);
14248             }
14249         }
14250 
14251         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
14252             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
14253             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
14254         } else {
14255             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
14256         }
14257 
14258         rc = bxe_get_igu_cam_info(sc);
14259 
14260         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
14261 
14262         if (rc) {
14263             return (rc);
14264         }
14265     }
14266 
14267     /*
14268      * Get base FW non-default (fast path) status block ID. This value is
14269      * used to initialize the fw_sb_id saved on the fp/queue structure to
14270      * determine the id used by the FW.
14271      */
14272     if (CHIP_IS_E1x(sc)) {
14273         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
14274     } else {
14275         /*
14276          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
14277          * the same queue are indicated on the same IGU SB). So we prefer
14278          * FW and IGU SBs to be the same value.
14279          */
14280         sc->base_fw_ndsb = sc->igu_base_sb;
14281     }
14282 
14283     BLOGD(sc, DBG_LOAD,
14284           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14285           sc->igu_dsb_id, sc->igu_base_sb,
14286           sc->igu_sb_cnt, sc->base_fw_ndsb);
14287 
14288     elink_phy_probe(&sc->link_params);
14289 
14290     return (0);
14291 }
14292 
14293 static void
14294 bxe_link_settings_supported(struct bxe_softc *sc,
14295                             uint32_t         switch_cfg)
14296 {
14297     uint32_t cfg_size = 0;
14298     uint32_t idx;
14299     uint8_t port = SC_PORT(sc);
14300 
14301     /* aggregation of supported attributes of all external phys */
14302     sc->port.supported[0] = 0;
14303     sc->port.supported[1] = 0;
14304 
14305     switch (sc->link_params.num_phys) {
14306     case 1:
14307         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14308         cfg_size = 1;
14309         break;
14310     case 2:
14311         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14312         cfg_size = 1;
14313         break;
14314     case 3:
14315         if (sc->link_params.multi_phy_config &
14316             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14317             sc->port.supported[1] =
14318                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14319             sc->port.supported[0] =
14320                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14321         } else {
14322             sc->port.supported[0] =
14323                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14324             sc->port.supported[1] =
14325                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14326         }
14327         cfg_size = 2;
14328         break;
14329     }
14330 
14331     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14332         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14333               SHMEM_RD(sc,
14334                        dev_info.port_hw_config[port].external_phy_config),
14335               SHMEM_RD(sc,
14336                        dev_info.port_hw_config[port].external_phy_config2));
14337         return;
14338     }
14339 
14340     if (CHIP_IS_E3(sc))
14341         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14342     else {
14343         switch (switch_cfg) {
14344         case ELINK_SWITCH_CFG_1G:
14345             sc->port.phy_addr =
14346                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14347             break;
14348         case ELINK_SWITCH_CFG_10G:
14349             sc->port.phy_addr =
14350                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14351             break;
14352         default:
14353             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14354                   sc->port.link_config[0]);
14355             return;
14356         }
14357     }
14358 
14359     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14360 
14361     /* mask what we support according to speed_cap_mask per configuration */
14362     for (idx = 0; idx < cfg_size; idx++) {
14363         if (!(sc->link_params.speed_cap_mask[idx] &
14364               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14365             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14366         }
14367 
14368         if (!(sc->link_params.speed_cap_mask[idx] &
14369               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14370             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14371         }
14372 
14373         if (!(sc->link_params.speed_cap_mask[idx] &
14374               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14375             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14376         }
14377 
14378         if (!(sc->link_params.speed_cap_mask[idx] &
14379               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14380             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14381         }
14382 
14383         if (!(sc->link_params.speed_cap_mask[idx] &
14384               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14385             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14386         }
14387 
14388         if (!(sc->link_params.speed_cap_mask[idx] &
14389               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14390             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14391         }
14392 
14393         if (!(sc->link_params.speed_cap_mask[idx] &
14394               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14395             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14396         }
14397 
14398         if (!(sc->link_params.speed_cap_mask[idx] &
14399               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14400             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14401         }
14402     }
14403 
14404     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14405           sc->port.supported[0], sc->port.supported[1]);
14406 	ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14407 					sc->port.supported[0], sc->port.supported[1]);
14408 }
14409 
14410 static void
14411 bxe_link_settings_requested(struct bxe_softc *sc)
14412 {
14413     uint32_t link_config;
14414     uint32_t idx;
14415     uint32_t cfg_size = 0;
14416 
14417     sc->port.advertising[0] = 0;
14418     sc->port.advertising[1] = 0;
14419 
14420     switch (sc->link_params.num_phys) {
14421     case 1:
14422     case 2:
14423         cfg_size = 1;
14424         break;
14425     case 3:
14426         cfg_size = 2;
14427         break;
14428     }
14429 
14430     for (idx = 0; idx < cfg_size; idx++) {
14431         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14432         link_config = sc->port.link_config[idx];
14433 
14434         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14435         case PORT_FEATURE_LINK_SPEED_AUTO:
14436             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14437                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14438                 sc->port.advertising[idx] |= sc->port.supported[idx];
14439                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14440                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14441                     sc->port.advertising[idx] |=
14442                         (ELINK_SUPPORTED_100baseT_Half |
14443                          ELINK_SUPPORTED_100baseT_Full);
14444             } else {
14445                 /* force 10G, no AN */
14446                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14447                 sc->port.advertising[idx] |=
14448                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14449                 continue;
14450             }
14451             break;
14452 
14453         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14454             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14455                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14456                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14457                                               ADVERTISED_TP);
14458             } else {
14459                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14460                           "speed_cap_mask=0x%08x\n",
14461                       link_config, sc->link_params.speed_cap_mask[idx]);
14462                 return;
14463             }
14464             break;
14465 
14466         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14467             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14468                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14469                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14470                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14471                                               ADVERTISED_TP);
14472 				ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14473 								sc->link_params.req_duplex[idx]);
14474             } else {
14475                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14476                           "speed_cap_mask=0x%08x\n",
14477                       link_config, sc->link_params.speed_cap_mask[idx]);
14478                 return;
14479             }
14480             break;
14481 
14482         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14483             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14484                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14485                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14486                                               ADVERTISED_TP);
14487             } else {
14488                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14489                           "speed_cap_mask=0x%08x\n",
14490                       link_config, sc->link_params.speed_cap_mask[idx]);
14491                 return;
14492             }
14493             break;
14494 
14495         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14496             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14497                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14498                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14499                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14500                                               ADVERTISED_TP);
14501             } else {
14502                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14503                           "speed_cap_mask=0x%08x\n",
14504                       link_config, sc->link_params.speed_cap_mask[idx]);
14505                 return;
14506             }
14507             break;
14508 
14509         case PORT_FEATURE_LINK_SPEED_1G:
14510             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14511                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14512                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14513                                               ADVERTISED_TP);
14514             } else {
14515                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14516                           "speed_cap_mask=0x%08x\n",
14517                       link_config, sc->link_params.speed_cap_mask[idx]);
14518                 return;
14519             }
14520             break;
14521 
14522         case PORT_FEATURE_LINK_SPEED_2_5G:
14523             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14524                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14525                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14526                                               ADVERTISED_TP);
14527             } else {
14528                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14529                           "speed_cap_mask=0x%08x\n",
14530                       link_config, sc->link_params.speed_cap_mask[idx]);
14531                 return;
14532             }
14533             break;
14534 
14535         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14536             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14537                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14538                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14539                                               ADVERTISED_FIBRE);
14540             } else {
14541                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14542                           "speed_cap_mask=0x%08x\n",
14543                       link_config, sc->link_params.speed_cap_mask[idx]);
14544                 return;
14545             }
14546             break;
14547 
14548         case PORT_FEATURE_LINK_SPEED_20G:
14549             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14550             break;
14551 
14552         default:
14553             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14554                       "speed_cap_mask=0x%08x\n",
14555                   link_config, sc->link_params.speed_cap_mask[idx]);
14556             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14557             sc->port.advertising[idx] = sc->port.supported[idx];
14558             break;
14559         }
14560 
14561         sc->link_params.req_flow_ctrl[idx] =
14562             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14563 
14564         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14565             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14566                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14567             } else {
14568                 bxe_set_requested_fc(sc);
14569             }
14570         }
14571 
14572         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14573                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14574               sc->link_params.req_line_speed[idx],
14575               sc->link_params.req_duplex[idx],
14576               sc->link_params.req_flow_ctrl[idx],
14577               sc->port.advertising[idx]);
14578 		ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14579 						"advertising=0x%x\n",
14580 						sc->link_params.req_line_speed[idx],
14581 						sc->link_params.req_duplex[idx],
14582 						sc->port.advertising[idx]);
14583     }
14584 }
14585 
14586 static void
14587 bxe_get_phy_info(struct bxe_softc *sc)
14588 {
14589     uint8_t port = SC_PORT(sc);
14590     uint32_t config = sc->port.config;
14591     uint32_t eee_mode;
14592 
14593     /* shmem data already read in bxe_get_shmem_info() */
14594 
14595     ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14596                         "link_config0=0x%08x\n",
14597                sc->link_params.lane_config,
14598                sc->link_params.speed_cap_mask[0],
14599                sc->port.link_config[0]);
14600 
14601 
14602     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14603     bxe_link_settings_requested(sc);
14604 
14605     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14606         sc->link_params.feature_config_flags |=
14607             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14608     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14609         sc->link_params.feature_config_flags &=
14610             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14611     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14612         sc->link_params.feature_config_flags |=
14613             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14614     }
14615 
14616     /* configure link feature according to nvram value */
14617     eee_mode =
14618         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14619           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14620          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14621     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14622         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14623                                     ELINK_EEE_MODE_ENABLE_LPI |
14624                                     ELINK_EEE_MODE_OUTPUT_TIME);
14625     } else {
14626         sc->link_params.eee_mode = 0;
14627     }
14628 
14629     /* get the media type */
14630     bxe_media_detect(sc);
14631 	ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14632 }
14633 
14634 static void
14635 bxe_get_params(struct bxe_softc *sc)
14636 {
14637     /* get user tunable params */
14638     bxe_get_tunable_params(sc);
14639 
14640     /* select the RX and TX ring sizes */
14641     sc->tx_ring_size = TX_BD_USABLE;
14642     sc->rx_ring_size = RX_BD_USABLE;
14643 
14644     /* XXX disable WoL */
14645     sc->wol = 0;
14646 }
14647 
14648 static void
14649 bxe_set_modes_bitmap(struct bxe_softc *sc)
14650 {
14651     uint32_t flags = 0;
14652 
14653     if (CHIP_REV_IS_FPGA(sc)) {
14654         SET_FLAGS(flags, MODE_FPGA);
14655     } else if (CHIP_REV_IS_EMUL(sc)) {
14656         SET_FLAGS(flags, MODE_EMUL);
14657     } else {
14658         SET_FLAGS(flags, MODE_ASIC);
14659     }
14660 
14661     if (CHIP_IS_MODE_4_PORT(sc)) {
14662         SET_FLAGS(flags, MODE_PORT4);
14663     } else {
14664         SET_FLAGS(flags, MODE_PORT2);
14665     }
14666 
14667     if (CHIP_IS_E2(sc)) {
14668         SET_FLAGS(flags, MODE_E2);
14669     } else if (CHIP_IS_E3(sc)) {
14670         SET_FLAGS(flags, MODE_E3);
14671         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14672             SET_FLAGS(flags, MODE_E3_A0);
14673         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14674             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14675         }
14676     }
14677 
14678     if (IS_MF(sc)) {
14679         SET_FLAGS(flags, MODE_MF);
14680         switch (sc->devinfo.mf_info.mf_mode) {
14681         case MULTI_FUNCTION_SD:
14682             SET_FLAGS(flags, MODE_MF_SD);
14683             break;
14684         case MULTI_FUNCTION_SI:
14685             SET_FLAGS(flags, MODE_MF_SI);
14686             break;
14687         case MULTI_FUNCTION_AFEX:
14688             SET_FLAGS(flags, MODE_MF_AFEX);
14689             break;
14690         }
14691     } else {
14692         SET_FLAGS(flags, MODE_SF);
14693     }
14694 
14695 #if defined(__LITTLE_ENDIAN)
14696     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14697 #else /* __BIG_ENDIAN */
14698     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14699 #endif
14700 
14701     INIT_MODE_FLAGS(sc) = flags;
14702 }
14703 
14704 static int
14705 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14706 {
14707     struct bxe_fastpath *fp;
14708     bus_addr_t busaddr;
14709     int max_agg_queues;
14710     int max_segments;
14711     bus_size_t max_size;
14712     bus_size_t max_seg_size;
14713     char buf[32];
14714     int rc;
14715     int i, j;
14716 
14717     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14718 
14719     /* allocate the parent bus DMA tag */
14720     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14721                             1,                        /* alignment */
14722                             0,                        /* boundary limit */
14723                             BUS_SPACE_MAXADDR,        /* restricted low */
14724                             BUS_SPACE_MAXADDR,        /* restricted hi */
14725                             NULL,                     /* addr filter() */
14726                             NULL,                     /* addr filter() arg */
14727                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14728                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14729                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14730                             0,                        /* flags */
14731                             NULL,                     /* lock() */
14732                             NULL,                     /* lock() arg */
14733                             &sc->parent_dma_tag);     /* returned dma tag */
14734     if (rc != 0) {
14735         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14736         return (1);
14737     }
14738 
14739     /************************/
14740     /* DEFAULT STATUS BLOCK */
14741     /************************/
14742 
14743     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14744                       &sc->def_sb_dma, "default status block") != 0) {
14745         /* XXX */
14746         bus_dma_tag_destroy(sc->parent_dma_tag);
14747         return (1);
14748     }
14749 
14750     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14751 
14752     /***************/
14753     /* EVENT QUEUE */
14754     /***************/
14755 
14756     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14757                       &sc->eq_dma, "event queue") != 0) {
14758         /* XXX */
14759         bxe_dma_free(sc, &sc->def_sb_dma);
14760         sc->def_sb = NULL;
14761         bus_dma_tag_destroy(sc->parent_dma_tag);
14762         return (1);
14763     }
14764 
14765     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14766 
14767     /*************/
14768     /* SLOW PATH */
14769     /*************/
14770 
14771     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14772                       &sc->sp_dma, "slow path") != 0) {
14773         /* XXX */
14774         bxe_dma_free(sc, &sc->eq_dma);
14775         sc->eq = NULL;
14776         bxe_dma_free(sc, &sc->def_sb_dma);
14777         sc->def_sb = NULL;
14778         bus_dma_tag_destroy(sc->parent_dma_tag);
14779         return (1);
14780     }
14781 
14782     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14783 
14784     /*******************/
14785     /* SLOW PATH QUEUE */
14786     /*******************/
14787 
14788     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14789                       &sc->spq_dma, "slow path queue") != 0) {
14790         /* XXX */
14791         bxe_dma_free(sc, &sc->sp_dma);
14792         sc->sp = NULL;
14793         bxe_dma_free(sc, &sc->eq_dma);
14794         sc->eq = NULL;
14795         bxe_dma_free(sc, &sc->def_sb_dma);
14796         sc->def_sb = NULL;
14797         bus_dma_tag_destroy(sc->parent_dma_tag);
14798         return (1);
14799     }
14800 
14801     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14802 
14803     /***************************/
14804     /* FW DECOMPRESSION BUFFER */
14805     /***************************/
14806 
14807     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14808                       "fw decompression buffer") != 0) {
14809         /* XXX */
14810         bxe_dma_free(sc, &sc->spq_dma);
14811         sc->spq = NULL;
14812         bxe_dma_free(sc, &sc->sp_dma);
14813         sc->sp = NULL;
14814         bxe_dma_free(sc, &sc->eq_dma);
14815         sc->eq = NULL;
14816         bxe_dma_free(sc, &sc->def_sb_dma);
14817         sc->def_sb = NULL;
14818         bus_dma_tag_destroy(sc->parent_dma_tag);
14819         return (1);
14820     }
14821 
14822     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14823 
14824     if ((sc->gz_strm =
14825          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14826         /* XXX */
14827         bxe_dma_free(sc, &sc->gz_buf_dma);
14828         sc->gz_buf = NULL;
14829         bxe_dma_free(sc, &sc->spq_dma);
14830         sc->spq = NULL;
14831         bxe_dma_free(sc, &sc->sp_dma);
14832         sc->sp = NULL;
14833         bxe_dma_free(sc, &sc->eq_dma);
14834         sc->eq = NULL;
14835         bxe_dma_free(sc, &sc->def_sb_dma);
14836         sc->def_sb = NULL;
14837         bus_dma_tag_destroy(sc->parent_dma_tag);
14838         return (1);
14839     }
14840 
14841     /*************/
14842     /* FASTPATHS */
14843     /*************/
14844 
14845     /* allocate DMA memory for each fastpath structure */
14846     for (i = 0; i < sc->num_queues; i++) {
14847         fp = &sc->fp[i];
14848         fp->sc    = sc;
14849         fp->index = i;
14850 
14851         /*******************/
14852         /* FP STATUS BLOCK */
14853         /*******************/
14854 
14855         snprintf(buf, sizeof(buf), "fp %d status block", i);
14856         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14857                           &fp->sb_dma, buf) != 0) {
14858             /* XXX unwind and free previous fastpath allocations */
14859             BLOGE(sc, "Failed to alloc %s\n", buf);
14860             return (1);
14861         } else {
14862             if (CHIP_IS_E2E3(sc)) {
14863                 fp->status_block.e2_sb =
14864                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14865             } else {
14866                 fp->status_block.e1x_sb =
14867                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14868             }
14869         }
14870 
14871         /******************/
14872         /* FP TX BD CHAIN */
14873         /******************/
14874 
14875         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14876         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14877                           &fp->tx_dma, buf) != 0) {
14878             /* XXX unwind and free previous fastpath allocations */
14879             BLOGE(sc, "Failed to alloc %s\n", buf);
14880             return (1);
14881         } else {
14882             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14883         }
14884 
14885         /* link together the tx bd chain pages */
14886         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14887             /* index into the tx bd chain array to last entry per page */
14888             struct eth_tx_next_bd *tx_next_bd =
14889                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14890             /* point to the next page and wrap from last page */
14891             busaddr = (fp->tx_dma.paddr +
14892                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14893             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14894             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14895         }
14896 
14897         /******************/
14898         /* FP RX BD CHAIN */
14899         /******************/
14900 
14901         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14902         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14903                           &fp->rx_dma, buf) != 0) {
14904             /* XXX unwind and free previous fastpath allocations */
14905             BLOGE(sc, "Failed to alloc %s\n", buf);
14906             return (1);
14907         } else {
14908             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14909         }
14910 
14911         /* link together the rx bd chain pages */
14912         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14913             /* index into the rx bd chain array to last entry per page */
14914             struct eth_rx_bd *rx_bd =
14915                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14916             /* point to the next page and wrap from last page */
14917             busaddr = (fp->rx_dma.paddr +
14918                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14919             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14920             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14921         }
14922 
14923         /*******************/
14924         /* FP RX RCQ CHAIN */
14925         /*******************/
14926 
14927         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14928         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14929                           &fp->rcq_dma, buf) != 0) {
14930             /* XXX unwind and free previous fastpath allocations */
14931             BLOGE(sc, "Failed to alloc %s\n", buf);
14932             return (1);
14933         } else {
14934             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14935         }
14936 
14937         /* link together the rcq chain pages */
14938         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14939             /* index into the rcq chain array to last entry per page */
14940             struct eth_rx_cqe_next_page *rx_cqe_next =
14941                 (struct eth_rx_cqe_next_page *)
14942                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14943             /* point to the next page and wrap from last page */
14944             busaddr = (fp->rcq_dma.paddr +
14945                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14946             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14947             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14948         }
14949 
14950         /*******************/
14951         /* FP RX SGE CHAIN */
14952         /*******************/
14953 
14954         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14955         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14956                           &fp->rx_sge_dma, buf) != 0) {
14957             /* XXX unwind and free previous fastpath allocations */
14958             BLOGE(sc, "Failed to alloc %s\n", buf);
14959             return (1);
14960         } else {
14961             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14962         }
14963 
14964         /* link together the sge chain pages */
14965         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14966             /* index into the rcq chain array to last entry per page */
14967             struct eth_rx_sge *rx_sge =
14968                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14969             /* point to the next page and wrap from last page */
14970             busaddr = (fp->rx_sge_dma.paddr +
14971                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14972             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14973             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14974         }
14975 
14976         /***********************/
14977         /* FP TX MBUF DMA MAPS */
14978         /***********************/
14979 
14980         /* set required sizes before mapping to conserve resources */
14981         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14982             max_size     = BXE_TSO_MAX_SIZE;
14983             max_segments = BXE_TSO_MAX_SEGMENTS;
14984             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14985         } else {
14986             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14987             max_segments = BXE_MAX_SEGMENTS;
14988             max_seg_size = MCLBYTES;
14989         }
14990 
14991         /* create a dma tag for the tx mbufs */
14992         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14993                                 1,                  /* alignment */
14994                                 0,                  /* boundary limit */
14995                                 BUS_SPACE_MAXADDR,  /* restricted low */
14996                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14997                                 NULL,               /* addr filter() */
14998                                 NULL,               /* addr filter() arg */
14999                                 max_size,           /* max map size */
15000                                 max_segments,       /* num discontinuous */
15001                                 max_seg_size,       /* max seg size */
15002                                 0,                  /* flags */
15003                                 NULL,               /* lock() */
15004                                 NULL,               /* lock() arg */
15005                                 &fp->tx_mbuf_tag);  /* returned dma tag */
15006         if (rc != 0) {
15007             /* XXX unwind and free previous fastpath allocations */
15008             BLOGE(sc, "Failed to create dma tag for "
15009                       "'fp %d tx mbufs' (%d)\n", i, rc);
15010             return (1);
15011         }
15012 
15013         /* create dma maps for each of the tx mbuf clusters */
15014         for (j = 0; j < TX_BD_TOTAL; j++) {
15015             if (bus_dmamap_create(fp->tx_mbuf_tag,
15016                                   BUS_DMA_NOWAIT,
15017                                   &fp->tx_mbuf_chain[j].m_map)) {
15018                 /* XXX unwind and free previous fastpath allocations */
15019                 BLOGE(sc, "Failed to create dma map for "
15020                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
15021                 return (1);
15022             }
15023         }
15024 
15025         /***********************/
15026         /* FP RX MBUF DMA MAPS */
15027         /***********************/
15028 
15029         /* create a dma tag for the rx mbufs */
15030         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15031                                 1,                  /* alignment */
15032                                 0,                  /* boundary limit */
15033                                 BUS_SPACE_MAXADDR,  /* restricted low */
15034                                 BUS_SPACE_MAXADDR,  /* restricted hi */
15035                                 NULL,               /* addr filter() */
15036                                 NULL,               /* addr filter() arg */
15037                                 MJUM9BYTES,         /* max map size */
15038                                 1,                  /* num discontinuous */
15039                                 MJUM9BYTES,         /* max seg size */
15040                                 0,                  /* flags */
15041                                 NULL,               /* lock() */
15042                                 NULL,               /* lock() arg */
15043                                 &fp->rx_mbuf_tag);  /* returned dma tag */
15044         if (rc != 0) {
15045             /* XXX unwind and free previous fastpath allocations */
15046             BLOGE(sc, "Failed to create dma tag for "
15047                       "'fp %d rx mbufs' (%d)\n", i, rc);
15048             return (1);
15049         }
15050 
15051         /* create dma maps for each of the rx mbuf clusters */
15052         for (j = 0; j < RX_BD_TOTAL; j++) {
15053             if (bus_dmamap_create(fp->rx_mbuf_tag,
15054                                   BUS_DMA_NOWAIT,
15055                                   &fp->rx_mbuf_chain[j].m_map)) {
15056                 /* XXX unwind and free previous fastpath allocations */
15057                 BLOGE(sc, "Failed to create dma map for "
15058                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
15059                 return (1);
15060             }
15061         }
15062 
15063         /* create dma map for the spare rx mbuf cluster */
15064         if (bus_dmamap_create(fp->rx_mbuf_tag,
15065                               BUS_DMA_NOWAIT,
15066                               &fp->rx_mbuf_spare_map)) {
15067             /* XXX unwind and free previous fastpath allocations */
15068             BLOGE(sc, "Failed to create dma map for "
15069                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
15070             return (1);
15071         }
15072 
15073         /***************************/
15074         /* FP RX SGE MBUF DMA MAPS */
15075         /***************************/
15076 
15077         /* create a dma tag for the rx sge mbufs */
15078         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
15079                                 1,                  /* alignment */
15080                                 0,                  /* boundary limit */
15081                                 BUS_SPACE_MAXADDR,  /* restricted low */
15082                                 BUS_SPACE_MAXADDR,  /* restricted hi */
15083                                 NULL,               /* addr filter() */
15084                                 NULL,               /* addr filter() arg */
15085                                 BCM_PAGE_SIZE,      /* max map size */
15086                                 1,                  /* num discontinuous */
15087                                 BCM_PAGE_SIZE,      /* max seg size */
15088                                 0,                  /* flags */
15089                                 NULL,               /* lock() */
15090                                 NULL,               /* lock() arg */
15091                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
15092         if (rc != 0) {
15093             /* XXX unwind and free previous fastpath allocations */
15094             BLOGE(sc, "Failed to create dma tag for "
15095                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
15096             return (1);
15097         }
15098 
15099         /* create dma maps for the rx sge mbuf clusters */
15100         for (j = 0; j < RX_SGE_TOTAL; j++) {
15101             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15102                                   BUS_DMA_NOWAIT,
15103                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
15104                 /* XXX unwind and free previous fastpath allocations */
15105                 BLOGE(sc, "Failed to create dma map for "
15106                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
15107                 return (1);
15108             }
15109         }
15110 
15111         /* create dma map for the spare rx sge mbuf cluster */
15112         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
15113                               BUS_DMA_NOWAIT,
15114                               &fp->rx_sge_mbuf_spare_map)) {
15115             /* XXX unwind and free previous fastpath allocations */
15116             BLOGE(sc, "Failed to create dma map for "
15117                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
15118             return (1);
15119         }
15120 
15121         /***************************/
15122         /* FP RX TPA MBUF DMA MAPS */
15123         /***************************/
15124 
15125         /* create dma maps for the rx tpa mbuf clusters */
15126         max_agg_queues = MAX_AGG_QS(sc);
15127 
15128         for (j = 0; j < max_agg_queues; j++) {
15129             if (bus_dmamap_create(fp->rx_mbuf_tag,
15130                                   BUS_DMA_NOWAIT,
15131                                   &fp->rx_tpa_info[j].bd.m_map)) {
15132                 /* XXX unwind and free previous fastpath allocations */
15133                 BLOGE(sc, "Failed to create dma map for "
15134                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
15135                 return (1);
15136             }
15137         }
15138 
15139         /* create dma map for the spare rx tpa mbuf cluster */
15140         if (bus_dmamap_create(fp->rx_mbuf_tag,
15141                               BUS_DMA_NOWAIT,
15142                               &fp->rx_tpa_info_mbuf_spare_map)) {
15143             /* XXX unwind and free previous fastpath allocations */
15144             BLOGE(sc, "Failed to create dma map for "
15145                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
15146             return (1);
15147         }
15148 
15149         bxe_init_sge_ring_bit_mask(fp);
15150     }
15151 
15152     return (0);
15153 }
15154 
15155 static void
15156 bxe_free_hsi_mem(struct bxe_softc *sc)
15157 {
15158     struct bxe_fastpath *fp;
15159     int max_agg_queues;
15160     int i, j;
15161 
15162     if (sc->parent_dma_tag == NULL) {
15163         return; /* assume nothing was allocated */
15164     }
15165 
15166     for (i = 0; i < sc->num_queues; i++) {
15167         fp = &sc->fp[i];
15168 
15169         /*******************/
15170         /* FP STATUS BLOCK */
15171         /*******************/
15172 
15173         bxe_dma_free(sc, &fp->sb_dma);
15174         memset(&fp->status_block, 0, sizeof(fp->status_block));
15175 
15176         /******************/
15177         /* FP TX BD CHAIN */
15178         /******************/
15179 
15180         bxe_dma_free(sc, &fp->tx_dma);
15181         fp->tx_chain = NULL;
15182 
15183         /******************/
15184         /* FP RX BD CHAIN */
15185         /******************/
15186 
15187         bxe_dma_free(sc, &fp->rx_dma);
15188         fp->rx_chain = NULL;
15189 
15190         /*******************/
15191         /* FP RX RCQ CHAIN */
15192         /*******************/
15193 
15194         bxe_dma_free(sc, &fp->rcq_dma);
15195         fp->rcq_chain = NULL;
15196 
15197         /*******************/
15198         /* FP RX SGE CHAIN */
15199         /*******************/
15200 
15201         bxe_dma_free(sc, &fp->rx_sge_dma);
15202         fp->rx_sge_chain = NULL;
15203 
15204         /***********************/
15205         /* FP TX MBUF DMA MAPS */
15206         /***********************/
15207 
15208         if (fp->tx_mbuf_tag != NULL) {
15209             for (j = 0; j < TX_BD_TOTAL; j++) {
15210                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
15211                     bus_dmamap_unload(fp->tx_mbuf_tag,
15212                                       fp->tx_mbuf_chain[j].m_map);
15213                     bus_dmamap_destroy(fp->tx_mbuf_tag,
15214                                        fp->tx_mbuf_chain[j].m_map);
15215                 }
15216             }
15217 
15218             bus_dma_tag_destroy(fp->tx_mbuf_tag);
15219             fp->tx_mbuf_tag = NULL;
15220         }
15221 
15222         /***********************/
15223         /* FP RX MBUF DMA MAPS */
15224         /***********************/
15225 
15226         if (fp->rx_mbuf_tag != NULL) {
15227             for (j = 0; j < RX_BD_TOTAL; j++) {
15228                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
15229                     bus_dmamap_unload(fp->rx_mbuf_tag,
15230                                       fp->rx_mbuf_chain[j].m_map);
15231                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15232                                        fp->rx_mbuf_chain[j].m_map);
15233                 }
15234             }
15235 
15236             if (fp->rx_mbuf_spare_map != NULL) {
15237                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15238                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
15239             }
15240 
15241             /***************************/
15242             /* FP RX TPA MBUF DMA MAPS */
15243             /***************************/
15244 
15245             max_agg_queues = MAX_AGG_QS(sc);
15246 
15247             for (j = 0; j < max_agg_queues; j++) {
15248                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
15249                     bus_dmamap_unload(fp->rx_mbuf_tag,
15250                                       fp->rx_tpa_info[j].bd.m_map);
15251                     bus_dmamap_destroy(fp->rx_mbuf_tag,
15252                                        fp->rx_tpa_info[j].bd.m_map);
15253                 }
15254             }
15255 
15256             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
15257                 bus_dmamap_unload(fp->rx_mbuf_tag,
15258                                   fp->rx_tpa_info_mbuf_spare_map);
15259                 bus_dmamap_destroy(fp->rx_mbuf_tag,
15260                                    fp->rx_tpa_info_mbuf_spare_map);
15261             }
15262 
15263             bus_dma_tag_destroy(fp->rx_mbuf_tag);
15264             fp->rx_mbuf_tag = NULL;
15265         }
15266 
15267         /***************************/
15268         /* FP RX SGE MBUF DMA MAPS */
15269         /***************************/
15270 
15271         if (fp->rx_sge_mbuf_tag != NULL) {
15272             for (j = 0; j < RX_SGE_TOTAL; j++) {
15273                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
15274                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15275                                       fp->rx_sge_mbuf_chain[j].m_map);
15276                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15277                                        fp->rx_sge_mbuf_chain[j].m_map);
15278                 }
15279             }
15280 
15281             if (fp->rx_sge_mbuf_spare_map != NULL) {
15282                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
15283                                   fp->rx_sge_mbuf_spare_map);
15284                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
15285                                    fp->rx_sge_mbuf_spare_map);
15286             }
15287 
15288             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
15289             fp->rx_sge_mbuf_tag = NULL;
15290         }
15291     }
15292 
15293     /***************************/
15294     /* FW DECOMPRESSION BUFFER */
15295     /***************************/
15296 
15297     bxe_dma_free(sc, &sc->gz_buf_dma);
15298     sc->gz_buf = NULL;
15299     free(sc->gz_strm, M_DEVBUF);
15300     sc->gz_strm = NULL;
15301 
15302     /*******************/
15303     /* SLOW PATH QUEUE */
15304     /*******************/
15305 
15306     bxe_dma_free(sc, &sc->spq_dma);
15307     sc->spq = NULL;
15308 
15309     /*************/
15310     /* SLOW PATH */
15311     /*************/
15312 
15313     bxe_dma_free(sc, &sc->sp_dma);
15314     sc->sp = NULL;
15315 
15316     /***************/
15317     /* EVENT QUEUE */
15318     /***************/
15319 
15320     bxe_dma_free(sc, &sc->eq_dma);
15321     sc->eq = NULL;
15322 
15323     /************************/
15324     /* DEFAULT STATUS BLOCK */
15325     /************************/
15326 
15327     bxe_dma_free(sc, &sc->def_sb_dma);
15328     sc->def_sb = NULL;
15329 
15330     bus_dma_tag_destroy(sc->parent_dma_tag);
15331     sc->parent_dma_tag = NULL;
15332 }
15333 
15334 /*
15335  * Previous driver DMAE transaction may have occurred when pre-boot stage
15336  * ended and boot began. This would invalidate the addresses of the
15337  * transaction, resulting in was-error bit set in the PCI causing all
15338  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15339  * the interrupt which detected this from the pglueb and the was-done bit
15340  */
15341 static void
15342 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15343 {
15344     uint32_t val;
15345 
15346     if (!CHIP_IS_E1x(sc)) {
15347         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15348         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15349             BLOGD(sc, DBG_LOAD,
15350                   "Clearing 'was-error' bit that was set in pglueb");
15351             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15352         }
15353     }
15354 }
15355 
15356 static int
15357 bxe_prev_mcp_done(struct bxe_softc *sc)
15358 {
15359     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15360                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15361     if (!rc) {
15362         BLOGE(sc, "MCP response failure, aborting\n");
15363         return (-1);
15364     }
15365 
15366     return (0);
15367 }
15368 
15369 static struct bxe_prev_list_node *
15370 bxe_prev_path_get_entry(struct bxe_softc *sc)
15371 {
15372     struct bxe_prev_list_node *tmp;
15373 
15374     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15375         if ((sc->pcie_bus == tmp->bus) &&
15376             (sc->pcie_device == tmp->slot) &&
15377             (SC_PATH(sc) == tmp->path)) {
15378             return (tmp);
15379         }
15380     }
15381 
15382     return (NULL);
15383 }
15384 
15385 static uint8_t
15386 bxe_prev_is_path_marked(struct bxe_softc *sc)
15387 {
15388     struct bxe_prev_list_node *tmp;
15389     int rc = FALSE;
15390 
15391     mtx_lock(&bxe_prev_mtx);
15392 
15393     tmp = bxe_prev_path_get_entry(sc);
15394     if (tmp) {
15395         if (tmp->aer) {
15396             BLOGD(sc, DBG_LOAD,
15397                   "Path %d/%d/%d was marked by AER\n",
15398                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15399         } else {
15400             rc = TRUE;
15401             BLOGD(sc, DBG_LOAD,
15402                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15403                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15404         }
15405     }
15406 
15407     mtx_unlock(&bxe_prev_mtx);
15408 
15409     return (rc);
15410 }
15411 
15412 static int
15413 bxe_prev_mark_path(struct bxe_softc *sc,
15414                    uint8_t          after_undi)
15415 {
15416     struct bxe_prev_list_node *tmp;
15417 
15418     mtx_lock(&bxe_prev_mtx);
15419 
15420     /* Check whether the entry for this path already exists */
15421     tmp = bxe_prev_path_get_entry(sc);
15422     if (tmp) {
15423         if (!tmp->aer) {
15424             BLOGD(sc, DBG_LOAD,
15425                   "Re-marking AER in path %d/%d/%d\n",
15426                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15427         } else {
15428             BLOGD(sc, DBG_LOAD,
15429                   "Removing AER indication from path %d/%d/%d\n",
15430                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15431             tmp->aer = 0;
15432         }
15433 
15434         mtx_unlock(&bxe_prev_mtx);
15435         return (0);
15436     }
15437 
15438     mtx_unlock(&bxe_prev_mtx);
15439 
15440     /* Create an entry for this path and add it */
15441     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15442                  (M_NOWAIT | M_ZERO));
15443     if (!tmp) {
15444         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15445         return (-1);
15446     }
15447 
15448     tmp->bus  = sc->pcie_bus;
15449     tmp->slot = sc->pcie_device;
15450     tmp->path = SC_PATH(sc);
15451     tmp->aer  = 0;
15452     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15453 
15454     mtx_lock(&bxe_prev_mtx);
15455 
15456     BLOGD(sc, DBG_LOAD,
15457           "Marked path %d/%d/%d - finished previous unload\n",
15458           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15459     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15460 
15461     mtx_unlock(&bxe_prev_mtx);
15462 
15463     return (0);
15464 }
15465 
15466 static int
15467 bxe_do_flr(struct bxe_softc *sc)
15468 {
15469     int i;
15470 
15471     /* only E2 and onwards support FLR */
15472     if (CHIP_IS_E1x(sc)) {
15473         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15474         return (-1);
15475     }
15476 
15477     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15478     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15479         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15480               sc->devinfo.bc_ver);
15481         return (-1);
15482     }
15483 
15484     /* Wait for Transaction Pending bit clean */
15485     for (i = 0; i < 4; i++) {
15486         if (i) {
15487             DELAY(((1 << (i - 1)) * 100) * 1000);
15488         }
15489 
15490         if (!bxe_is_pcie_pending(sc)) {
15491             goto clear;
15492         }
15493     }
15494 
15495     BLOGE(sc, "PCIE transaction is not cleared, "
15496               "proceeding with reset anyway\n");
15497 
15498 clear:
15499 
15500     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15501     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15502 
15503     return (0);
15504 }
15505 
15506 struct bxe_mac_vals {
15507     uint32_t xmac_addr;
15508     uint32_t xmac_val;
15509     uint32_t emac_addr;
15510     uint32_t emac_val;
15511     uint32_t umac_addr;
15512     uint32_t umac_val;
15513     uint32_t bmac_addr;
15514     uint32_t bmac_val[2];
15515 };
15516 
15517 static void
15518 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15519                           struct bxe_mac_vals *vals)
15520 {
15521     uint32_t val, base_addr, offset, mask, reset_reg;
15522     uint8_t mac_stopped = FALSE;
15523     uint8_t port = SC_PORT(sc);
15524     uint32_t wb_data[2];
15525 
15526     /* reset addresses as they also mark which values were changed */
15527     vals->bmac_addr = 0;
15528     vals->umac_addr = 0;
15529     vals->xmac_addr = 0;
15530     vals->emac_addr = 0;
15531 
15532     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15533 
15534     if (!CHIP_IS_E3(sc)) {
15535         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15536         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15537         if ((mask & reset_reg) && val) {
15538             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15539             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15540                                     : NIG_REG_INGRESS_BMAC0_MEM;
15541             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15542                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15543 
15544             /*
15545              * use rd/wr since we cannot use dmae. This is safe
15546              * since MCP won't access the bus due to the request
15547              * to unload, and no function on the path can be
15548              * loaded at this time.
15549              */
15550             wb_data[0] = REG_RD(sc, base_addr + offset);
15551             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15552             vals->bmac_addr = base_addr + offset;
15553             vals->bmac_val[0] = wb_data[0];
15554             vals->bmac_val[1] = wb_data[1];
15555             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15556             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15557             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15558         }
15559 
15560         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15561         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15562         vals->emac_val = REG_RD(sc, vals->emac_addr);
15563         REG_WR(sc, vals->emac_addr, 0);
15564         mac_stopped = TRUE;
15565     } else {
15566         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15567             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15568             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15569             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15570             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15571             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15572             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15573             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15574             REG_WR(sc, vals->xmac_addr, 0);
15575             mac_stopped = TRUE;
15576         }
15577 
15578         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15579         if (mask & reset_reg) {
15580             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15581             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15582             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15583             vals->umac_val = REG_RD(sc, vals->umac_addr);
15584             REG_WR(sc, vals->umac_addr, 0);
15585             mac_stopped = TRUE;
15586         }
15587     }
15588 
15589     if (mac_stopped) {
15590         DELAY(20000);
15591     }
15592 }
15593 
15594 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15595 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15596 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15597 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15598 
15599 static void
15600 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15601                          uint8_t          port,
15602                          uint8_t          inc)
15603 {
15604     uint16_t rcq, bd;
15605     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15606 
15607     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15608     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15609 
15610     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15611     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15612 
15613     BLOGD(sc, DBG_LOAD,
15614           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15615           port, bd, rcq);
15616 }
15617 
15618 static int
15619 bxe_prev_unload_common(struct bxe_softc *sc)
15620 {
15621     uint32_t reset_reg, tmp_reg = 0, rc;
15622     uint8_t prev_undi = FALSE;
15623     struct bxe_mac_vals mac_vals;
15624     uint32_t timer_count = 1000;
15625     uint32_t prev_brb;
15626 
15627     /*
15628      * It is possible a previous function received 'common' answer,
15629      * but hasn't loaded yet, therefore creating a scenario of
15630      * multiple functions receiving 'common' on the same path.
15631      */
15632     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15633 
15634     memset(&mac_vals, 0, sizeof(mac_vals));
15635 
15636     if (bxe_prev_is_path_marked(sc)) {
15637         return (bxe_prev_mcp_done(sc));
15638     }
15639 
15640     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15641 
15642     /* Reset should be performed after BRB is emptied */
15643     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15644         /* Close the MAC Rx to prevent BRB from filling up */
15645         bxe_prev_unload_close_mac(sc, &mac_vals);
15646 
15647         /* close LLH filters towards the BRB */
15648         elink_set_rx_filter(&sc->link_params, 0);
15649 
15650         /*
15651          * Check if the UNDI driver was previously loaded.
15652          * UNDI driver initializes CID offset for normal bell to 0x7
15653          */
15654         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15655             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15656             if (tmp_reg == 0x7) {
15657                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15658                 prev_undi = TRUE;
15659                 /* clear the UNDI indication */
15660                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15661                 /* clear possible idle check errors */
15662                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15663             }
15664         }
15665 
15666         /* wait until BRB is empty */
15667         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15668         while (timer_count) {
15669             prev_brb = tmp_reg;
15670 
15671             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15672             if (!tmp_reg) {
15673                 break;
15674             }
15675 
15676             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15677 
15678             /* reset timer as long as BRB actually gets emptied */
15679             if (prev_brb > tmp_reg) {
15680                 timer_count = 1000;
15681             } else {
15682                 timer_count--;
15683             }
15684 
15685             /* If UNDI resides in memory, manually increment it */
15686             if (prev_undi) {
15687                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15688             }
15689 
15690             DELAY(10);
15691         }
15692 
15693         if (!timer_count) {
15694             BLOGE(sc, "Failed to empty BRB\n");
15695         }
15696     }
15697 
15698     /* No packets are in the pipeline, path is ready for reset */
15699     bxe_reset_common(sc);
15700 
15701     if (mac_vals.xmac_addr) {
15702         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15703     }
15704     if (mac_vals.umac_addr) {
15705         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15706     }
15707     if (mac_vals.emac_addr) {
15708         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15709     }
15710     if (mac_vals.bmac_addr) {
15711         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15712         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15713     }
15714 
15715     rc = bxe_prev_mark_path(sc, prev_undi);
15716     if (rc) {
15717         bxe_prev_mcp_done(sc);
15718         return (rc);
15719     }
15720 
15721     return (bxe_prev_mcp_done(sc));
15722 }
15723 
15724 static int
15725 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15726 {
15727     int rc;
15728 
15729     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15730 
15731     /* Test if previous unload process was already finished for this path */
15732     if (bxe_prev_is_path_marked(sc)) {
15733         return (bxe_prev_mcp_done(sc));
15734     }
15735 
15736     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15737 
15738     /*
15739      * If function has FLR capabilities, and existing FW version matches
15740      * the one required, then FLR will be sufficient to clean any residue
15741      * left by previous driver
15742      */
15743     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15744     if (!rc) {
15745         /* fw version is good */
15746         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15747         rc = bxe_do_flr(sc);
15748     }
15749 
15750     if (!rc) {
15751         /* FLR was performed */
15752         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15753         return (0);
15754     }
15755 
15756     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15757 
15758     /* Close the MCP request, return failure*/
15759     rc = bxe_prev_mcp_done(sc);
15760     if (!rc) {
15761         rc = BXE_PREV_WAIT_NEEDED;
15762     }
15763 
15764     return (rc);
15765 }
15766 
15767 static int
15768 bxe_prev_unload(struct bxe_softc *sc)
15769 {
15770     int time_counter = 10;
15771     uint32_t fw, hw_lock_reg, hw_lock_val;
15772     uint32_t rc = 0;
15773 
15774     /*
15775      * Clear HW from errors which may have resulted from an interrupted
15776      * DMAE transaction.
15777      */
15778     bxe_prev_interrupted_dmae(sc);
15779 
15780     /* Release previously held locks */
15781     hw_lock_reg =
15782         (SC_FUNC(sc) <= 5) ?
15783             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15784             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15785 
15786     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15787     if (hw_lock_val) {
15788         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15789             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15790             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15791                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15792         }
15793         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15794         REG_WR(sc, hw_lock_reg, 0xffffffff);
15795     } else {
15796         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15797     }
15798 
15799     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15800         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15801         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15802     }
15803 
15804     do {
15805         /* Lock MCP using an unload request */
15806         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15807         if (!fw) {
15808             BLOGE(sc, "MCP response failure, aborting\n");
15809             rc = -1;
15810             break;
15811         }
15812 
15813         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15814             rc = bxe_prev_unload_common(sc);
15815             break;
15816         }
15817 
15818         /* non-common reply from MCP night require looping */
15819         rc = bxe_prev_unload_uncommon(sc);
15820         if (rc != BXE_PREV_WAIT_NEEDED) {
15821             break;
15822         }
15823 
15824         DELAY(20000);
15825     } while (--time_counter);
15826 
15827     if (!time_counter || rc) {
15828         BLOGE(sc, "Failed to unload previous driver!"
15829             " time_counter %d rc %d\n", time_counter, rc);
15830         rc = -1;
15831     }
15832 
15833     return (rc);
15834 }
15835 
15836 void
15837 bxe_dcbx_set_state(struct bxe_softc *sc,
15838                    uint8_t          dcb_on,
15839                    uint32_t         dcbx_enabled)
15840 {
15841     if (!CHIP_IS_E1x(sc)) {
15842         sc->dcb_state = dcb_on;
15843         sc->dcbx_enabled = dcbx_enabled;
15844     } else {
15845         sc->dcb_state = FALSE;
15846         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15847     }
15848     BLOGD(sc, DBG_LOAD,
15849           "DCB state [%s:%s]\n",
15850           dcb_on ? "ON" : "OFF",
15851           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15852           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15853           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15854           "on-chip with negotiation" : "invalid");
15855 }
15856 
15857 /* must be called after sriov-enable */
15858 static int
15859 bxe_set_qm_cid_count(struct bxe_softc *sc)
15860 {
15861     int cid_count = BXE_L2_MAX_CID(sc);
15862 
15863     if (IS_SRIOV(sc)) {
15864         cid_count += BXE_VF_CIDS;
15865     }
15866 
15867     if (CNIC_SUPPORT(sc)) {
15868         cid_count += CNIC_CID_MAX;
15869     }
15870 
15871     return (roundup(cid_count, QM_CID_ROUND));
15872 }
15873 
15874 static void
15875 bxe_init_multi_cos(struct bxe_softc *sc)
15876 {
15877     int pri, cos;
15878 
15879     uint32_t pri_map = 0; /* XXX change to user config */
15880 
15881     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15882         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15883         if (cos < sc->max_cos) {
15884             sc->prio_to_cos[pri] = cos;
15885         } else {
15886             BLOGW(sc, "Invalid COS %d for priority %d "
15887                       "(max COS is %d), setting to 0\n",
15888                   cos, pri, (sc->max_cos - 1));
15889             sc->prio_to_cos[pri] = 0;
15890         }
15891     }
15892 }
15893 
15894 static int
15895 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15896 {
15897     struct bxe_softc *sc;
15898     int error, result;
15899 
15900     result = 0;
15901     error = sysctl_handle_int(oidp, &result, 0, req);
15902 
15903     if (error || !req->newptr) {
15904         return (error);
15905     }
15906 
15907     if (result == 1) {
15908         uint32_t  temp;
15909         sc = (struct bxe_softc *)arg1;
15910 
15911         BLOGI(sc, "... dumping driver state ...\n");
15912         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15913         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15914     }
15915 
15916     return (error);
15917 }
15918 
15919 static int
15920 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15921 {
15922     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15923     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15924     uint32_t *offset;
15925     uint64_t value = 0;
15926     int index = (int)arg2;
15927 
15928     if (index >= BXE_NUM_ETH_STATS) {
15929         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15930         return (-1);
15931     }
15932 
15933     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15934 
15935     switch (bxe_eth_stats_arr[index].size) {
15936     case 4:
15937         value = (uint64_t)*offset;
15938         break;
15939     case 8:
15940         value = HILO_U64(*offset, *(offset + 1));
15941         break;
15942     default:
15943         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15944               index, bxe_eth_stats_arr[index].size);
15945         return (-1);
15946     }
15947 
15948     return (sysctl_handle_64(oidp, &value, 0, req));
15949 }
15950 
15951 static int
15952 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15953 {
15954     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15955     uint32_t *eth_stats;
15956     uint32_t *offset;
15957     uint64_t value = 0;
15958     uint32_t q_stat = (uint32_t)arg2;
15959     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15960     uint32_t index = (q_stat & 0xffff);
15961 
15962     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15963 
15964     if (index >= BXE_NUM_ETH_Q_STATS) {
15965         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15966         return (-1);
15967     }
15968 
15969     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15970 
15971     switch (bxe_eth_q_stats_arr[index].size) {
15972     case 4:
15973         value = (uint64_t)*offset;
15974         break;
15975     case 8:
15976         value = HILO_U64(*offset, *(offset + 1));
15977         break;
15978     default:
15979         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15980               index, bxe_eth_q_stats_arr[index].size);
15981         return (-1);
15982     }
15983 
15984     return (sysctl_handle_64(oidp, &value, 0, req));
15985 }
15986 
15987 static void bxe_force_link_reset(struct bxe_softc *sc)
15988 {
15989 
15990         bxe_acquire_phy_lock(sc);
15991         elink_link_reset(&sc->link_params, &sc->link_vars, 1);
15992         bxe_release_phy_lock(sc);
15993 }
15994 
15995 static int
15996 bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
15997 {
15998         struct bxe_softc *sc = (struct bxe_softc *)arg1;;
15999         uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
16000         int rc = 0;
16001         int error;
16002         int result;
16003 
16004 
16005         error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
16006 
16007         if (error || !req->newptr) {
16008                 return (error);
16009         }
16010         if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
16011                 BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
16012                 sc->bxe_pause_param = 8;
16013         }
16014 
16015         result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
16016 
16017 
16018         if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
16019                         BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
16020                         return -EINVAL;
16021         }
16022 
16023         if(IS_MF(sc))
16024                 return 0;
16025        sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
16026         if(result & ELINK_FLOW_CTRL_RX)
16027                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
16028 
16029         if(result & ELINK_FLOW_CTRL_TX)
16030                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
16031         if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
16032                 sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
16033 
16034         if(result & 0x400) {
16035                 if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
16036                         sc->link_params.req_flow_ctrl[cfg_idx] =
16037                                 ELINK_FLOW_CTRL_AUTO;
16038                 }
16039                 sc->link_params.req_fc_auto_adv = 0;
16040                 if (result & ELINK_FLOW_CTRL_RX)
16041                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
16042 
16043                 if (result & ELINK_FLOW_CTRL_TX)
16044                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
16045                 if (!sc->link_params.req_fc_auto_adv)
16046                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
16047         }
16048          if (IS_PF(sc)) {
16049                         if (sc->link_vars.link_up) {
16050                                 bxe_stats_handle(sc, STATS_EVENT_STOP);
16051                         }
16052 			if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
16053                         bxe_force_link_reset(sc);
16054                         bxe_acquire_phy_lock(sc);
16055 
16056                         rc = elink_phy_init(&sc->link_params, &sc->link_vars);
16057 
16058                         bxe_release_phy_lock(sc);
16059 
16060                         bxe_calc_fc_adv(sc);
16061                         }
16062         }
16063         return rc;
16064 }
16065 
16066 
16067 static void
16068 bxe_add_sysctls(struct bxe_softc *sc)
16069 {
16070     struct sysctl_ctx_list *ctx;
16071     struct sysctl_oid_list *children;
16072     struct sysctl_oid *queue_top, *queue;
16073     struct sysctl_oid_list *queue_top_children, *queue_children;
16074     char queue_num_buf[32];
16075     uint32_t q_stat;
16076     int i, j;
16077 
16078     ctx = device_get_sysctl_ctx(sc->dev);
16079     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
16080 
16081     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
16082                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
16083                       "version");
16084 
16085     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
16086              BCM_5710_FW_MAJOR_VERSION,
16087              BCM_5710_FW_MINOR_VERSION,
16088              BCM_5710_FW_REVISION_VERSION,
16089              BCM_5710_FW_ENGINEERING_VERSION);
16090 
16091     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
16092         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
16093          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
16094          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
16095          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
16096                                                                 "Unknown"));
16097     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
16098                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
16099                     "multifunction vnics per port");
16100 
16101     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
16102         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
16103          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
16104          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
16105                                               "???GT/s"),
16106         sc->devinfo.pcie_link_width);
16107 
16108     sc->debug = bxe_debug;
16109 
16110 #if __FreeBSD_version >= 900000
16111     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16112                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
16113                       "bootcode version");
16114     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16115                       CTLFLAG_RD, sc->fw_ver_str, 0,
16116                       "firmware version");
16117     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16118                       CTLFLAG_RD, sc->mf_mode_str, 0,
16119                       "multifunction mode");
16120     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16121                       CTLFLAG_RD, sc->mac_addr_str, 0,
16122                       "mac address");
16123     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16124                       CTLFLAG_RD, sc->pci_link_str, 0,
16125                       "pci link status");
16126     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
16127                     CTLFLAG_RW, &sc->debug,
16128                     "debug logging mode");
16129 #else
16130     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
16131                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
16132                       "bootcode version");
16133     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
16134                       CTLFLAG_RD, &sc->fw_ver_str, 0,
16135                       "firmware version");
16136     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
16137                       CTLFLAG_RD, &sc->mf_mode_str, 0,
16138                       "multifunction mode");
16139     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
16140                       CTLFLAG_RD, &sc->mac_addr_str, 0,
16141                       "mac address");
16142     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
16143                       CTLFLAG_RD, &sc->pci_link_str, 0,
16144                       "pci link status");
16145     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
16146                     CTLFLAG_RW, &sc->debug, 0,
16147                     "debug logging mode");
16148 #endif /* #if __FreeBSD_version >= 900000 */
16149 
16150     sc->trigger_grcdump = 0;
16151     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
16152                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
16153                    "trigger grcdump should be invoked"
16154                    "  before collecting grcdump");
16155 
16156     sc->grcdump_started = 0;
16157     sc->grcdump_done = 0;
16158     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
16159                    CTLFLAG_RD, &sc->grcdump_done, 0,
16160                    "set by driver when grcdump is done");
16161 
16162     sc->rx_budget = bxe_rx_budget;
16163     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
16164                     CTLFLAG_RW, &sc->rx_budget, 0,
16165                     "rx processing budget");
16166 
16167     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
16168         CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, sc, 0,
16169         bxe_sysctl_pauseparam, "IU",
16170         "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
16171 
16172 
16173     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
16174         CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, sc, 0,
16175         bxe_sysctl_state, "IU", "dump driver state");
16176 
16177     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
16178         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
16179             bxe_eth_stats_arr[i].string,
16180             CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_NEEDGIANT, sc, i,
16181             bxe_sysctl_eth_stat, "LU", bxe_eth_stats_arr[i].string);
16182     }
16183 
16184     /* add a new parent node for all queues "dev.bxe.#.queue" */
16185     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
16186         CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "queue");
16187     queue_top_children = SYSCTL_CHILDREN(queue_top);
16188 
16189     for (i = 0; i < sc->num_queues; i++) {
16190         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
16191         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
16192         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
16193             queue_num_buf, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "single queue");
16194         queue_children = SYSCTL_CHILDREN(queue);
16195 
16196         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
16197             q_stat = ((i << 16) | j);
16198             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
16199                  bxe_eth_q_stats_arr[j].string,
16200                  CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_NEEDGIANT, sc, q_stat,
16201                  bxe_sysctl_eth_q_stat, "LU", bxe_eth_q_stats_arr[j].string);
16202         }
16203     }
16204 }
16205 
16206 static int
16207 bxe_alloc_buf_rings(struct bxe_softc *sc)
16208 {
16209 #if __FreeBSD_version >= 901504
16210 
16211     int i;
16212     struct bxe_fastpath *fp;
16213 
16214     for (i = 0; i < sc->num_queues; i++) {
16215 
16216         fp = &sc->fp[i];
16217 
16218         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
16219                                    M_NOWAIT, &fp->tx_mtx);
16220         if (fp->tx_br == NULL)
16221             return (-1);
16222     }
16223 #endif
16224     return (0);
16225 }
16226 
16227 static void
16228 bxe_free_buf_rings(struct bxe_softc *sc)
16229 {
16230 #if __FreeBSD_version >= 901504
16231 
16232     int i;
16233     struct bxe_fastpath *fp;
16234 
16235     for (i = 0; i < sc->num_queues; i++) {
16236 
16237         fp = &sc->fp[i];
16238 
16239         if (fp->tx_br) {
16240             buf_ring_free(fp->tx_br, M_DEVBUF);
16241             fp->tx_br = NULL;
16242         }
16243     }
16244 
16245 #endif
16246 }
16247 
16248 static void
16249 bxe_init_fp_mutexs(struct bxe_softc *sc)
16250 {
16251     int i;
16252     struct bxe_fastpath *fp;
16253 
16254     for (i = 0; i < sc->num_queues; i++) {
16255 
16256         fp = &sc->fp[i];
16257 
16258         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
16259             "bxe%d_fp%d_tx_lock", sc->unit, i);
16260         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
16261 
16262         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
16263             "bxe%d_fp%d_rx_lock", sc->unit, i);
16264         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
16265     }
16266 }
16267 
16268 static void
16269 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
16270 {
16271     int i;
16272     struct bxe_fastpath *fp;
16273 
16274     for (i = 0; i < sc->num_queues; i++) {
16275 
16276         fp = &sc->fp[i];
16277 
16278         if (mtx_initialized(&fp->tx_mtx)) {
16279             mtx_destroy(&fp->tx_mtx);
16280         }
16281 
16282         if (mtx_initialized(&fp->rx_mtx)) {
16283             mtx_destroy(&fp->rx_mtx);
16284         }
16285     }
16286 }
16287 
16288 
16289 /*
16290  * Device attach function.
16291  *
16292  * Allocates device resources, performs secondary chip identification, and
16293  * initializes driver instance variables. This function is called from driver
16294  * load after a successful probe.
16295  *
16296  * Returns:
16297  *   0 = Success, >0 = Failure
16298  */
16299 static int
16300 bxe_attach(device_t dev)
16301 {
16302     struct bxe_softc *sc;
16303 
16304     sc = device_get_softc(dev);
16305 
16306     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
16307 
16308     sc->state = BXE_STATE_CLOSED;
16309 
16310     sc->dev  = dev;
16311     sc->unit = device_get_unit(dev);
16312 
16313     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
16314 
16315     sc->pcie_bus    = pci_get_bus(dev);
16316     sc->pcie_device = pci_get_slot(dev);
16317     sc->pcie_func   = pci_get_function(dev);
16318 
16319     /* enable bus master capability */
16320     pci_enable_busmaster(dev);
16321 
16322     /* get the BARs */
16323     if (bxe_allocate_bars(sc) != 0) {
16324         return (ENXIO);
16325     }
16326 
16327     /* initialize the mutexes */
16328     bxe_init_mutexes(sc);
16329 
16330     /* prepare the periodic callout */
16331     callout_init(&sc->periodic_callout, 0);
16332 
16333     /* prepare the chip taskqueue */
16334     sc->chip_tq_flags = CHIP_TQ_NONE;
16335     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16336              "bxe%d_chip_tq", sc->unit);
16337     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16338     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16339                                    taskqueue_thread_enqueue,
16340                                    &sc->chip_tq);
16341     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16342                             "%s", sc->chip_tq_name);
16343 
16344     TIMEOUT_TASK_INIT(taskqueue_thread,
16345         &sc->sp_err_timeout_task, 0, bxe_sp_err_timeout_task,  sc);
16346 
16347 
16348     /* get device info and set params */
16349     if (bxe_get_device_info(sc) != 0) {
16350         BLOGE(sc, "getting device info\n");
16351         bxe_deallocate_bars(sc);
16352         pci_disable_busmaster(dev);
16353         return (ENXIO);
16354     }
16355 
16356     /* get final misc params */
16357     bxe_get_params(sc);
16358 
16359     /* set the default MTU (changed via ifconfig) */
16360     sc->mtu = ETHERMTU;
16361 
16362     bxe_set_modes_bitmap(sc);
16363 
16364     /* XXX
16365      * If in AFEX mode and the function is configured for FCoE
16366      * then bail... no L2 allowed.
16367      */
16368 
16369     /* get phy settings from shmem and 'and' against admin settings */
16370     bxe_get_phy_info(sc);
16371 
16372     /* initialize the FreeBSD ifnet interface */
16373     if (bxe_init_ifnet(sc) != 0) {
16374         bxe_release_mutexes(sc);
16375         bxe_deallocate_bars(sc);
16376         pci_disable_busmaster(dev);
16377         return (ENXIO);
16378     }
16379 
16380     if (bxe_add_cdev(sc) != 0) {
16381         if (sc->ifp != NULL) {
16382             ether_ifdetach(sc->ifp);
16383         }
16384         ifmedia_removeall(&sc->ifmedia);
16385         bxe_release_mutexes(sc);
16386         bxe_deallocate_bars(sc);
16387         pci_disable_busmaster(dev);
16388         return (ENXIO);
16389     }
16390 
16391     /* allocate device interrupts */
16392     if (bxe_interrupt_alloc(sc) != 0) {
16393         bxe_del_cdev(sc);
16394         if (sc->ifp != NULL) {
16395             ether_ifdetach(sc->ifp);
16396         }
16397         ifmedia_removeall(&sc->ifmedia);
16398         bxe_release_mutexes(sc);
16399         bxe_deallocate_bars(sc);
16400         pci_disable_busmaster(dev);
16401         return (ENXIO);
16402     }
16403 
16404     bxe_init_fp_mutexs(sc);
16405 
16406     if (bxe_alloc_buf_rings(sc) != 0) {
16407 	bxe_free_buf_rings(sc);
16408         bxe_interrupt_free(sc);
16409         bxe_del_cdev(sc);
16410         if (sc->ifp != NULL) {
16411             ether_ifdetach(sc->ifp);
16412         }
16413         ifmedia_removeall(&sc->ifmedia);
16414         bxe_release_mutexes(sc);
16415         bxe_deallocate_bars(sc);
16416         pci_disable_busmaster(dev);
16417         return (ENXIO);
16418     }
16419 
16420     /* allocate ilt */
16421     if (bxe_alloc_ilt_mem(sc) != 0) {
16422 	bxe_free_buf_rings(sc);
16423         bxe_interrupt_free(sc);
16424         bxe_del_cdev(sc);
16425         if (sc->ifp != NULL) {
16426             ether_ifdetach(sc->ifp);
16427         }
16428         ifmedia_removeall(&sc->ifmedia);
16429         bxe_release_mutexes(sc);
16430         bxe_deallocate_bars(sc);
16431         pci_disable_busmaster(dev);
16432         return (ENXIO);
16433     }
16434 
16435     /* allocate the host hardware/software hsi structures */
16436     if (bxe_alloc_hsi_mem(sc) != 0) {
16437         bxe_free_ilt_mem(sc);
16438 	bxe_free_buf_rings(sc);
16439         bxe_interrupt_free(sc);
16440         bxe_del_cdev(sc);
16441         if (sc->ifp != NULL) {
16442             ether_ifdetach(sc->ifp);
16443         }
16444         ifmedia_removeall(&sc->ifmedia);
16445         bxe_release_mutexes(sc);
16446         bxe_deallocate_bars(sc);
16447         pci_disable_busmaster(dev);
16448         return (ENXIO);
16449     }
16450 
16451     /* need to reset chip if UNDI was active */
16452     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16453         /* init fw_seq */
16454         sc->fw_seq =
16455             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16456              DRV_MSG_SEQ_NUMBER_MASK);
16457         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16458         bxe_prev_unload(sc);
16459     }
16460 
16461 #if 1
16462     /* XXX */
16463     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16464 #else
16465     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16466         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16467         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16468         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16469         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16470         bxe_dcbx_init_params(sc);
16471     } else {
16472         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16473     }
16474 #endif
16475 
16476     /* calculate qm_cid_count */
16477     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16478     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16479 
16480     sc->max_cos = 1;
16481     bxe_init_multi_cos(sc);
16482 
16483     bxe_add_sysctls(sc);
16484 
16485     return (0);
16486 }
16487 
16488 /*
16489  * Device detach function.
16490  *
16491  * Stops the controller, resets the controller, and releases resources.
16492  *
16493  * Returns:
16494  *   0 = Success, >0 = Failure
16495  */
16496 static int
16497 bxe_detach(device_t dev)
16498 {
16499     struct bxe_softc *sc;
16500     if_t ifp;
16501 
16502     sc = device_get_softc(dev);
16503 
16504     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16505 
16506     ifp = sc->ifp;
16507     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
16508         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16509         return(EBUSY);
16510     }
16511 
16512     bxe_del_cdev(sc);
16513 
16514     /* stop the periodic callout */
16515     bxe_periodic_stop(sc);
16516 
16517     /* stop the chip taskqueue */
16518     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16519     if (sc->chip_tq) {
16520         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16521         taskqueue_free(sc->chip_tq);
16522         sc->chip_tq = NULL;
16523         taskqueue_drain_timeout(taskqueue_thread,
16524             &sc->sp_err_timeout_task);
16525     }
16526 
16527     /* stop and reset the controller if it was open */
16528     if (sc->state != BXE_STATE_CLOSED) {
16529         BXE_CORE_LOCK(sc);
16530         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16531         sc->state = BXE_STATE_DISABLED;
16532         BXE_CORE_UNLOCK(sc);
16533     }
16534 
16535     /* release the network interface */
16536     if (ifp != NULL) {
16537         ether_ifdetach(ifp);
16538     }
16539     ifmedia_removeall(&sc->ifmedia);
16540 
16541     /* XXX do the following based on driver state... */
16542 
16543     /* free the host hardware/software hsi structures */
16544     bxe_free_hsi_mem(sc);
16545 
16546     /* free ilt */
16547     bxe_free_ilt_mem(sc);
16548 
16549     bxe_free_buf_rings(sc);
16550 
16551     /* release the interrupts */
16552     bxe_interrupt_free(sc);
16553 
16554     /* Release the mutexes*/
16555     bxe_destroy_fp_mutexs(sc);
16556     bxe_release_mutexes(sc);
16557 
16558 
16559     /* Release the PCIe BAR mapped memory */
16560     bxe_deallocate_bars(sc);
16561 
16562     /* Release the FreeBSD interface. */
16563     if (sc->ifp != NULL) {
16564         if_free(sc->ifp);
16565     }
16566 
16567     pci_disable_busmaster(dev);
16568 
16569     return (0);
16570 }
16571 
16572 /*
16573  * Device shutdown function.
16574  *
16575  * Stops and resets the controller.
16576  *
16577  * Returns:
16578  *   Nothing
16579  */
16580 static int
16581 bxe_shutdown(device_t dev)
16582 {
16583     struct bxe_softc *sc;
16584 
16585     sc = device_get_softc(dev);
16586 
16587     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16588 
16589     /* stop the periodic callout */
16590     bxe_periodic_stop(sc);
16591 
16592     if (sc->state != BXE_STATE_CLOSED) {
16593     	BXE_CORE_LOCK(sc);
16594     	bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16595     	BXE_CORE_UNLOCK(sc);
16596     }
16597 
16598     return (0);
16599 }
16600 
16601 void
16602 bxe_igu_ack_sb(struct bxe_softc *sc,
16603                uint8_t          igu_sb_id,
16604                uint8_t          segment,
16605                uint16_t         index,
16606                uint8_t          op,
16607                uint8_t          update)
16608 {
16609     uint32_t igu_addr = sc->igu_base_addr;
16610     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16611     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16612 }
16613 
16614 static void
16615 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16616                      uint8_t          func,
16617                      uint8_t          idu_sb_id,
16618                      uint8_t          is_pf)
16619 {
16620     uint32_t data, ctl, cnt = 100;
16621     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16622     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16623     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16624     uint32_t sb_bit =  1 << (idu_sb_id%32);
16625     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16626     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16627 
16628     /* Not supported in BC mode */
16629     if (CHIP_INT_MODE_IS_BC(sc)) {
16630         return;
16631     }
16632 
16633     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16634              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16635             IGU_REGULAR_CLEANUP_SET |
16636             IGU_REGULAR_BCLEANUP);
16637 
16638     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16639            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16640            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16641 
16642     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16643             data, igu_addr_data);
16644     REG_WR(sc, igu_addr_data, data);
16645 
16646     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16647                       BUS_SPACE_BARRIER_WRITE);
16648     mb();
16649 
16650     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16651             ctl, igu_addr_ctl);
16652     REG_WR(sc, igu_addr_ctl, ctl);
16653 
16654     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16655                       BUS_SPACE_BARRIER_WRITE);
16656     mb();
16657 
16658     /* wait for clean up to finish */
16659     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16660         DELAY(20000);
16661     }
16662 
16663     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16664         BLOGD(sc, DBG_LOAD,
16665               "Unable to finish IGU cleanup: "
16666               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16667               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16668     }
16669 }
16670 
16671 static void
16672 bxe_igu_clear_sb(struct bxe_softc *sc,
16673                  uint8_t          idu_sb_id)
16674 {
16675     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16676 }
16677 
16678 
16679 
16680 
16681 
16682 
16683 
16684 /*******************/
16685 /* ECORE CALLBACKS */
16686 /*******************/
16687 
16688 static void
16689 bxe_reset_common(struct bxe_softc *sc)
16690 {
16691     uint32_t val = 0x1400;
16692 
16693     /* reset_common */
16694     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16695 
16696     if (CHIP_IS_E3(sc)) {
16697         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16698         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16699     }
16700 
16701     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16702 }
16703 
16704 static void
16705 bxe_common_init_phy(struct bxe_softc *sc)
16706 {
16707     uint32_t shmem_base[2];
16708     uint32_t shmem2_base[2];
16709 
16710     /* Avoid common init in case MFW supports LFA */
16711     if (SHMEM2_RD(sc, size) >
16712         (uint32_t)offsetof(struct shmem2_region,
16713                            lfa_host_addr[SC_PORT(sc)])) {
16714         return;
16715     }
16716 
16717     shmem_base[0]  = sc->devinfo.shmem_base;
16718     shmem2_base[0] = sc->devinfo.shmem2_base;
16719 
16720     if (!CHIP_IS_E1x(sc)) {
16721         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16722         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16723     }
16724 
16725     bxe_acquire_phy_lock(sc);
16726     elink_common_init_phy(sc, shmem_base, shmem2_base,
16727                           sc->devinfo.chip_id, 0);
16728     bxe_release_phy_lock(sc);
16729 }
16730 
16731 static void
16732 bxe_pf_disable(struct bxe_softc *sc)
16733 {
16734     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16735 
16736     val &= ~IGU_PF_CONF_FUNC_EN;
16737 
16738     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16739     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16740     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16741 }
16742 
16743 static void
16744 bxe_init_pxp(struct bxe_softc *sc)
16745 {
16746     uint16_t devctl;
16747     int r_order, w_order;
16748 
16749     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16750 
16751     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16752 
16753     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16754 
16755     if (sc->mrrs == -1) {
16756         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16757     } else {
16758         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16759         r_order = sc->mrrs;
16760     }
16761 
16762     ecore_init_pxp_arb(sc, r_order, w_order);
16763 }
16764 
16765 static uint32_t
16766 bxe_get_pretend_reg(struct bxe_softc *sc)
16767 {
16768     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16769     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16770     return (base + (SC_ABS_FUNC(sc)) * stride);
16771 }
16772 
16773 /*
16774  * Called only on E1H or E2.
16775  * When pretending to be PF, the pretend value is the function number 0..7.
16776  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16777  * combination.
16778  */
16779 static int
16780 bxe_pretend_func(struct bxe_softc *sc,
16781                  uint16_t         pretend_func_val)
16782 {
16783     uint32_t pretend_reg;
16784 
16785     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16786         return (-1);
16787     }
16788 
16789     /* get my own pretend register */
16790     pretend_reg = bxe_get_pretend_reg(sc);
16791     REG_WR(sc, pretend_reg, pretend_func_val);
16792     REG_RD(sc, pretend_reg);
16793     return (0);
16794 }
16795 
16796 static void
16797 bxe_iov_init_dmae(struct bxe_softc *sc)
16798 {
16799     return;
16800 }
16801 
16802 static void
16803 bxe_iov_init_dq(struct bxe_softc *sc)
16804 {
16805     return;
16806 }
16807 
16808 /* send a NIG loopback debug packet */
16809 static void
16810 bxe_lb_pckt(struct bxe_softc *sc)
16811 {
16812     uint32_t wb_write[3];
16813 
16814     /* Ethernet source and destination addresses */
16815     wb_write[0] = 0x55555555;
16816     wb_write[1] = 0x55555555;
16817     wb_write[2] = 0x20;     /* SOP */
16818     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16819 
16820     /* NON-IP protocol */
16821     wb_write[0] = 0x09000000;
16822     wb_write[1] = 0x55555555;
16823     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16824     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16825 }
16826 
16827 /*
16828  * Some of the internal memories are not directly readable from the driver.
16829  * To test them we send debug packets.
16830  */
16831 static int
16832 bxe_int_mem_test(struct bxe_softc *sc)
16833 {
16834     int factor;
16835     int count, i;
16836     uint32_t val = 0;
16837 
16838     if (CHIP_REV_IS_FPGA(sc)) {
16839         factor = 120;
16840     } else if (CHIP_REV_IS_EMUL(sc)) {
16841         factor = 200;
16842     } else {
16843         factor = 1;
16844     }
16845 
16846     /* disable inputs of parser neighbor blocks */
16847     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16848     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16849     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16850     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16851 
16852     /*  write 0 to parser credits for CFC search request */
16853     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16854 
16855     /* send Ethernet packet */
16856     bxe_lb_pckt(sc);
16857 
16858     /* TODO do i reset NIG statistic? */
16859     /* Wait until NIG register shows 1 packet of size 0x10 */
16860     count = 1000 * factor;
16861     while (count) {
16862         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16863         val = *BXE_SP(sc, wb_data[0]);
16864         if (val == 0x10) {
16865             break;
16866         }
16867 
16868         DELAY(10000);
16869         count--;
16870     }
16871 
16872     if (val != 0x10) {
16873         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16874         return (-1);
16875     }
16876 
16877     /* wait until PRS register shows 1 packet */
16878     count = (1000 * factor);
16879     while (count) {
16880         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16881         if (val == 1) {
16882             break;
16883         }
16884 
16885         DELAY(10000);
16886         count--;
16887     }
16888 
16889     if (val != 0x1) {
16890         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16891         return (-2);
16892     }
16893 
16894     /* Reset and init BRB, PRS */
16895     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16896     DELAY(50000);
16897     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16898     DELAY(50000);
16899     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16900     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16901 
16902     /* Disable inputs of parser neighbor blocks */
16903     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16904     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16905     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16906     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16907 
16908     /* Write 0 to parser credits for CFC search request */
16909     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16910 
16911     /* send 10 Ethernet packets */
16912     for (i = 0; i < 10; i++) {
16913         bxe_lb_pckt(sc);
16914     }
16915 
16916     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16917     count = (1000 * factor);
16918     while (count) {
16919         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16920         val = *BXE_SP(sc, wb_data[0]);
16921         if (val == 0xb0) {
16922             break;
16923         }
16924 
16925         DELAY(10000);
16926         count--;
16927     }
16928 
16929     if (val != 0xb0) {
16930         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16931         return (-3);
16932     }
16933 
16934     /* Wait until PRS register shows 2 packets */
16935     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16936     if (val != 2) {
16937         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16938     }
16939 
16940     /* Write 1 to parser credits for CFC search request */
16941     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16942 
16943     /* Wait until PRS register shows 3 packets */
16944     DELAY(10000 * factor);
16945 
16946     /* Wait until NIG register shows 1 packet of size 0x10 */
16947     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16948     if (val != 3) {
16949         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16950     }
16951 
16952     /* clear NIG EOP FIFO */
16953     for (i = 0; i < 11; i++) {
16954         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16955     }
16956 
16957     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16958     if (val != 1) {
16959         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16960         return (-4);
16961     }
16962 
16963     /* Reset and init BRB, PRS, NIG */
16964     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16965     DELAY(50000);
16966     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16967     DELAY(50000);
16968     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16969     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16970     if (!CNIC_SUPPORT(sc)) {
16971         /* set NIC mode */
16972         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16973     }
16974 
16975     /* Enable inputs of parser neighbor blocks */
16976     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16977     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16978     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16979     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16980 
16981     return (0);
16982 }
16983 
16984 static void
16985 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16986 {
16987     int is_required;
16988     uint32_t val;
16989     int port;
16990 
16991     is_required = 0;
16992     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16993            SHARED_HW_CFG_FAN_FAILURE_MASK);
16994 
16995     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16996         is_required = 1;
16997     }
16998     /*
16999      * The fan failure mechanism is usually related to the PHY type since
17000      * the power consumption of the board is affected by the PHY. Currently,
17001      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
17002      */
17003     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
17004         for (port = PORT_0; port < PORT_MAX; port++) {
17005             is_required |= elink_fan_failure_det_req(sc,
17006                                                      sc->devinfo.shmem_base,
17007                                                      sc->devinfo.shmem2_base,
17008                                                      port);
17009         }
17010     }
17011 
17012     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
17013 
17014     if (is_required == 0) {
17015         return;
17016     }
17017 
17018     /* Fan failure is indicated by SPIO 5 */
17019     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
17020 
17021     /* set to active low mode */
17022     val = REG_RD(sc, MISC_REG_SPIO_INT);
17023     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
17024     REG_WR(sc, MISC_REG_SPIO_INT, val);
17025 
17026     /* enable interrupt to signal the IGU */
17027     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17028     val |= MISC_SPIO_SPIO5;
17029     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
17030 }
17031 
17032 static void
17033 bxe_enable_blocks_attention(struct bxe_softc *sc)
17034 {
17035     uint32_t val;
17036 
17037     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17038     if (!CHIP_IS_E1x(sc)) {
17039         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
17040     } else {
17041         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
17042     }
17043     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17044     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17045     /*
17046      * mask read length error interrupts in brb for parser
17047      * (parsing unit and 'checksum and crc' unit)
17048      * these errors are legal (PU reads fixed length and CAC can cause
17049      * read length error on truncated packets)
17050      */
17051     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
17052     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
17053     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
17054     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
17055     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
17056     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
17057 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
17058 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
17059     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
17060     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
17061     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
17062 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
17063 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
17064     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
17065     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
17066     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
17067     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
17068 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
17069 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
17070 
17071     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
17072            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
17073            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
17074     if (!CHIP_IS_E1x(sc)) {
17075         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
17076                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
17077     }
17078     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
17079 
17080     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
17081     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
17082     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
17083 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
17084 
17085     if (!CHIP_IS_E1x(sc)) {
17086         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
17087         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
17088     }
17089 
17090     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
17091     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
17092 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
17093     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
17094 }
17095 
17096 /**
17097  * bxe_init_hw_common - initialize the HW at the COMMON phase.
17098  *
17099  * @sc:     driver handle
17100  */
17101 static int
17102 bxe_init_hw_common(struct bxe_softc *sc)
17103 {
17104     uint8_t abs_func_id;
17105     uint32_t val;
17106 
17107     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
17108           SC_ABS_FUNC(sc));
17109 
17110     /*
17111      * take the RESET lock to protect undi_unload flow from accessing
17112      * registers while we are resetting the chip
17113      */
17114     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17115 
17116     bxe_reset_common(sc);
17117 
17118     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
17119 
17120     val = 0xfffc;
17121     if (CHIP_IS_E3(sc)) {
17122         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
17123         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
17124     }
17125 
17126     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
17127 
17128     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
17129 
17130     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
17131     BLOGD(sc, DBG_LOAD, "after misc block init\n");
17132 
17133     if (!CHIP_IS_E1x(sc)) {
17134         /*
17135          * 4-port mode or 2-port mode we need to turn off master-enable for
17136          * everyone. After that we turn it back on for self. So, we disregard
17137          * multi-function, and always disable all functions on the given path,
17138          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
17139          */
17140         for (abs_func_id = SC_PATH(sc);
17141              abs_func_id < (E2_FUNC_MAX * 2);
17142              abs_func_id += 2) {
17143             if (abs_func_id == SC_ABS_FUNC(sc)) {
17144                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17145                 continue;
17146             }
17147 
17148             bxe_pretend_func(sc, abs_func_id);
17149 
17150             /* clear pf enable */
17151             bxe_pf_disable(sc);
17152 
17153             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17154         }
17155     }
17156 
17157     BLOGD(sc, DBG_LOAD, "after pf disable\n");
17158 
17159     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
17160 
17161     if (CHIP_IS_E1(sc)) {
17162         /*
17163          * enable HW interrupt from PXP on USDM overflow
17164          * bit 16 on INT_MASK_0
17165          */
17166         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
17167     }
17168 
17169     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
17170     bxe_init_pxp(sc);
17171 
17172 #ifdef __BIG_ENDIAN
17173     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
17174     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
17175     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
17176     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
17177     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
17178     /* make sure this value is 0 */
17179     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
17180 
17181     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
17182     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
17183     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
17184     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
17185     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
17186 #endif
17187 
17188     ecore_ilt_init_page_size(sc, INITOP_SET);
17189 
17190     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
17191         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
17192     }
17193 
17194     /* let the HW do it's magic... */
17195     DELAY(100000);
17196 
17197     /* finish PXP init */
17198     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
17199     if (val != 1) {
17200         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
17201             val);
17202         return (-1);
17203     }
17204     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
17205     if (val != 1) {
17206         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
17207         return (-1);
17208     }
17209 
17210     BLOGD(sc, DBG_LOAD, "after pxp init\n");
17211 
17212     /*
17213      * Timer bug workaround for E2 only. We need to set the entire ILT to have
17214      * entries with value "0" and valid bit on. This needs to be done by the
17215      * first PF that is loaded in a path (i.e. common phase)
17216      */
17217     if (!CHIP_IS_E1x(sc)) {
17218 /*
17219  * In E2 there is a bug in the timers block that can cause function 6 / 7
17220  * (i.e. vnic3) to start even if it is marked as "scan-off".
17221  * This occurs when a different function (func2,3) is being marked
17222  * as "scan-off". Real-life scenario for example: if a driver is being
17223  * load-unloaded while func6,7 are down. This will cause the timer to access
17224  * the ilt, translate to a logical address and send a request to read/write.
17225  * Since the ilt for the function that is down is not valid, this will cause
17226  * a translation error which is unrecoverable.
17227  * The Workaround is intended to make sure that when this happens nothing
17228  * fatal will occur. The workaround:
17229  *  1.  First PF driver which loads on a path will:
17230  *      a.  After taking the chip out of reset, by using pretend,
17231  *          it will write "0" to the following registers of
17232  *          the other vnics.
17233  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
17234  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
17235  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
17236  *          And for itself it will write '1' to
17237  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
17238  *          dmae-operations (writing to pram for example.)
17239  *          note: can be done for only function 6,7 but cleaner this
17240  *            way.
17241  *      b.  Write zero+valid to the entire ILT.
17242  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
17243  *          VNIC3 (of that port). The range allocated will be the
17244  *          entire ILT. This is needed to prevent  ILT range error.
17245  *  2.  Any PF driver load flow:
17246  *      a.  ILT update with the physical addresses of the allocated
17247  *          logical pages.
17248  *      b.  Wait 20msec. - note that this timeout is needed to make
17249  *          sure there are no requests in one of the PXP internal
17250  *          queues with "old" ILT addresses.
17251  *      c.  PF enable in the PGLC.
17252  *      d.  Clear the was_error of the PF in the PGLC. (could have
17253  *          occurred while driver was down)
17254  *      e.  PF enable in the CFC (WEAK + STRONG)
17255  *      f.  Timers scan enable
17256  *  3.  PF driver unload flow:
17257  *      a.  Clear the Timers scan_en.
17258  *      b.  Polling for scan_on=0 for that PF.
17259  *      c.  Clear the PF enable bit in the PXP.
17260  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
17261  *      e.  Write zero+valid to all ILT entries (The valid bit must
17262  *          stay set)
17263  *      f.  If this is VNIC 3 of a port then also init
17264  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
17265  *          to the last enrty in the ILT.
17266  *
17267  *      Notes:
17268  *      Currently the PF error in the PGLC is non recoverable.
17269  *      In the future the there will be a recovery routine for this error.
17270  *      Currently attention is masked.
17271  *      Having an MCP lock on the load/unload process does not guarantee that
17272  *      there is no Timer disable during Func6/7 enable. This is because the
17273  *      Timers scan is currently being cleared by the MCP on FLR.
17274  *      Step 2.d can be done only for PF6/7 and the driver can also check if
17275  *      there is error before clearing it. But the flow above is simpler and
17276  *      more general.
17277  *      All ILT entries are written by zero+valid and not just PF6/7
17278  *      ILT entries since in the future the ILT entries allocation for
17279  *      PF-s might be dynamic.
17280  */
17281         struct ilt_client_info ilt_cli;
17282         struct ecore_ilt ilt;
17283 
17284         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
17285         memset(&ilt, 0, sizeof(struct ecore_ilt));
17286 
17287         /* initialize dummy TM client */
17288         ilt_cli.start      = 0;
17289         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
17290         ilt_cli.client_num = ILT_CLIENT_TM;
17291 
17292         /*
17293          * Step 1: set zeroes to all ilt page entries with valid bit on
17294          * Step 2: set the timers first/last ilt entry to point
17295          * to the entire range to prevent ILT range error for 3rd/4th
17296          * vnic (this code assumes existence of the vnic)
17297          *
17298          * both steps performed by call to ecore_ilt_client_init_op()
17299          * with dummy TM client
17300          *
17301          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
17302          * and his brother are split registers
17303          */
17304 
17305         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
17306         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
17307         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
17308 
17309         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
17310         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
17311         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
17312     }
17313 
17314     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
17315     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
17316 
17317     if (!CHIP_IS_E1x(sc)) {
17318         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
17319                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
17320 
17321         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
17322         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
17323 
17324         /* let the HW do it's magic... */
17325         do {
17326             DELAY(200000);
17327             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17328         } while (factor-- && (val != 1));
17329 
17330         if (val != 1) {
17331             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17332             return (-1);
17333         }
17334     }
17335 
17336     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17337 
17338     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17339 
17340     bxe_iov_init_dmae(sc);
17341 
17342     /* clean the DMAE memory */
17343     sc->dmae_ready = 1;
17344     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17345 
17346     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17347 
17348     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17349 
17350     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17351 
17352     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17353 
17354     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17355     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17356     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17357     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17358 
17359     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17360 
17361     /* QM queues pointers table */
17362     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17363 
17364     /* soft reset pulse */
17365     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17366     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17367 
17368     if (CNIC_SUPPORT(sc))
17369         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17370 
17371     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17372     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17373     if (!CHIP_REV_IS_SLOW(sc)) {
17374         /* enable hw interrupt from doorbell Q */
17375         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17376     }
17377 
17378     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17379 
17380     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17381     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17382 
17383     if (!CHIP_IS_E1(sc)) {
17384         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17385     }
17386 
17387     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17388         if (IS_MF_AFEX(sc)) {
17389             /*
17390              * configure that AFEX and VLAN headers must be
17391              * received in AFEX mode
17392              */
17393             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17394             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17395             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17396             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17397             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17398         } else {
17399             /*
17400              * Bit-map indicating which L2 hdrs may appear
17401              * after the basic Ethernet header
17402              */
17403             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17404                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17405         }
17406     }
17407 
17408     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17409     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17410     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17411     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17412 
17413     if (!CHIP_IS_E1x(sc)) {
17414         /* reset VFC memories */
17415         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17416                VFC_MEMORIES_RST_REG_CAM_RST |
17417                VFC_MEMORIES_RST_REG_RAM_RST);
17418         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17419                VFC_MEMORIES_RST_REG_CAM_RST |
17420                VFC_MEMORIES_RST_REG_RAM_RST);
17421 
17422         DELAY(20000);
17423     }
17424 
17425     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17426     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17427     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17428     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17429 
17430     /* sync semi rtc */
17431     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17432            0x80000000);
17433     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17434            0x80000000);
17435 
17436     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17437     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17438     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17439 
17440     if (!CHIP_IS_E1x(sc)) {
17441         if (IS_MF_AFEX(sc)) {
17442             /*
17443              * configure that AFEX and VLAN headers must be
17444              * sent in AFEX mode
17445              */
17446             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17447             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17448             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17449             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17450             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17451         } else {
17452             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17453                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17454         }
17455     }
17456 
17457     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17458 
17459     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17460 
17461     if (CNIC_SUPPORT(sc)) {
17462         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17463         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17464         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17465         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17466         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17467         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17468         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17469         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17470         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17471         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17472     }
17473     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17474 
17475     if (sizeof(union cdu_context) != 1024) {
17476         /* we currently assume that a context is 1024 bytes */
17477         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17478               (long)sizeof(union cdu_context));
17479     }
17480 
17481     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17482     val = (4 << 24) + (0 << 12) + 1024;
17483     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17484 
17485     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17486 
17487     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17488     /* enable context validation interrupt from CFC */
17489     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17490 
17491     /* set the thresholds to prevent CFC/CDU race */
17492     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17493     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17494 
17495     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17496         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17497     }
17498 
17499     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17500     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17501 
17502     /* Reset PCIE errors for debug */
17503     REG_WR(sc, 0x2814, 0xffffffff);
17504     REG_WR(sc, 0x3820, 0xffffffff);
17505 
17506     if (!CHIP_IS_E1x(sc)) {
17507         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17508                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17509                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17510         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17511                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17512                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17513                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17514         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17515                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17516                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17517                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17518     }
17519 
17520     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17521 
17522     if (!CHIP_IS_E1(sc)) {
17523         /* in E3 this done in per-port section */
17524         if (!CHIP_IS_E3(sc))
17525             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17526     }
17527 
17528     if (CHIP_IS_E1H(sc)) {
17529         /* not applicable for E2 (and above ...) */
17530         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17531     }
17532 
17533     if (CHIP_REV_IS_SLOW(sc)) {
17534         DELAY(200000);
17535     }
17536 
17537     /* finish CFC init */
17538     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17539     if (val != 1) {
17540         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17541         return (-1);
17542     }
17543     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17544     if (val != 1) {
17545         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17546         return (-1);
17547     }
17548     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17549     if (val != 1) {
17550         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17551         return (-1);
17552     }
17553     REG_WR(sc, CFC_REG_DEBUG0, 0);
17554 
17555     if (CHIP_IS_E1(sc)) {
17556         /* read NIG statistic to see if this is our first up since powerup */
17557         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17558         val = *BXE_SP(sc, wb_data[0]);
17559 
17560         /* do internal memory self test */
17561         if ((val == 0) && bxe_int_mem_test(sc)) {
17562             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17563             return (-1);
17564         }
17565     }
17566 
17567     bxe_setup_fan_failure_detection(sc);
17568 
17569     /* clear PXP2 attentions */
17570     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17571 
17572     bxe_enable_blocks_attention(sc);
17573 
17574     if (!CHIP_REV_IS_SLOW(sc)) {
17575         ecore_enable_blocks_parity(sc);
17576     }
17577 
17578     if (!BXE_NOMCP(sc)) {
17579         if (CHIP_IS_E1x(sc)) {
17580             bxe_common_init_phy(sc);
17581         }
17582     }
17583 
17584     return (0);
17585 }
17586 
17587 /**
17588  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17589  *
17590  * @sc:     driver handle
17591  */
17592 static int
17593 bxe_init_hw_common_chip(struct bxe_softc *sc)
17594 {
17595     int rc = bxe_init_hw_common(sc);
17596 
17597     if (rc) {
17598         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17599         return (rc);
17600     }
17601 
17602     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17603     if (!BXE_NOMCP(sc)) {
17604         bxe_common_init_phy(sc);
17605     }
17606 
17607     return (0);
17608 }
17609 
17610 static int
17611 bxe_init_hw_port(struct bxe_softc *sc)
17612 {
17613     int port = SC_PORT(sc);
17614     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17615     uint32_t low, high;
17616     uint32_t val;
17617 
17618     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17619 
17620     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17621 
17622     ecore_init_block(sc, BLOCK_MISC, init_phase);
17623     ecore_init_block(sc, BLOCK_PXP, init_phase);
17624     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17625 
17626     /*
17627      * Timers bug workaround: disables the pf_master bit in pglue at
17628      * common phase, we need to enable it here before any dmae access are
17629      * attempted. Therefore we manually added the enable-master to the
17630      * port phase (it also happens in the function phase)
17631      */
17632     if (!CHIP_IS_E1x(sc)) {
17633         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17634     }
17635 
17636     ecore_init_block(sc, BLOCK_ATC, init_phase);
17637     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17638     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17639     ecore_init_block(sc, BLOCK_QM, init_phase);
17640 
17641     ecore_init_block(sc, BLOCK_TCM, init_phase);
17642     ecore_init_block(sc, BLOCK_UCM, init_phase);
17643     ecore_init_block(sc, BLOCK_CCM, init_phase);
17644     ecore_init_block(sc, BLOCK_XCM, init_phase);
17645 
17646     /* QM cid (connection) count */
17647     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17648 
17649     if (CNIC_SUPPORT(sc)) {
17650         ecore_init_block(sc, BLOCK_TM, init_phase);
17651         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17652         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17653     }
17654 
17655     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17656 
17657     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17658 
17659     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17660         if (IS_MF(sc)) {
17661             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17662         } else if (sc->mtu > 4096) {
17663             if (BXE_ONE_PORT(sc)) {
17664                 low = 160;
17665             } else {
17666                 val = sc->mtu;
17667                 /* (24*1024 + val*4)/256 */
17668                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17669             }
17670         } else {
17671             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17672         }
17673         high = (low + 56); /* 14*1024/256 */
17674         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17675         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17676     }
17677 
17678     if (CHIP_IS_MODE_4_PORT(sc)) {
17679         REG_WR(sc, SC_PORT(sc) ?
17680                BRB1_REG_MAC_GUARANTIED_1 :
17681                BRB1_REG_MAC_GUARANTIED_0, 40);
17682     }
17683 
17684     ecore_init_block(sc, BLOCK_PRS, init_phase);
17685     if (CHIP_IS_E3B0(sc)) {
17686         if (IS_MF_AFEX(sc)) {
17687             /* configure headers for AFEX mode */
17688             REG_WR(sc, SC_PORT(sc) ?
17689                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17690                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17691             REG_WR(sc, SC_PORT(sc) ?
17692                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17693                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17694             REG_WR(sc, SC_PORT(sc) ?
17695                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17696                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17697         } else {
17698             /* Ovlan exists only if we are in multi-function +
17699              * switch-dependent mode, in switch-independent there
17700              * is no ovlan headers
17701              */
17702             REG_WR(sc, SC_PORT(sc) ?
17703                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17704                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17705                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17706         }
17707     }
17708 
17709     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17710     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17711     ecore_init_block(sc, BLOCK_USDM, init_phase);
17712     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17713 
17714     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17715     ecore_init_block(sc, BLOCK_USEM, init_phase);
17716     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17717     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17718 
17719     ecore_init_block(sc, BLOCK_UPB, init_phase);
17720     ecore_init_block(sc, BLOCK_XPB, init_phase);
17721 
17722     ecore_init_block(sc, BLOCK_PBF, init_phase);
17723 
17724     if (CHIP_IS_E1x(sc)) {
17725         /* configure PBF to work without PAUSE mtu 9000 */
17726         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17727 
17728         /* update threshold */
17729         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17730         /* update init credit */
17731         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17732 
17733         /* probe changes */
17734         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17735         DELAY(50);
17736         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17737     }
17738 
17739     if (CNIC_SUPPORT(sc)) {
17740         ecore_init_block(sc, BLOCK_SRC, init_phase);
17741     }
17742 
17743     ecore_init_block(sc, BLOCK_CDU, init_phase);
17744     ecore_init_block(sc, BLOCK_CFC, init_phase);
17745 
17746     if (CHIP_IS_E1(sc)) {
17747         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17748         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17749     }
17750     ecore_init_block(sc, BLOCK_HC, init_phase);
17751 
17752     ecore_init_block(sc, BLOCK_IGU, init_phase);
17753 
17754     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17755     /* init aeu_mask_attn_func_0/1:
17756      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17757      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17758      *             bits 4-7 are used for "per vn group attention" */
17759     val = IS_MF(sc) ? 0xF7 : 0x7;
17760     /* Enable DCBX attention for all but E1 */
17761     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17762     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17763 
17764     ecore_init_block(sc, BLOCK_NIG, init_phase);
17765 
17766     if (!CHIP_IS_E1x(sc)) {
17767         /* Bit-map indicating which L2 hdrs may appear after the
17768          * basic Ethernet header
17769          */
17770         if (IS_MF_AFEX(sc)) {
17771             REG_WR(sc, SC_PORT(sc) ?
17772                    NIG_REG_P1_HDRS_AFTER_BASIC :
17773                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17774         } else {
17775             REG_WR(sc, SC_PORT(sc) ?
17776                    NIG_REG_P1_HDRS_AFTER_BASIC :
17777                    NIG_REG_P0_HDRS_AFTER_BASIC,
17778                    IS_MF_SD(sc) ? 7 : 6);
17779         }
17780 
17781         if (CHIP_IS_E3(sc)) {
17782             REG_WR(sc, SC_PORT(sc) ?
17783                    NIG_REG_LLH1_MF_MODE :
17784                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17785         }
17786     }
17787     if (!CHIP_IS_E3(sc)) {
17788         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17789     }
17790 
17791     if (!CHIP_IS_E1(sc)) {
17792         /* 0x2 disable mf_ov, 0x1 enable */
17793         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17794                (IS_MF_SD(sc) ? 0x1 : 0x2));
17795 
17796         if (!CHIP_IS_E1x(sc)) {
17797             val = 0;
17798             switch (sc->devinfo.mf_info.mf_mode) {
17799             case MULTI_FUNCTION_SD:
17800                 val = 1;
17801                 break;
17802             case MULTI_FUNCTION_SI:
17803             case MULTI_FUNCTION_AFEX:
17804                 val = 2;
17805                 break;
17806             }
17807 
17808             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17809                         NIG_REG_LLH0_CLS_TYPE), val);
17810         }
17811         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17812         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17813         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17814     }
17815 
17816     /* If SPIO5 is set to generate interrupts, enable it for this port */
17817     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17818     if (val & MISC_SPIO_SPIO5) {
17819         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17820                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17821         val = REG_RD(sc, reg_addr);
17822         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17823         REG_WR(sc, reg_addr, val);
17824     }
17825 
17826     return (0);
17827 }
17828 
17829 static uint32_t
17830 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17831                        uint32_t         reg,
17832                        uint32_t         expected,
17833                        uint32_t         poll_count)
17834 {
17835     uint32_t cur_cnt = poll_count;
17836     uint32_t val;
17837 
17838     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17839         DELAY(FLR_WAIT_INTERVAL);
17840     }
17841 
17842     return (val);
17843 }
17844 
17845 static int
17846 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17847                               uint32_t         reg,
17848                               char             *msg,
17849                               uint32_t         poll_cnt)
17850 {
17851     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17852 
17853     if (val != 0) {
17854         BLOGE(sc, "%s usage count=%d\n", msg, val);
17855         return (1);
17856     }
17857 
17858     return (0);
17859 }
17860 
17861 /* Common routines with VF FLR cleanup */
17862 static uint32_t
17863 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17864 {
17865     /* adjust polling timeout */
17866     if (CHIP_REV_IS_EMUL(sc)) {
17867         return (FLR_POLL_CNT * 2000);
17868     }
17869 
17870     if (CHIP_REV_IS_FPGA(sc)) {
17871         return (FLR_POLL_CNT * 120);
17872     }
17873 
17874     return (FLR_POLL_CNT);
17875 }
17876 
17877 static int
17878 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17879                            uint32_t         poll_cnt)
17880 {
17881     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17882     if (bxe_flr_clnup_poll_hw_counter(sc,
17883                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17884                                       "CFC PF usage counter timed out",
17885                                       poll_cnt)) {
17886         return (1);
17887     }
17888 
17889     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17890     if (bxe_flr_clnup_poll_hw_counter(sc,
17891                                       DORQ_REG_PF_USAGE_CNT,
17892                                       "DQ PF usage counter timed out",
17893                                       poll_cnt)) {
17894         return (1);
17895     }
17896 
17897     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17898     if (bxe_flr_clnup_poll_hw_counter(sc,
17899                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17900                                       "QM PF usage counter timed out",
17901                                       poll_cnt)) {
17902         return (1);
17903     }
17904 
17905     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17906     if (bxe_flr_clnup_poll_hw_counter(sc,
17907                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17908                                       "Timers VNIC usage counter timed out",
17909                                       poll_cnt)) {
17910         return (1);
17911     }
17912 
17913     if (bxe_flr_clnup_poll_hw_counter(sc,
17914                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17915                                       "Timers NUM_SCANS usage counter timed out",
17916                                       poll_cnt)) {
17917         return (1);
17918     }
17919 
17920     /* Wait DMAE PF usage counter to zero */
17921     if (bxe_flr_clnup_poll_hw_counter(sc,
17922                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17923                                       "DMAE dommand register timed out",
17924                                       poll_cnt)) {
17925         return (1);
17926     }
17927 
17928     return (0);
17929 }
17930 
17931 #define OP_GEN_PARAM(param)                                            \
17932     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17933 #define OP_GEN_TYPE(type)                                           \
17934     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17935 #define OP_GEN_AGG_VECT(index)                                             \
17936     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17937 
17938 static int
17939 bxe_send_final_clnup(struct bxe_softc *sc,
17940                      uint8_t          clnup_func,
17941                      uint32_t         poll_cnt)
17942 {
17943     uint32_t op_gen_command = 0;
17944     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17945                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17946     int ret = 0;
17947 
17948     if (REG_RD(sc, comp_addr)) {
17949         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17950         return (1);
17951     }
17952 
17953     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17954     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17955     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17956     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17957 
17958     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17959     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17960 
17961     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17962         BLOGE(sc, "FW final cleanup did not succeed\n");
17963         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17964               (REG_RD(sc, comp_addr)));
17965         bxe_panic(sc, ("FLR cleanup failed\n"));
17966         return (1);
17967     }
17968 
17969     /* Zero completion for nxt FLR */
17970     REG_WR(sc, comp_addr, 0);
17971 
17972     return (ret);
17973 }
17974 
17975 static void
17976 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17977                        struct pbf_pN_buf_regs *regs,
17978                        uint32_t               poll_count)
17979 {
17980     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17981     uint32_t cur_cnt = poll_count;
17982 
17983     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17984     crd = crd_start = REG_RD(sc, regs->crd);
17985     init_crd = REG_RD(sc, regs->init_crd);
17986 
17987     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17988     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17989     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17990 
17991     while ((crd != init_crd) &&
17992            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17993             (init_crd - crd_start))) {
17994         if (cur_cnt--) {
17995             DELAY(FLR_WAIT_INTERVAL);
17996             crd = REG_RD(sc, regs->crd);
17997             crd_freed = REG_RD(sc, regs->crd_freed);
17998         } else {
17999             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
18000             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
18001             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
18002             break;
18003         }
18004     }
18005 
18006     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
18007           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18008 }
18009 
18010 static void
18011 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
18012                        struct pbf_pN_cmd_regs *regs,
18013                        uint32_t               poll_count)
18014 {
18015     uint32_t occup, to_free, freed, freed_start;
18016     uint32_t cur_cnt = poll_count;
18017 
18018     occup = to_free = REG_RD(sc, regs->lines_occup);
18019     freed = freed_start = REG_RD(sc, regs->lines_freed);
18020 
18021     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18022     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18023 
18024     while (occup &&
18025            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
18026         if (cur_cnt--) {
18027             DELAY(FLR_WAIT_INTERVAL);
18028             occup = REG_RD(sc, regs->lines_occup);
18029             freed = REG_RD(sc, regs->lines_freed);
18030         } else {
18031             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
18032             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
18033             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
18034             break;
18035         }
18036     }
18037 
18038     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
18039           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
18040 }
18041 
18042 static void
18043 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
18044 {
18045     struct pbf_pN_cmd_regs cmd_regs[] = {
18046         {0, (CHIP_IS_E3B0(sc)) ?
18047             PBF_REG_TQ_OCCUPANCY_Q0 :
18048             PBF_REG_P0_TQ_OCCUPANCY,
18049             (CHIP_IS_E3B0(sc)) ?
18050             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
18051             PBF_REG_P0_TQ_LINES_FREED_CNT},
18052         {1, (CHIP_IS_E3B0(sc)) ?
18053             PBF_REG_TQ_OCCUPANCY_Q1 :
18054             PBF_REG_P1_TQ_OCCUPANCY,
18055             (CHIP_IS_E3B0(sc)) ?
18056             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
18057             PBF_REG_P1_TQ_LINES_FREED_CNT},
18058         {4, (CHIP_IS_E3B0(sc)) ?
18059             PBF_REG_TQ_OCCUPANCY_LB_Q :
18060             PBF_REG_P4_TQ_OCCUPANCY,
18061             (CHIP_IS_E3B0(sc)) ?
18062             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
18063             PBF_REG_P4_TQ_LINES_FREED_CNT}
18064     };
18065 
18066     struct pbf_pN_buf_regs buf_regs[] = {
18067         {0, (CHIP_IS_E3B0(sc)) ?
18068             PBF_REG_INIT_CRD_Q0 :
18069             PBF_REG_P0_INIT_CRD ,
18070             (CHIP_IS_E3B0(sc)) ?
18071             PBF_REG_CREDIT_Q0 :
18072             PBF_REG_P0_CREDIT,
18073             (CHIP_IS_E3B0(sc)) ?
18074             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
18075             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
18076         {1, (CHIP_IS_E3B0(sc)) ?
18077             PBF_REG_INIT_CRD_Q1 :
18078             PBF_REG_P1_INIT_CRD,
18079             (CHIP_IS_E3B0(sc)) ?
18080             PBF_REG_CREDIT_Q1 :
18081             PBF_REG_P1_CREDIT,
18082             (CHIP_IS_E3B0(sc)) ?
18083             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
18084             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
18085         {4, (CHIP_IS_E3B0(sc)) ?
18086             PBF_REG_INIT_CRD_LB_Q :
18087             PBF_REG_P4_INIT_CRD,
18088             (CHIP_IS_E3B0(sc)) ?
18089             PBF_REG_CREDIT_LB_Q :
18090             PBF_REG_P4_CREDIT,
18091             (CHIP_IS_E3B0(sc)) ?
18092             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
18093             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
18094     };
18095 
18096     int i;
18097 
18098     /* Verify the command queues are flushed P0, P1, P4 */
18099     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
18100         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
18101     }
18102 
18103     /* Verify the transmission buffers are flushed P0, P1, P4 */
18104     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
18105         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
18106     }
18107 }
18108 
18109 static void
18110 bxe_hw_enable_status(struct bxe_softc *sc)
18111 {
18112     uint32_t val;
18113 
18114     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
18115     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
18116 
18117     val = REG_RD(sc, PBF_REG_DISABLE_PF);
18118     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
18119 
18120     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
18121     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
18122 
18123     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
18124     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
18125 
18126     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
18127     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
18128 
18129     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
18130     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
18131 
18132     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
18133     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
18134 
18135     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
18136     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
18137 }
18138 
18139 static int
18140 bxe_pf_flr_clnup(struct bxe_softc *sc)
18141 {
18142     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
18143 
18144     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
18145 
18146     /* Re-enable PF target read access */
18147     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
18148 
18149     /* Poll HW usage counters */
18150     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
18151     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
18152         return (-1);
18153     }
18154 
18155     /* Zero the igu 'trailing edge' and 'leading edge' */
18156 
18157     /* Send the FW cleanup command */
18158     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
18159         return (-1);
18160     }
18161 
18162     /* ATC cleanup */
18163 
18164     /* Verify TX hw is flushed */
18165     bxe_tx_hw_flushed(sc, poll_cnt);
18166 
18167     /* Wait 100ms (not adjusted according to platform) */
18168     DELAY(100000);
18169 
18170     /* Verify no pending pci transactions */
18171     if (bxe_is_pcie_pending(sc)) {
18172         BLOGE(sc, "PCIE Transactions still pending\n");
18173     }
18174 
18175     /* Debug */
18176     bxe_hw_enable_status(sc);
18177 
18178     /*
18179      * Master enable - Due to WB DMAE writes performed before this
18180      * register is re-initialized as part of the regular function init
18181      */
18182     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18183 
18184     return (0);
18185 }
18186 
18187 static int
18188 bxe_init_hw_func(struct bxe_softc *sc)
18189 {
18190     int port = SC_PORT(sc);
18191     int func = SC_FUNC(sc);
18192     int init_phase = PHASE_PF0 + func;
18193     struct ecore_ilt *ilt = sc->ilt;
18194     uint16_t cdu_ilt_start;
18195     uint32_t addr, val;
18196     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
18197     int i, main_mem_width, rc;
18198 
18199     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
18200 
18201     /* FLR cleanup */
18202     if (!CHIP_IS_E1x(sc)) {
18203         rc = bxe_pf_flr_clnup(sc);
18204         if (rc) {
18205             BLOGE(sc, "FLR cleanup failed!\n");
18206             // XXX bxe_fw_dump(sc);
18207             // XXX bxe_idle_chk(sc);
18208             return (rc);
18209         }
18210     }
18211 
18212     /* set MSI reconfigure capability */
18213     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18214         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
18215         val = REG_RD(sc, addr);
18216         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
18217         REG_WR(sc, addr, val);
18218     }
18219 
18220     ecore_init_block(sc, BLOCK_PXP, init_phase);
18221     ecore_init_block(sc, BLOCK_PXP2, init_phase);
18222 
18223     ilt = sc->ilt;
18224     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
18225 
18226     for (i = 0; i < L2_ILT_LINES(sc); i++) {
18227         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
18228         ilt->lines[cdu_ilt_start + i].page_mapping =
18229             sc->context[i].vcxt_dma.paddr;
18230         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
18231     }
18232     ecore_ilt_init_op(sc, INITOP_SET);
18233 
18234     /* Set NIC mode */
18235     REG_WR(sc, PRS_REG_NIC_MODE, 1);
18236     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
18237 
18238     if (!CHIP_IS_E1x(sc)) {
18239         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
18240 
18241         /* Turn on a single ISR mode in IGU if driver is going to use
18242          * INT#x or MSI
18243          */
18244         if (sc->interrupt_mode != INTR_MODE_MSIX) {
18245             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
18246         }
18247 
18248         /*
18249          * Timers workaround bug: function init part.
18250          * Need to wait 20msec after initializing ILT,
18251          * needed to make sure there are no requests in
18252          * one of the PXP internal queues with "old" ILT addresses
18253          */
18254         DELAY(20000);
18255 
18256         /*
18257          * Master enable - Due to WB DMAE writes performed before this
18258          * register is re-initialized as part of the regular function
18259          * init
18260          */
18261         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
18262         /* Enable the function in IGU */
18263         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
18264     }
18265 
18266     sc->dmae_ready = 1;
18267 
18268     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
18269 
18270     if (!CHIP_IS_E1x(sc))
18271         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
18272 
18273     ecore_init_block(sc, BLOCK_ATC, init_phase);
18274     ecore_init_block(sc, BLOCK_DMAE, init_phase);
18275     ecore_init_block(sc, BLOCK_NIG, init_phase);
18276     ecore_init_block(sc, BLOCK_SRC, init_phase);
18277     ecore_init_block(sc, BLOCK_MISC, init_phase);
18278     ecore_init_block(sc, BLOCK_TCM, init_phase);
18279     ecore_init_block(sc, BLOCK_UCM, init_phase);
18280     ecore_init_block(sc, BLOCK_CCM, init_phase);
18281     ecore_init_block(sc, BLOCK_XCM, init_phase);
18282     ecore_init_block(sc, BLOCK_TSEM, init_phase);
18283     ecore_init_block(sc, BLOCK_USEM, init_phase);
18284     ecore_init_block(sc, BLOCK_CSEM, init_phase);
18285     ecore_init_block(sc, BLOCK_XSEM, init_phase);
18286 
18287     if (!CHIP_IS_E1x(sc))
18288         REG_WR(sc, QM_REG_PF_EN, 1);
18289 
18290     if (!CHIP_IS_E1x(sc)) {
18291         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18292         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18293         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18294         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
18295     }
18296     ecore_init_block(sc, BLOCK_QM, init_phase);
18297 
18298     ecore_init_block(sc, BLOCK_TM, init_phase);
18299     ecore_init_block(sc, BLOCK_DORQ, init_phase);
18300 
18301     bxe_iov_init_dq(sc);
18302 
18303     ecore_init_block(sc, BLOCK_BRB1, init_phase);
18304     ecore_init_block(sc, BLOCK_PRS, init_phase);
18305     ecore_init_block(sc, BLOCK_TSDM, init_phase);
18306     ecore_init_block(sc, BLOCK_CSDM, init_phase);
18307     ecore_init_block(sc, BLOCK_USDM, init_phase);
18308     ecore_init_block(sc, BLOCK_XSDM, init_phase);
18309     ecore_init_block(sc, BLOCK_UPB, init_phase);
18310     ecore_init_block(sc, BLOCK_XPB, init_phase);
18311     ecore_init_block(sc, BLOCK_PBF, init_phase);
18312     if (!CHIP_IS_E1x(sc))
18313         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
18314 
18315     ecore_init_block(sc, BLOCK_CDU, init_phase);
18316 
18317     ecore_init_block(sc, BLOCK_CFC, init_phase);
18318 
18319     if (!CHIP_IS_E1x(sc))
18320         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
18321 
18322     if (IS_MF(sc)) {
18323         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
18324         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
18325     }
18326 
18327     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18328 
18329     /* HC init per function */
18330     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18331         if (CHIP_IS_E1H(sc)) {
18332             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18333 
18334             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18335             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18336         }
18337         ecore_init_block(sc, BLOCK_HC, init_phase);
18338 
18339     } else {
18340         int num_segs, sb_idx, prod_offset;
18341 
18342         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18343 
18344         if (!CHIP_IS_E1x(sc)) {
18345             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18346             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18347         }
18348 
18349         ecore_init_block(sc, BLOCK_IGU, init_phase);
18350 
18351         if (!CHIP_IS_E1x(sc)) {
18352             int dsb_idx = 0;
18353             /**
18354              * Producer memory:
18355              * E2 mode: address 0-135 match to the mapping memory;
18356              * 136 - PF0 default prod; 137 - PF1 default prod;
18357              * 138 - PF2 default prod; 139 - PF3 default prod;
18358              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18359              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18360              * 144-147 reserved.
18361              *
18362              * E1.5 mode - In backward compatible mode;
18363              * for non default SB; each even line in the memory
18364              * holds the U producer and each odd line hold
18365              * the C producer. The first 128 producers are for
18366              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18367              * producers are for the DSB for each PF.
18368              * Each PF has five segments: (the order inside each
18369              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18370              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18371              * 144-147 attn prods;
18372              */
18373             /* non-default-status-blocks */
18374             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18375                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18376             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18377                 prod_offset = (sc->igu_base_sb + sb_idx) *
18378                     num_segs;
18379 
18380                 for (i = 0; i < num_segs; i++) {
18381                     addr = IGU_REG_PROD_CONS_MEMORY +
18382                             (prod_offset + i) * 4;
18383                     REG_WR(sc, addr, 0);
18384                 }
18385                 /* send consumer update with value 0 */
18386                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18387                            USTORM_ID, 0, IGU_INT_NOP, 1);
18388                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18389             }
18390 
18391             /* default-status-blocks */
18392             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18393                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18394 
18395             if (CHIP_IS_MODE_4_PORT(sc))
18396                 dsb_idx = SC_FUNC(sc);
18397             else
18398                 dsb_idx = SC_VN(sc);
18399 
18400             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18401                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18402                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18403 
18404             /*
18405              * igu prods come in chunks of E1HVN_MAX (4) -
18406              * does not matters what is the current chip mode
18407              */
18408             for (i = 0; i < (num_segs * E1HVN_MAX);
18409                  i += E1HVN_MAX) {
18410                 addr = IGU_REG_PROD_CONS_MEMORY +
18411                             (prod_offset + i)*4;
18412                 REG_WR(sc, addr, 0);
18413             }
18414             /* send consumer update with 0 */
18415             if (CHIP_INT_MODE_IS_BC(sc)) {
18416                 bxe_ack_sb(sc, sc->igu_dsb_id,
18417                            USTORM_ID, 0, IGU_INT_NOP, 1);
18418                 bxe_ack_sb(sc, sc->igu_dsb_id,
18419                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18420                 bxe_ack_sb(sc, sc->igu_dsb_id,
18421                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18422                 bxe_ack_sb(sc, sc->igu_dsb_id,
18423                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18424                 bxe_ack_sb(sc, sc->igu_dsb_id,
18425                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18426             } else {
18427                 bxe_ack_sb(sc, sc->igu_dsb_id,
18428                            USTORM_ID, 0, IGU_INT_NOP, 1);
18429                 bxe_ack_sb(sc, sc->igu_dsb_id,
18430                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18431             }
18432             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18433 
18434             /* !!! these should become driver const once
18435                rf-tool supports split-68 const */
18436             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18437             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18438             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18439             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18440             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18441             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18442         }
18443     }
18444 
18445     /* Reset PCIE errors for debug */
18446     REG_WR(sc, 0x2114, 0xffffffff);
18447     REG_WR(sc, 0x2120, 0xffffffff);
18448 
18449     if (CHIP_IS_E1x(sc)) {
18450         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18451         main_mem_base = HC_REG_MAIN_MEMORY +
18452                 SC_PORT(sc) * (main_mem_size * 4);
18453         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18454         main_mem_width = 8;
18455 
18456         val = REG_RD(sc, main_mem_prty_clr);
18457         if (val) {
18458             BLOGD(sc, DBG_LOAD,
18459                   "Parity errors in HC block during function init (0x%x)!\n",
18460                   val);
18461         }
18462 
18463         /* Clear "false" parity errors in MSI-X table */
18464         for (i = main_mem_base;
18465              i < main_mem_base + main_mem_size * 4;
18466              i += main_mem_width) {
18467             bxe_read_dmae(sc, i, main_mem_width / 4);
18468             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18469                            i, main_mem_width / 4);
18470         }
18471         /* Clear HC parity attention */
18472         REG_RD(sc, main_mem_prty_clr);
18473     }
18474 
18475 #if 1
18476     /* Enable STORMs SP logging */
18477     REG_WR8(sc, BAR_USTRORM_INTMEM +
18478            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18479     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18480            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18481     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18482            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18483     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18484            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18485 #endif
18486 
18487     elink_phy_probe(&sc->link_params);
18488 
18489     return (0);
18490 }
18491 
18492 static void
18493 bxe_link_reset(struct bxe_softc *sc)
18494 {
18495     if (!BXE_NOMCP(sc)) {
18496 	bxe_acquire_phy_lock(sc);
18497         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18498 	bxe_release_phy_lock(sc);
18499     } else {
18500         if (!CHIP_REV_IS_SLOW(sc)) {
18501             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18502         }
18503     }
18504 }
18505 
18506 static void
18507 bxe_reset_port(struct bxe_softc *sc)
18508 {
18509     int port = SC_PORT(sc);
18510     uint32_t val;
18511 
18512 	ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18513     /* reset physical Link */
18514     bxe_link_reset(sc);
18515 
18516     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18517 
18518     /* Do not rcv packets to BRB */
18519     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18520     /* Do not direct rcv packets that are not for MCP to the BRB */
18521     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18522                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18523 
18524     /* Configure AEU */
18525     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18526 
18527     DELAY(100000);
18528 
18529     /* Check for BRB port occupancy */
18530     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18531     if (val) {
18532         BLOGD(sc, DBG_LOAD,
18533               "BRB1 is not empty, %d blocks are occupied\n", val);
18534     }
18535 
18536     /* TODO: Close Doorbell port? */
18537 }
18538 
18539 static void
18540 bxe_ilt_wr(struct bxe_softc *sc,
18541            uint32_t         index,
18542            bus_addr_t       addr)
18543 {
18544     int reg;
18545     uint32_t wb_write[2];
18546 
18547     if (CHIP_IS_E1(sc)) {
18548         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18549     } else {
18550         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18551     }
18552 
18553     wb_write[0] = ONCHIP_ADDR1(addr);
18554     wb_write[1] = ONCHIP_ADDR2(addr);
18555     REG_WR_DMAE(sc, reg, wb_write, 2);
18556 }
18557 
18558 static void
18559 bxe_clear_func_ilt(struct bxe_softc *sc,
18560                    uint32_t         func)
18561 {
18562     uint32_t i, base = FUNC_ILT_BASE(func);
18563     for (i = base; i < base + ILT_PER_FUNC; i++) {
18564         bxe_ilt_wr(sc, i, 0);
18565     }
18566 }
18567 
18568 static void
18569 bxe_reset_func(struct bxe_softc *sc)
18570 {
18571     struct bxe_fastpath *fp;
18572     int port = SC_PORT(sc);
18573     int func = SC_FUNC(sc);
18574     int i;
18575 
18576     /* Disable the function in the FW */
18577     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18578     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18579     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18580     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18581 
18582     /* FP SBs */
18583     FOR_EACH_ETH_QUEUE(sc, i) {
18584         fp = &sc->fp[i];
18585         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18586                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18587                 SB_DISABLED);
18588     }
18589 
18590     /* SP SB */
18591     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18592             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18593             SB_DISABLED);
18594 
18595     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18596         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18597     }
18598 
18599     /* Configure IGU */
18600     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18601         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18602         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18603     } else {
18604         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18605         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18606     }
18607 
18608     if (CNIC_LOADED(sc)) {
18609         /* Disable Timer scan */
18610         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18611         /*
18612          * Wait for at least 10ms and up to 2 second for the timers
18613          * scan to complete
18614          */
18615         for (i = 0; i < 200; i++) {
18616             DELAY(10000);
18617             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18618                 break;
18619         }
18620     }
18621 
18622     /* Clear ILT */
18623     bxe_clear_func_ilt(sc, func);
18624 
18625     /*
18626      * Timers workaround bug for E2: if this is vnic-3,
18627      * we need to set the entire ilt range for this timers.
18628      */
18629     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18630         struct ilt_client_info ilt_cli;
18631         /* use dummy TM client */
18632         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18633         ilt_cli.start = 0;
18634         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18635         ilt_cli.client_num = ILT_CLIENT_TM;
18636 
18637         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18638     }
18639 
18640     /* this assumes that reset_port() called before reset_func()*/
18641     if (!CHIP_IS_E1x(sc)) {
18642         bxe_pf_disable(sc);
18643     }
18644 
18645     sc->dmae_ready = 0;
18646 }
18647 
18648 static int
18649 bxe_gunzip_init(struct bxe_softc *sc)
18650 {
18651     return (0);
18652 }
18653 
18654 static void
18655 bxe_gunzip_end(struct bxe_softc *sc)
18656 {
18657     return;
18658 }
18659 
18660 static int
18661 bxe_init_firmware(struct bxe_softc *sc)
18662 {
18663     if (CHIP_IS_E1(sc)) {
18664         ecore_init_e1_firmware(sc);
18665         sc->iro_array = e1_iro_arr;
18666     } else if (CHIP_IS_E1H(sc)) {
18667         ecore_init_e1h_firmware(sc);
18668         sc->iro_array = e1h_iro_arr;
18669     } else if (!CHIP_IS_E1x(sc)) {
18670         ecore_init_e2_firmware(sc);
18671         sc->iro_array = e2_iro_arr;
18672     } else {
18673         BLOGE(sc, "Unsupported chip revision\n");
18674         return (-1);
18675     }
18676 
18677     return (0);
18678 }
18679 
18680 static void
18681 bxe_release_firmware(struct bxe_softc *sc)
18682 {
18683     /* Do nothing */
18684     return;
18685 }
18686 
18687 static int
18688 ecore_gunzip(struct bxe_softc *sc,
18689              const uint8_t    *zbuf,
18690              int              len)
18691 {
18692     /* XXX : Implement... */
18693     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18694     return (FALSE);
18695 }
18696 
18697 static void
18698 ecore_reg_wr_ind(struct bxe_softc *sc,
18699                  uint32_t         addr,
18700                  uint32_t         val)
18701 {
18702     bxe_reg_wr_ind(sc, addr, val);
18703 }
18704 
18705 static void
18706 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18707                           bus_addr_t       phys_addr,
18708                           uint32_t         addr,
18709                           uint32_t         len)
18710 {
18711     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18712 }
18713 
18714 void
18715 ecore_storm_memset_struct(struct bxe_softc *sc,
18716                           uint32_t         addr,
18717                           size_t           size,
18718                           uint32_t         *data)
18719 {
18720     uint8_t i;
18721     for (i = 0; i < size/4; i++) {
18722         REG_WR(sc, addr + (i * 4), data[i]);
18723     }
18724 }
18725 
18726 
18727 /*
18728  * character device - ioctl interface definitions
18729  */
18730 
18731 
18732 #include "bxe_dump.h"
18733 #include "bxe_ioctl.h"
18734 #include <sys/conf.h>
18735 
18736 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18737                 struct thread *td);
18738 
18739 static struct cdevsw bxe_cdevsw = {
18740     .d_version = D_VERSION,
18741     .d_ioctl = bxe_eioctl,
18742     .d_name = "bxecnic",
18743 };
18744 
18745 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18746 
18747 
18748 #define DUMP_ALL_PRESETS        0x1FFF
18749 #define DUMP_MAX_PRESETS        13
18750 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18751 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18752 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18753 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18754 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18755 
18756 #define IS_REG_IN_PRESET(presets, idx)  \
18757                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18758 
18759 
18760 static int
18761 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18762 {
18763     if (CHIP_IS_E1(sc))
18764         return dump_num_registers[0][preset-1];
18765     else if (CHIP_IS_E1H(sc))
18766         return dump_num_registers[1][preset-1];
18767     else if (CHIP_IS_E2(sc))
18768         return dump_num_registers[2][preset-1];
18769     else if (CHIP_IS_E3A0(sc))
18770         return dump_num_registers[3][preset-1];
18771     else if (CHIP_IS_E3B0(sc))
18772         return dump_num_registers[4][preset-1];
18773     else
18774         return 0;
18775 }
18776 
18777 static int
18778 bxe_get_total_regs_len32(struct bxe_softc *sc)
18779 {
18780     uint32_t preset_idx;
18781     int regdump_len32 = 0;
18782 
18783 
18784     /* Calculate the total preset regs length */
18785     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18786         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18787     }
18788 
18789     return regdump_len32;
18790 }
18791 
18792 static const uint32_t *
18793 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18794 {
18795     if (CHIP_IS_E2(sc))
18796         return page_vals_e2;
18797     else if (CHIP_IS_E3(sc))
18798         return page_vals_e3;
18799     else
18800         return NULL;
18801 }
18802 
18803 static uint32_t
18804 __bxe_get_page_reg_num(struct bxe_softc *sc)
18805 {
18806     if (CHIP_IS_E2(sc))
18807         return PAGE_MODE_VALUES_E2;
18808     else if (CHIP_IS_E3(sc))
18809         return PAGE_MODE_VALUES_E3;
18810     else
18811         return 0;
18812 }
18813 
18814 static const uint32_t *
18815 __bxe_get_page_write_ar(struct bxe_softc *sc)
18816 {
18817     if (CHIP_IS_E2(sc))
18818         return page_write_regs_e2;
18819     else if (CHIP_IS_E3(sc))
18820         return page_write_regs_e3;
18821     else
18822         return NULL;
18823 }
18824 
18825 static uint32_t
18826 __bxe_get_page_write_num(struct bxe_softc *sc)
18827 {
18828     if (CHIP_IS_E2(sc))
18829         return PAGE_WRITE_REGS_E2;
18830     else if (CHIP_IS_E3(sc))
18831         return PAGE_WRITE_REGS_E3;
18832     else
18833         return 0;
18834 }
18835 
18836 static const struct reg_addr *
18837 __bxe_get_page_read_ar(struct bxe_softc *sc)
18838 {
18839     if (CHIP_IS_E2(sc))
18840         return page_read_regs_e2;
18841     else if (CHIP_IS_E3(sc))
18842         return page_read_regs_e3;
18843     else
18844         return NULL;
18845 }
18846 
18847 static uint32_t
18848 __bxe_get_page_read_num(struct bxe_softc *sc)
18849 {
18850     if (CHIP_IS_E2(sc))
18851         return PAGE_READ_REGS_E2;
18852     else if (CHIP_IS_E3(sc))
18853         return PAGE_READ_REGS_E3;
18854     else
18855         return 0;
18856 }
18857 
18858 static bool
18859 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18860 {
18861     if (CHIP_IS_E1(sc))
18862         return IS_E1_REG(reg_info->chips);
18863     else if (CHIP_IS_E1H(sc))
18864         return IS_E1H_REG(reg_info->chips);
18865     else if (CHIP_IS_E2(sc))
18866         return IS_E2_REG(reg_info->chips);
18867     else if (CHIP_IS_E3A0(sc))
18868         return IS_E3A0_REG(reg_info->chips);
18869     else if (CHIP_IS_E3B0(sc))
18870         return IS_E3B0_REG(reg_info->chips);
18871     else
18872         return 0;
18873 }
18874 
18875 static bool
18876 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18877 {
18878     if (CHIP_IS_E1(sc))
18879         return IS_E1_REG(wreg_info->chips);
18880     else if (CHIP_IS_E1H(sc))
18881         return IS_E1H_REG(wreg_info->chips);
18882     else if (CHIP_IS_E2(sc))
18883         return IS_E2_REG(wreg_info->chips);
18884     else if (CHIP_IS_E3A0(sc))
18885         return IS_E3A0_REG(wreg_info->chips);
18886     else if (CHIP_IS_E3B0(sc))
18887         return IS_E3B0_REG(wreg_info->chips);
18888     else
18889         return 0;
18890 }
18891 
18892 /**
18893  * bxe_read_pages_regs - read "paged" registers
18894  *
18895  * @bp          device handle
18896  * @p           output buffer
18897  *
18898  * Reads "paged" memories: memories that may only be read by first writing to a
18899  * specific address ("write address") and then reading from a specific address
18900  * ("read address"). There may be more than one write address per "page" and
18901  * more than one read address per write address.
18902  */
18903 static void
18904 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18905 {
18906     uint32_t i, j, k, n;
18907 
18908     /* addresses of the paged registers */
18909     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18910     /* number of paged registers */
18911     int num_pages = __bxe_get_page_reg_num(sc);
18912     /* write addresses */
18913     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18914     /* number of write addresses */
18915     int write_num = __bxe_get_page_write_num(sc);
18916     /* read addresses info */
18917     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18918     /* number of read addresses */
18919     int read_num = __bxe_get_page_read_num(sc);
18920     uint32_t addr, size;
18921 
18922     for (i = 0; i < num_pages; i++) {
18923         for (j = 0; j < write_num; j++) {
18924             REG_WR(sc, write_addr[j], page_addr[i]);
18925 
18926             for (k = 0; k < read_num; k++) {
18927                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18928                     size = read_addr[k].size;
18929                     for (n = 0; n < size; n++) {
18930                         addr = read_addr[k].addr + n*4;
18931                         *p++ = REG_RD(sc, addr);
18932                     }
18933                 }
18934             }
18935         }
18936     }
18937     return;
18938 }
18939 
18940 
18941 static int
18942 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18943 {
18944     uint32_t i, j, addr;
18945     const struct wreg_addr *wreg_addr_p = NULL;
18946 
18947     if (CHIP_IS_E1(sc))
18948         wreg_addr_p = &wreg_addr_e1;
18949     else if (CHIP_IS_E1H(sc))
18950         wreg_addr_p = &wreg_addr_e1h;
18951     else if (CHIP_IS_E2(sc))
18952         wreg_addr_p = &wreg_addr_e2;
18953     else if (CHIP_IS_E3A0(sc))
18954         wreg_addr_p = &wreg_addr_e3;
18955     else if (CHIP_IS_E3B0(sc))
18956         wreg_addr_p = &wreg_addr_e3b0;
18957     else
18958         return (-1);
18959 
18960     /* Read the idle_chk registers */
18961     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18962         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18963             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18964             for (j = 0; j < idle_reg_addrs[i].size; j++)
18965                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18966         }
18967     }
18968 
18969     /* Read the regular registers */
18970     for (i = 0; i < REGS_COUNT; i++) {
18971         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18972             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18973             for (j = 0; j < reg_addrs[i].size; j++)
18974                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18975         }
18976     }
18977 
18978     /* Read the CAM registers */
18979     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18980         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18981         for (i = 0; i < wreg_addr_p->size; i++) {
18982             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18983 
18984             /* In case of wreg_addr register, read additional
18985                registers from read_regs array
18986              */
18987             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18988                 addr = *(wreg_addr_p->read_regs);
18989                 *p++ = REG_RD(sc, addr + j*4);
18990             }
18991         }
18992     }
18993 
18994     /* Paged registers are supported in E2 & E3 only */
18995     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18996         /* Read "paged" registers */
18997         bxe_read_pages_regs(sc, p, preset);
18998     }
18999 
19000     return 0;
19001 }
19002 
19003 int
19004 bxe_grc_dump(struct bxe_softc *sc)
19005 {
19006     int rval = 0;
19007     uint32_t preset_idx;
19008     uint8_t *buf;
19009     uint32_t size;
19010     struct  dump_header *d_hdr;
19011     uint32_t i;
19012     uint32_t reg_val;
19013     uint32_t reg_addr;
19014     uint32_t cmd_offset;
19015     struct ecore_ilt *ilt = SC_ILT(sc);
19016     struct bxe_fastpath *fp;
19017     struct ilt_client_info *ilt_cli;
19018     int grc_dump_size;
19019 
19020 
19021     if (sc->grcdump_done || sc->grcdump_started)
19022 	return (rval);
19023 
19024     sc->grcdump_started = 1;
19025     BLOGI(sc, "Started collecting grcdump\n");
19026 
19027     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19028                 sizeof(struct  dump_header);
19029 
19030     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
19031 
19032     if (sc->grc_dump == NULL) {
19033         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
19034         return(ENOMEM);
19035     }
19036 
19037 
19038 
19039     /* Disable parity attentions as long as following dump may
19040      * cause false alarms by reading never written registers. We
19041      * will re-enable parity attentions right after the dump.
19042      */
19043 
19044     /* Disable parity on path 0 */
19045     bxe_pretend_func(sc, 0);
19046 
19047     ecore_disable_blocks_parity(sc);
19048 
19049     /* Disable parity on path 1 */
19050     bxe_pretend_func(sc, 1);
19051     ecore_disable_blocks_parity(sc);
19052 
19053     /* Return to current function */
19054     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
19055 
19056     buf = sc->grc_dump;
19057     d_hdr = sc->grc_dump;
19058 
19059     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
19060     d_hdr->version = BNX2X_DUMP_VERSION;
19061     d_hdr->preset = DUMP_ALL_PRESETS;
19062 
19063     if (CHIP_IS_E1(sc)) {
19064         d_hdr->dump_meta_data = DUMP_CHIP_E1;
19065     } else if (CHIP_IS_E1H(sc)) {
19066         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
19067     } else if (CHIP_IS_E2(sc)) {
19068         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
19069                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19070     } else if (CHIP_IS_E3A0(sc)) {
19071         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
19072                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19073     } else if (CHIP_IS_E3B0(sc)) {
19074         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
19075                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
19076     }
19077 
19078     buf += sizeof(struct  dump_header);
19079 
19080     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
19081 
19082         /* Skip presets with IOR */
19083         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
19084             (preset_idx == 11))
19085             continue;
19086 
19087         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
19088 
19089 	if (rval)
19090             break;
19091 
19092         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
19093 
19094         buf += size;
19095     }
19096 
19097     bxe_pretend_func(sc, 0);
19098     ecore_clear_blocks_parity(sc);
19099     ecore_enable_blocks_parity(sc);
19100 
19101     bxe_pretend_func(sc, 1);
19102     ecore_clear_blocks_parity(sc);
19103     ecore_enable_blocks_parity(sc);
19104 
19105     /* Return to current function */
19106     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
19107 
19108 
19109 
19110     if(sc->state == BXE_STATE_OPEN) {
19111         if(sc->fw_stats_req  != NULL) {
19112     		BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
19113         			(uintmax_t)sc->fw_stats_req_mapping,
19114         			(uintmax_t)sc->fw_stats_data_mapping,
19115         			sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
19116 		}
19117 		if(sc->def_sb != NULL) {
19118 			BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
19119         			(void *)sc->def_sb_dma.paddr, sc->def_sb,
19120         			sizeof(struct host_sp_status_block));
19121 		}
19122 		if(sc->eq_dma.vaddr != NULL) {
19123     		BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
19124         			(uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
19125 		}
19126 		if(sc->sp_dma.vaddr != NULL) {
19127     		BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
19128         			(uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
19129         			sizeof(struct bxe_slowpath));
19130 		}
19131 		if(sc->spq_dma.vaddr != NULL) {
19132     		BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
19133         			(uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
19134 		}
19135 		if(sc->gz_buf_dma.vaddr != NULL) {
19136     		BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
19137         			(uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
19138         			FW_BUF_SIZE);
19139 		}
19140     	for (i = 0; i < sc->num_queues; i++) {
19141         	fp = &sc->fp[i];
19142 			if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
19143                         fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
19144                         fp->rx_sge_dma.vaddr != NULL) {
19145 
19146 				BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
19147             			(uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
19148             			sizeof(union bxe_host_hc_status_block));
19149 				BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19150             			(uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
19151             			(BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
19152         		BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19153             			(uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
19154             			(BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
19155         		BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
19156             			(uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
19157             			(BCM_PAGE_SIZE * RCQ_NUM_PAGES));
19158         		BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
19159             			(uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
19160             			(BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
19161     		}
19162 		}
19163 		if(ilt != NULL ) {
19164     		ilt_cli = &ilt->clients[1];
19165 			if(ilt->lines != NULL) {
19166     		for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
19167         		BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
19168             			(uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
19169             			((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
19170     		}
19171 			}
19172 		}
19173 
19174 
19175     	cmd_offset = DMAE_REG_CMD_MEM;
19176     	for (i = 0; i < 224; i++) {
19177         	reg_addr = (cmd_offset +(i * 4));
19178         	reg_val = REG_RD(sc, reg_addr);
19179         	BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
19180             			reg_addr, reg_val);
19181     	}
19182 	}
19183 
19184     BLOGI(sc, "Collection of grcdump done\n");
19185     sc->grcdump_done = 1;
19186     return(rval);
19187 }
19188 
19189 static int
19190 bxe_add_cdev(struct bxe_softc *sc)
19191 {
19192     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
19193 
19194     if (sc->eeprom == NULL) {
19195         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
19196         return (-1);
19197     }
19198 
19199     sc->ioctl_dev = make_dev(&bxe_cdevsw,
19200                             sc->ifp->if_dunit,
19201                             UID_ROOT,
19202                             GID_WHEEL,
19203                             0600,
19204                             "%s",
19205                             if_name(sc->ifp));
19206 
19207     if (sc->ioctl_dev == NULL) {
19208         free(sc->eeprom, M_DEVBUF);
19209         sc->eeprom = NULL;
19210         return (-1);
19211     }
19212 
19213     sc->ioctl_dev->si_drv1 = sc;
19214 
19215     return (0);
19216 }
19217 
19218 static void
19219 bxe_del_cdev(struct bxe_softc *sc)
19220 {
19221     if (sc->ioctl_dev != NULL)
19222         destroy_dev(sc->ioctl_dev);
19223 
19224     if (sc->eeprom != NULL) {
19225         free(sc->eeprom, M_DEVBUF);
19226         sc->eeprom = NULL;
19227     }
19228     sc->ioctl_dev = NULL;
19229 
19230     return;
19231 }
19232 
19233 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
19234 {
19235 
19236     if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
19237         return FALSE;
19238 
19239     return TRUE;
19240 }
19241 
19242 
19243 static int
19244 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
19245 {
19246     int rval = 0;
19247 
19248     if(!bxe_is_nvram_accessible(sc)) {
19249         BLOGW(sc, "Cannot access eeprom when interface is down\n");
19250         return (-EAGAIN);
19251     }
19252     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
19253 
19254 
19255    return (rval);
19256 }
19257 
19258 static int
19259 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
19260 {
19261     int rval = 0;
19262 
19263     if(!bxe_is_nvram_accessible(sc)) {
19264         BLOGW(sc, "Cannot access eeprom when interface is down\n");
19265         return (-EAGAIN);
19266     }
19267     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
19268 
19269    return (rval);
19270 }
19271 
19272 static int
19273 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
19274 {
19275     int rval = 0;
19276 
19277     switch (eeprom->eeprom_cmd) {
19278 
19279     case BXE_EEPROM_CMD_SET_EEPROM:
19280 
19281         rval = copyin(eeprom->eeprom_data, sc->eeprom,
19282                        eeprom->eeprom_data_len);
19283 
19284         if (rval)
19285             break;
19286 
19287         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
19288                        eeprom->eeprom_data_len);
19289         break;
19290 
19291     case BXE_EEPROM_CMD_GET_EEPROM:
19292 
19293         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
19294                        eeprom->eeprom_data_len);
19295 
19296         if (rval) {
19297             break;
19298         }
19299 
19300         rval = copyout(sc->eeprom, eeprom->eeprom_data,
19301                        eeprom->eeprom_data_len);
19302         break;
19303 
19304     default:
19305             rval = EINVAL;
19306             break;
19307     }
19308 
19309     if (rval) {
19310         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
19311     }
19312 
19313     return (rval);
19314 }
19315 
19316 static int
19317 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
19318 {
19319     uint32_t ext_phy_config;
19320     int port = SC_PORT(sc);
19321     int cfg_idx = bxe_get_link_cfg_idx(sc);
19322 
19323     dev_p->supported = sc->port.supported[cfg_idx] |
19324             (sc->port.supported[cfg_idx ^ 1] &
19325             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
19326     dev_p->advertising = sc->port.advertising[cfg_idx];
19327     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
19328         ELINK_ETH_PHY_SFP_1G_FIBER) {
19329         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
19330         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
19331     }
19332     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
19333         !(sc->flags & BXE_MF_FUNC_DIS)) {
19334         dev_p->duplex = sc->link_vars.duplex;
19335         if (IS_MF(sc) && !BXE_NOMCP(sc))
19336             dev_p->speed = bxe_get_mf_speed(sc);
19337         else
19338             dev_p->speed = sc->link_vars.line_speed;
19339     } else {
19340         dev_p->duplex = DUPLEX_UNKNOWN;
19341         dev_p->speed = SPEED_UNKNOWN;
19342     }
19343 
19344     dev_p->port = bxe_media_detect(sc);
19345 
19346     ext_phy_config = SHMEM_RD(sc,
19347                          dev_info.port_hw_config[port].external_phy_config);
19348     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19349         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19350         dev_p->phy_address =  sc->port.phy_addr;
19351     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19352             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19353         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19354             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19355         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19356     else
19357         dev_p->phy_address = 0;
19358 
19359     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19360         dev_p->autoneg = AUTONEG_ENABLE;
19361     else
19362        dev_p->autoneg = AUTONEG_DISABLE;
19363 
19364 
19365     return 0;
19366 }
19367 
19368 static int
19369 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19370         struct thread *td)
19371 {
19372     struct bxe_softc    *sc;
19373     int                 rval = 0;
19374     device_t            pci_dev;
19375     bxe_grcdump_t       *dump = NULL;
19376     int grc_dump_size;
19377     bxe_drvinfo_t   *drv_infop = NULL;
19378     bxe_dev_setting_t  *dev_p;
19379     bxe_dev_setting_t  dev_set;
19380     bxe_get_regs_t  *reg_p;
19381     bxe_reg_rdw_t *reg_rdw_p;
19382     bxe_pcicfg_rdw_t *cfg_rdw_p;
19383     bxe_perm_mac_addr_t *mac_addr_p;
19384 
19385 
19386     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19387         return ENXIO;
19388 
19389     pci_dev= sc->dev;
19390 
19391     dump = (bxe_grcdump_t *)data;
19392 
19393     switch(cmd) {
19394 
19395         case BXE_GRC_DUMP_SIZE:
19396             dump->pci_func = sc->pcie_func;
19397             dump->grcdump_size =
19398                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19399                      sizeof(struct  dump_header);
19400             break;
19401 
19402         case BXE_GRC_DUMP:
19403 
19404             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19405                                 sizeof(struct  dump_header);
19406             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19407                 (dump->grcdump_size < grc_dump_size)) {
19408                 rval = EINVAL;
19409                 break;
19410             }
19411 
19412             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19413                 (!sc->grcdump_started)) {
19414                 rval =  bxe_grc_dump(sc);
19415             }
19416 
19417             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19418                 (sc->grc_dump != NULL))  {
19419                 dump->grcdump_dwords = grc_dump_size >> 2;
19420                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19421                 free(sc->grc_dump, M_DEVBUF);
19422                 sc->grc_dump = NULL;
19423                 sc->grcdump_started = 0;
19424                 sc->grcdump_done = 0;
19425             }
19426 
19427             break;
19428 
19429         case BXE_DRV_INFO:
19430             drv_infop = (bxe_drvinfo_t *)data;
19431             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19432             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19433                 BXE_DRIVER_VERSION);
19434             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19435                 sc->devinfo.bc_ver_str);
19436             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19437                 "%s", sc->fw_ver_str);
19438             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19439             drv_infop->reg_dump_len =
19440                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19441                     + sizeof(struct  dump_header);
19442             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19443                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19444             break;
19445 
19446         case BXE_DEV_SETTING:
19447             dev_p = (bxe_dev_setting_t *)data;
19448             bxe_get_settings(sc, &dev_set);
19449             dev_p->supported = dev_set.supported;
19450             dev_p->advertising = dev_set.advertising;
19451             dev_p->speed = dev_set.speed;
19452             dev_p->duplex = dev_set.duplex;
19453             dev_p->port = dev_set.port;
19454             dev_p->phy_address = dev_set.phy_address;
19455             dev_p->autoneg = dev_set.autoneg;
19456 
19457             break;
19458 
19459         case BXE_GET_REGS:
19460 
19461             reg_p = (bxe_get_regs_t *)data;
19462             grc_dump_size = reg_p->reg_buf_len;
19463 
19464             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19465                 bxe_grc_dump(sc);
19466             }
19467             if((sc->grcdump_done) && (sc->grcdump_started) &&
19468                 (sc->grc_dump != NULL))  {
19469                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19470                 free(sc->grc_dump, M_DEVBUF);
19471                 sc->grc_dump = NULL;
19472                 sc->grcdump_started = 0;
19473                 sc->grcdump_done = 0;
19474             }
19475 
19476             break;
19477 
19478         case BXE_RDW_REG:
19479             reg_rdw_p = (bxe_reg_rdw_t *)data;
19480             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19481                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19482                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19483 
19484             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19485                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19486                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19487 
19488             break;
19489 
19490         case BXE_RDW_PCICFG:
19491             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19492             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19493 
19494                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19495                                          cfg_rdw_p->cfg_width);
19496 
19497             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19498                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19499                             cfg_rdw_p->cfg_width);
19500             } else {
19501                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19502             }
19503             break;
19504 
19505         case BXE_MAC_ADDR:
19506             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19507             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19508                 sc->mac_addr_str);
19509             break;
19510 
19511         case BXE_EEPROM:
19512             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19513             break;
19514 
19515 
19516         default:
19517             break;
19518     }
19519 
19520     return (rval);
19521 }
19522 
19523 #ifdef DEBUGNET
19524 static void
19525 bxe_debugnet_init(struct ifnet *ifp, int *nrxr, int *ncl, int *clsize)
19526 {
19527 	struct bxe_softc *sc;
19528 
19529 	sc = if_getsoftc(ifp);
19530 	BXE_CORE_LOCK(sc);
19531 	*nrxr = sc->num_queues;
19532 	*ncl = DEBUGNET_MAX_IN_FLIGHT;
19533 	*clsize = sc->fp[0].mbuf_alloc_size;
19534 	BXE_CORE_UNLOCK(sc);
19535 }
19536 
19537 static void
19538 bxe_debugnet_event(struct ifnet *ifp __unused, enum debugnet_ev event __unused)
19539 {
19540 }
19541 
19542 static int
19543 bxe_debugnet_transmit(struct ifnet *ifp, struct mbuf *m)
19544 {
19545 	struct bxe_softc *sc;
19546 	int error;
19547 
19548 	sc = if_getsoftc(ifp);
19549 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
19550 	    IFF_DRV_RUNNING || !sc->link_vars.link_up)
19551 		return (ENOENT);
19552 
19553 	error = bxe_tx_encap(&sc->fp[0], &m);
19554 	if (error != 0 && m != NULL)
19555 		m_freem(m);
19556 	return (error);
19557 }
19558 
19559 static int
19560 bxe_debugnet_poll(struct ifnet *ifp, int count)
19561 {
19562 	struct bxe_softc *sc;
19563 	int i;
19564 
19565 	sc = if_getsoftc(ifp);
19566 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0 ||
19567 	    !sc->link_vars.link_up)
19568 		return (ENOENT);
19569 
19570 	for (i = 0; i < sc->num_queues; i++)
19571 		(void)bxe_rxeof(sc, &sc->fp[i]);
19572 	(void)bxe_txeof(sc, &sc->fp[0]);
19573 	return (0);
19574 }
19575 #endif /* DEBUGNET */
19576