]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/bxe/bxe.c
Revert and redo r306083.
[FreeBSD/FreeBSD.git] / sys / dev / bxe / bxe.c
1 /*-
2  * Copyright (c) 2007-2014 QLogic Corporation. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS'
15  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
18  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
24  * THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #define BXE_DRIVER_VERSION "1.78.81"
31
32 #include "bxe.h"
33 #include "ecore_sp.h"
34 #include "ecore_init.h"
35 #include "ecore_init_ops.h"
36
37 #include "57710_int_offsets.h"
38 #include "57711_int_offsets.h"
39 #include "57712_int_offsets.h"
40
41 /*
42  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
43  * explicitly here for older kernels that don't include this changeset.
44  */
45 #ifndef CTLTYPE_U64
46 #define CTLTYPE_U64      CTLTYPE_QUAD
47 #define sysctl_handle_64 sysctl_handle_quad
48 #endif
49
50 /*
51  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
52  * here as zero(0) for older kernels that don't include this changeset
53  * thereby masking the functionality.
54  */
55 #ifndef CSUM_TCP_IPV6
56 #define CSUM_TCP_IPV6 0
57 #define CSUM_UDP_IPV6 0
58 #endif
59
60 /*
61  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
62  * for older kernels that don't include this changeset.
63  */
64 #if __FreeBSD_version < 900035
65 #define pci_find_cap pci_find_extcap
66 #endif
67
68 #define BXE_DEF_SB_ATT_IDX 0x0001
69 #define BXE_DEF_SB_IDX     0x0002
70
71 /*
72  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
73  * function HW initialization.
74  */
75 #define FLR_WAIT_USEC     10000 /* 10 msecs */
76 #define FLR_WAIT_INTERVAL 50    /* usecs */
77 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
78
79 struct pbf_pN_buf_regs {
80     int pN;
81     uint32_t init_crd;
82     uint32_t crd;
83     uint32_t crd_freed;
84 };
85
86 struct pbf_pN_cmd_regs {
87     int pN;
88     uint32_t lines_occup;
89     uint32_t lines_freed;
90 };
91
92 /*
93  * PCI Device ID Table used by bxe_probe().
94  */
95 #define BXE_DEVDESC_MAX 64
96 static struct bxe_device_type bxe_devs[] = {
97     {
98         BRCM_VENDORID,
99         CHIP_NUM_57710,
100         PCI_ANY_ID, PCI_ANY_ID,
101         "QLogic NetXtreme II BCM57710 10GbE"
102     },
103     {
104         BRCM_VENDORID,
105         CHIP_NUM_57711,
106         PCI_ANY_ID, PCI_ANY_ID,
107         "QLogic NetXtreme II BCM57711 10GbE"
108     },
109     {
110         BRCM_VENDORID,
111         CHIP_NUM_57711E,
112         PCI_ANY_ID, PCI_ANY_ID,
113         "QLogic NetXtreme II BCM57711E 10GbE"
114     },
115     {
116         BRCM_VENDORID,
117         CHIP_NUM_57712,
118         PCI_ANY_ID, PCI_ANY_ID,
119         "QLogic NetXtreme II BCM57712 10GbE"
120     },
121     {
122         BRCM_VENDORID,
123         CHIP_NUM_57712_MF,
124         PCI_ANY_ID, PCI_ANY_ID,
125         "QLogic NetXtreme II BCM57712 MF 10GbE"
126     },
127     {
128         BRCM_VENDORID,
129         CHIP_NUM_57800,
130         PCI_ANY_ID, PCI_ANY_ID,
131         "QLogic NetXtreme II BCM57800 10GbE"
132     },
133     {
134         BRCM_VENDORID,
135         CHIP_NUM_57800_MF,
136         PCI_ANY_ID, PCI_ANY_ID,
137         "QLogic NetXtreme II BCM57800 MF 10GbE"
138     },
139     {
140         BRCM_VENDORID,
141         CHIP_NUM_57810,
142         PCI_ANY_ID, PCI_ANY_ID,
143         "QLogic NetXtreme II BCM57810 10GbE"
144     },
145     {
146         BRCM_VENDORID,
147         CHIP_NUM_57810_MF,
148         PCI_ANY_ID, PCI_ANY_ID,
149         "QLogic NetXtreme II BCM57810 MF 10GbE"
150     },
151     {
152         BRCM_VENDORID,
153         CHIP_NUM_57811,
154         PCI_ANY_ID, PCI_ANY_ID,
155         "QLogic NetXtreme II BCM57811 10GbE"
156     },
157     {
158         BRCM_VENDORID,
159         CHIP_NUM_57811_MF,
160         PCI_ANY_ID, PCI_ANY_ID,
161         "QLogic NetXtreme II BCM57811 MF 10GbE"
162     },
163     {
164         BRCM_VENDORID,
165         CHIP_NUM_57840_4_10,
166         PCI_ANY_ID, PCI_ANY_ID,
167         "QLogic NetXtreme II BCM57840 4x10GbE"
168     },
169     {
170         BRCM_VENDORID,
171         CHIP_NUM_57840_MF,
172         PCI_ANY_ID, PCI_ANY_ID,
173         "QLogic NetXtreme II BCM57840 MF 10GbE"
174     },
175     {
176         0, 0, 0, 0, NULL
177     }
178 };
179
180 MALLOC_DECLARE(M_BXE_ILT);
181 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
182
183 /*
184  * FreeBSD device entry points.
185  */
186 static int bxe_probe(device_t);
187 static int bxe_attach(device_t);
188 static int bxe_detach(device_t);
189 static int bxe_shutdown(device_t);
190
191 /*
192  * FreeBSD KLD module/device interface event handler method.
193  */
194 static device_method_t bxe_methods[] = {
195     /* Device interface (device_if.h) */
196     DEVMETHOD(device_probe,     bxe_probe),
197     DEVMETHOD(device_attach,    bxe_attach),
198     DEVMETHOD(device_detach,    bxe_detach),
199     DEVMETHOD(device_shutdown,  bxe_shutdown),
200     /* Bus interface (bus_if.h) */
201     DEVMETHOD(bus_print_child,  bus_generic_print_child),
202     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
203     KOBJMETHOD_END
204 };
205
206 /*
207  * FreeBSD KLD Module data declaration
208  */
209 static driver_t bxe_driver = {
210     "bxe",                   /* module name */
211     bxe_methods,             /* event handler */
212     sizeof(struct bxe_softc) /* extra data */
213 };
214
215 /*
216  * FreeBSD dev class is needed to manage dev instances and
217  * to associate with a bus type
218  */
219 static devclass_t bxe_devclass;
220
221 MODULE_DEPEND(bxe, pci, 1, 1, 1);
222 MODULE_DEPEND(bxe, ether, 1, 1, 1);
223 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
224
225 /* resources needed for unloading a previously loaded device */
226
227 #define BXE_PREV_WAIT_NEEDED 1
228 struct mtx bxe_prev_mtx;
229 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
230 struct bxe_prev_list_node {
231     LIST_ENTRY(bxe_prev_list_node) node;
232     uint8_t bus;
233     uint8_t slot;
234     uint8_t path;
235     uint8_t aer; /* XXX automatic error recovery */
236     uint8_t undi;
237 };
238 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
239
240 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
241
242 /* Tunable device values... */
243
244 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
245
246 /* Debug */
247 unsigned long bxe_debug = 0;
248 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, CTLFLAG_RDTUN,
249              &bxe_debug, 0, "Debug logging mode");
250
251 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
252 static int bxe_interrupt_mode = INTR_MODE_MSIX;
253 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
254            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
255
256 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
257 static int bxe_queue_count = 4;
258 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
259            &bxe_queue_count, 0, "Multi-Queue queue count");
260
261 /* max number of buffers per queue (default RX_BD_USABLE) */
262 static int bxe_max_rx_bufs = 0;
263 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
264            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
265
266 /* Host interrupt coalescing RX tick timer (usecs) */
267 static int bxe_hc_rx_ticks = 25;
268 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
269            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
270
271 /* Host interrupt coalescing TX tick timer (usecs) */
272 static int bxe_hc_tx_ticks = 50;
273 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
274            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
275
276 /* Maximum number of Rx packets to process at a time */
277 static int bxe_rx_budget = 0xffffffff;
278 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
279            &bxe_rx_budget, 0, "Rx processing budget");
280
281 /* Maximum LRO aggregation size */
282 static int bxe_max_aggregation_size = 0;
283 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
284            &bxe_max_aggregation_size, 0, "max aggregation size");
285
286 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
287 static int bxe_mrrs = -1;
288 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
289            &bxe_mrrs, 0, "PCIe maximum read request size");
290
291 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
292 static int bxe_autogreeen = 0;
293 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
294            &bxe_autogreeen, 0, "AutoGrEEEn support");
295
296 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
297 static int bxe_udp_rss = 0;
298 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
299            &bxe_udp_rss, 0, "UDP RSS support");
300
301
302 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
303
304 #define STATS_OFFSET32(stat_name)                   \
305     (offsetof(struct bxe_eth_stats, stat_name) / 4)
306
307 #define Q_STATS_OFFSET32(stat_name)                   \
308     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
309
310 static const struct {
311     uint32_t offset;
312     uint32_t size;
313     uint32_t flags;
314 #define STATS_FLAGS_PORT  1
315 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
316 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
317     char string[STAT_NAME_LEN];
318 } bxe_eth_stats_arr[] = {
319     { STATS_OFFSET32(total_bytes_received_hi),
320                 8, STATS_FLAGS_BOTH, "rx_bytes" },
321     { STATS_OFFSET32(error_bytes_received_hi),
322                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
323     { STATS_OFFSET32(total_unicast_packets_received_hi),
324                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
325     { STATS_OFFSET32(total_multicast_packets_received_hi),
326                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
327     { STATS_OFFSET32(total_broadcast_packets_received_hi),
328                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
329     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
330                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
331     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
332                 8, STATS_FLAGS_PORT, "rx_align_errors" },
333     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
334                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
335     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
336                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
337     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
338                 8, STATS_FLAGS_PORT, "rx_fragments" },
339     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
340                 8, STATS_FLAGS_PORT, "rx_jabbers" },
341     { STATS_OFFSET32(no_buff_discard_hi),
342                 8, STATS_FLAGS_BOTH, "rx_discards" },
343     { STATS_OFFSET32(mac_filter_discard),
344                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
345     { STATS_OFFSET32(mf_tag_discard),
346                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
347     { STATS_OFFSET32(pfc_frames_received_hi),
348                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
349     { STATS_OFFSET32(pfc_frames_sent_hi),
350                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
351     { STATS_OFFSET32(brb_drop_hi),
352                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
353     { STATS_OFFSET32(brb_truncate_hi),
354                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
355     { STATS_OFFSET32(pause_frames_received_hi),
356                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
357     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
358                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
359     { STATS_OFFSET32(nig_timer_max),
360                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
361     { STATS_OFFSET32(total_bytes_transmitted_hi),
362                 8, STATS_FLAGS_BOTH, "tx_bytes" },
363     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
364                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
365     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
366                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
367     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
368                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
369     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
370                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
371     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
372                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
373     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
374                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
375     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
376                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
377     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
378                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
379     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
380                 8, STATS_FLAGS_PORT, "tx_deferred" },
381     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
382                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
383     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
384                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
385     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
386                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
387     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
388                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
389     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
390                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
391     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
392                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
393     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
394                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
395     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
396                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
397     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
398                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
399     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
400                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
401     { STATS_OFFSET32(pause_frames_sent_hi),
402                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
403     { STATS_OFFSET32(total_tpa_aggregations_hi),
404                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
405     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
406                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
407     { STATS_OFFSET32(total_tpa_bytes_hi),
408                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
409     { STATS_OFFSET32(eee_tx_lpi),
410                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
411     { STATS_OFFSET32(rx_calls),
412                 4, STATS_FLAGS_FUNC, "rx_calls"},
413     { STATS_OFFSET32(rx_pkts),
414                 4, STATS_FLAGS_FUNC, "rx_pkts"},
415     { STATS_OFFSET32(rx_tpa_pkts),
416                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
417     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
418                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
419     { STATS_OFFSET32(rx_bxe_service_rxsgl),
420                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
421     { STATS_OFFSET32(rx_jumbo_sge_pkts),
422                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
423     { STATS_OFFSET32(rx_soft_errors),
424                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
425     { STATS_OFFSET32(rx_hw_csum_errors),
426                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
427     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
428                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
429     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
430                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
431     { STATS_OFFSET32(rx_budget_reached),
432                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
433     { STATS_OFFSET32(tx_pkts),
434                 4, STATS_FLAGS_FUNC, "tx_pkts"},
435     { STATS_OFFSET32(tx_soft_errors),
436                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
437     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
438                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
439     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
440                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
441     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
442                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
443     { STATS_OFFSET32(tx_ofld_frames_lso),
444                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
445     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
446                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
447     { STATS_OFFSET32(tx_encap_failures),
448                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
449     { STATS_OFFSET32(tx_hw_queue_full),
450                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
451     { STATS_OFFSET32(tx_hw_max_queue_depth),
452                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
453     { STATS_OFFSET32(tx_dma_mapping_failure),
454                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
455     { STATS_OFFSET32(tx_max_drbr_queue_depth),
456                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
457     { STATS_OFFSET32(tx_window_violation_std),
458                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
459     { STATS_OFFSET32(tx_window_violation_tso),
460                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
461     { STATS_OFFSET32(tx_chain_lost_mbuf),
462                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
463     { STATS_OFFSET32(tx_frames_deferred),
464                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
465     { STATS_OFFSET32(tx_queue_xoff),
466                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
467     { STATS_OFFSET32(mbuf_defrag_attempts),
468                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
469     { STATS_OFFSET32(mbuf_defrag_failures),
470                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
471     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
472                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
473     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
474                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
475     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
476                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
477     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
478                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
479     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
480                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
481     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
482                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
483     { STATS_OFFSET32(mbuf_alloc_tx),
484                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
485     { STATS_OFFSET32(mbuf_alloc_rx),
486                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
487     { STATS_OFFSET32(mbuf_alloc_sge),
488                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
489     { STATS_OFFSET32(mbuf_alloc_tpa),
490                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
491     { STATS_OFFSET32(tx_queue_full_return),
492                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"}
493 };
494
495 static const struct {
496     uint32_t offset;
497     uint32_t size;
498     char string[STAT_NAME_LEN];
499 } bxe_eth_q_stats_arr[] = {
500     { Q_STATS_OFFSET32(total_bytes_received_hi),
501                 8, "rx_bytes" },
502     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
503                 8, "rx_ucast_packets" },
504     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
505                 8, "rx_mcast_packets" },
506     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
507                 8, "rx_bcast_packets" },
508     { Q_STATS_OFFSET32(no_buff_discard_hi),
509                 8, "rx_discards" },
510     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
511                 8, "tx_bytes" },
512     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
513                 8, "tx_ucast_packets" },
514     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
515                 8, "tx_mcast_packets" },
516     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
517                 8, "tx_bcast_packets" },
518     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
519                 8, "tpa_aggregations" },
520     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
521                 8, "tpa_aggregated_frames"},
522     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
523                 8, "tpa_bytes"},
524     { Q_STATS_OFFSET32(rx_calls),
525                 4, "rx_calls"},
526     { Q_STATS_OFFSET32(rx_pkts),
527                 4, "rx_pkts"},
528     { Q_STATS_OFFSET32(rx_tpa_pkts),
529                 4, "rx_tpa_pkts"},
530     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
531                 4, "rx_erroneous_jumbo_sge_pkts"},
532     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
533                 4, "rx_bxe_service_rxsgl"},
534     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
535                 4, "rx_jumbo_sge_pkts"},
536     { Q_STATS_OFFSET32(rx_soft_errors),
537                 4, "rx_soft_errors"},
538     { Q_STATS_OFFSET32(rx_hw_csum_errors),
539                 4, "rx_hw_csum_errors"},
540     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
541                 4, "rx_ofld_frames_csum_ip"},
542     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
543                 4, "rx_ofld_frames_csum_tcp_udp"},
544     { Q_STATS_OFFSET32(rx_budget_reached),
545                 4, "rx_budget_reached"},
546     { Q_STATS_OFFSET32(tx_pkts),
547                 4, "tx_pkts"},
548     { Q_STATS_OFFSET32(tx_soft_errors),
549                 4, "tx_soft_errors"},
550     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
551                 4, "tx_ofld_frames_csum_ip"},
552     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
553                 4, "tx_ofld_frames_csum_tcp"},
554     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
555                 4, "tx_ofld_frames_csum_udp"},
556     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
557                 4, "tx_ofld_frames_lso"},
558     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
559                 4, "tx_ofld_frames_lso_hdr_splits"},
560     { Q_STATS_OFFSET32(tx_encap_failures),
561                 4, "tx_encap_failures"},
562     { Q_STATS_OFFSET32(tx_hw_queue_full),
563                 4, "tx_hw_queue_full"},
564     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
565                 4, "tx_hw_max_queue_depth"},
566     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
567                 4, "tx_dma_mapping_failure"},
568     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
569                 4, "tx_max_drbr_queue_depth"},
570     { Q_STATS_OFFSET32(tx_window_violation_std),
571                 4, "tx_window_violation_std"},
572     { Q_STATS_OFFSET32(tx_window_violation_tso),
573                 4, "tx_window_violation_tso"},
574     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
575                 4, "tx_chain_lost_mbuf"},
576     { Q_STATS_OFFSET32(tx_frames_deferred),
577                 4, "tx_frames_deferred"},
578     { Q_STATS_OFFSET32(tx_queue_xoff),
579                 4, "tx_queue_xoff"},
580     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
581                 4, "mbuf_defrag_attempts"},
582     { Q_STATS_OFFSET32(mbuf_defrag_failures),
583                 4, "mbuf_defrag_failures"},
584     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
585                 4, "mbuf_rx_bd_alloc_failed"},
586     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
587                 4, "mbuf_rx_bd_mapping_failed"},
588     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
589                 4, "mbuf_rx_tpa_alloc_failed"},
590     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
591                 4, "mbuf_rx_tpa_mapping_failed"},
592     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
593                 4, "mbuf_rx_sge_alloc_failed"},
594     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
595                 4, "mbuf_rx_sge_mapping_failed"},
596     { Q_STATS_OFFSET32(mbuf_alloc_tx),
597                 4, "mbuf_alloc_tx"},
598     { Q_STATS_OFFSET32(mbuf_alloc_rx),
599                 4, "mbuf_alloc_rx"},
600     { Q_STATS_OFFSET32(mbuf_alloc_sge),
601                 4, "mbuf_alloc_sge"},
602     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
603                 4, "mbuf_alloc_tpa"},
604     { Q_STATS_OFFSET32(tx_queue_full_return),
605                 4, "tx_queue_full_return"}
606 };
607
608 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
609 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
610
611
612 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
613                                  uint8_t          read_cfg,
614                                  uint8_t          cmng_type);
615 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
616 static void    storm_memset_cmng(struct bxe_softc *sc,
617                                  struct cmng_init *cmng,
618                                  uint8_t          port);
619 static void    bxe_set_reset_global(struct bxe_softc *sc);
620 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
621 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
622                                  int              engine);
623 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
624 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
625                                    uint8_t          *global,
626                                    uint8_t          print);
627 static void    bxe_int_disable(struct bxe_softc *sc);
628 static int     bxe_release_leader_lock(struct bxe_softc *sc);
629 static void    bxe_pf_disable(struct bxe_softc *sc);
630 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
631 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
632                                       struct bxe_fastpath *fp,
633                                       uint16_t            rx_bd_prod,
634                                       uint16_t            rx_cq_prod,
635                                       uint16_t            rx_sge_prod);
636 static void    bxe_link_report_locked(struct bxe_softc *sc);
637 static void    bxe_link_report(struct bxe_softc *sc);
638 static void    bxe_link_status_update(struct bxe_softc *sc);
639 static void    bxe_periodic_callout_func(void *xsc);
640 static void    bxe_periodic_start(struct bxe_softc *sc);
641 static void    bxe_periodic_stop(struct bxe_softc *sc);
642 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
643                                     uint16_t prev_index,
644                                     uint16_t index);
645 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
646                                      int                 queue);
647 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
648                                      uint16_t            index);
649 static uint8_t bxe_txeof(struct bxe_softc *sc,
650                          struct bxe_fastpath *fp);
651 static void    bxe_task_fp(struct bxe_fastpath *fp);
652 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
653                                      struct mbuf      *m,
654                                      uint8_t          contents);
655 static int     bxe_alloc_mem(struct bxe_softc *sc);
656 static void    bxe_free_mem(struct bxe_softc *sc);
657 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
658 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
659 static int     bxe_interrupt_attach(struct bxe_softc *sc);
660 static void    bxe_interrupt_detach(struct bxe_softc *sc);
661 static void    bxe_set_rx_mode(struct bxe_softc *sc);
662 static int     bxe_init_locked(struct bxe_softc *sc);
663 static int     bxe_stop_locked(struct bxe_softc *sc);
664 static __noinline int bxe_nic_load(struct bxe_softc *sc,
665                                    int              load_mode);
666 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
667                                      uint32_t         unload_mode,
668                                      uint8_t          keep_link);
669
670 static void bxe_handle_sp_tq(void *context, int pending);
671 static void bxe_handle_fp_tq(void *context, int pending);
672
673 static int bxe_add_cdev(struct bxe_softc *sc);
674 static void bxe_del_cdev(struct bxe_softc *sc);
675 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
676 static void bxe_free_buf_rings(struct bxe_softc *sc);
677
678 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
679 uint32_t
680 calc_crc32(uint8_t  *crc32_packet,
681            uint32_t crc32_length,
682            uint32_t crc32_seed,
683            uint8_t  complement)
684 {
685    uint32_t byte         = 0;
686    uint32_t bit          = 0;
687    uint8_t  msb          = 0;
688    uint32_t temp         = 0;
689    uint32_t shft         = 0;
690    uint8_t  current_byte = 0;
691    uint32_t crc32_result = crc32_seed;
692    const uint32_t CRC32_POLY = 0x1edc6f41;
693
694    if ((crc32_packet == NULL) ||
695        (crc32_length == 0) ||
696        ((crc32_length % 8) != 0))
697     {
698         return (crc32_result);
699     }
700
701     for (byte = 0; byte < crc32_length; byte = byte + 1)
702     {
703         current_byte = crc32_packet[byte];
704         for (bit = 0; bit < 8; bit = bit + 1)
705         {
706             /* msb = crc32_result[31]; */
707             msb = (uint8_t)(crc32_result >> 31);
708
709             crc32_result = crc32_result << 1;
710
711             /* it (msb != current_byte[bit]) */
712             if (msb != (0x1 & (current_byte >> bit)))
713             {
714                 crc32_result = crc32_result ^ CRC32_POLY;
715                 /* crc32_result[0] = 1 */
716                 crc32_result |= 1;
717             }
718         }
719     }
720
721     /* Last step is to:
722      * 1. "mirror" every bit
723      * 2. swap the 4 bytes
724      * 3. complement each bit
725      */
726
727     /* Mirror */
728     temp = crc32_result;
729     shft = sizeof(crc32_result) * 8 - 1;
730
731     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
732     {
733         temp <<= 1;
734         temp |= crc32_result & 1;
735         shft-- ;
736     }
737
738     /* temp[31-bit] = crc32_result[bit] */
739     temp <<= shft;
740
741     /* Swap */
742     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
743     {
744         uint32_t t0, t1, t2, t3;
745         t0 = (0x000000ff & (temp >> 24));
746         t1 = (0x0000ff00 & (temp >> 8));
747         t2 = (0x00ff0000 & (temp << 8));
748         t3 = (0xff000000 & (temp << 24));
749         crc32_result = t0 | t1 | t2 | t3;
750     }
751
752     /* Complement */
753     if (complement)
754     {
755         crc32_result = ~crc32_result;
756     }
757
758     return (crc32_result);
759 }
760
761 int
762 bxe_test_bit(int                    nr,
763              volatile unsigned long *addr)
764 {
765     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
766 }
767
768 void
769 bxe_set_bit(unsigned int           nr,
770             volatile unsigned long *addr)
771 {
772     atomic_set_acq_long(addr, (1 << nr));
773 }
774
775 void
776 bxe_clear_bit(int                    nr,
777               volatile unsigned long *addr)
778 {
779     atomic_clear_acq_long(addr, (1 << nr));
780 }
781
782 int
783 bxe_test_and_set_bit(int                    nr,
784                        volatile unsigned long *addr)
785 {
786     unsigned long x;
787     nr = (1 << nr);
788     do {
789         x = *addr;
790     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
791     // if (x & nr) bit_was_set; else bit_was_not_set;
792     return (x & nr);
793 }
794
795 int
796 bxe_test_and_clear_bit(int                    nr,
797                        volatile unsigned long *addr)
798 {
799     unsigned long x;
800     nr = (1 << nr);
801     do {
802         x = *addr;
803     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
804     // if (x & nr) bit_was_set; else bit_was_not_set;
805     return (x & nr);
806 }
807
808 int
809 bxe_cmpxchg(volatile int *addr,
810             int          old,
811             int          new)
812 {
813     int x;
814     do {
815         x = *addr;
816     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
817     return (x);
818 }
819
820 /*
821  * Get DMA memory from the OS.
822  *
823  * Validates that the OS has provided DMA buffers in response to a
824  * bus_dmamap_load call and saves the physical address of those buffers.
825  * When the callback is used the OS will return 0 for the mapping function
826  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
827  * failures back to the caller.
828  *
829  * Returns:
830  *   Nothing.
831  */
832 static void
833 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
834 {
835     struct bxe_dma *dma = arg;
836
837     if (error) {
838         dma->paddr = 0;
839         dma->nseg  = 0;
840         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
841     } else {
842         dma->paddr = segs->ds_addr;
843         dma->nseg  = nseg;
844     }
845 }
846
847 /*
848  * Allocate a block of memory and map it for DMA. No partial completions
849  * allowed and release any resources acquired if we can't acquire all
850  * resources.
851  *
852  * Returns:
853  *   0 = Success, !0 = Failure
854  */
855 int
856 bxe_dma_alloc(struct bxe_softc *sc,
857               bus_size_t       size,
858               struct bxe_dma   *dma,
859               const char       *msg)
860 {
861     int rc;
862
863     if (dma->size > 0) {
864         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
865               (unsigned long)dma->size);
866         return (1);
867     }
868
869     memset(dma, 0, sizeof(*dma)); /* sanity */
870     dma->sc   = sc;
871     dma->size = size;
872     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
873
874     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
875                             BCM_PAGE_SIZE,      /* alignment */
876                             0,                  /* boundary limit */
877                             BUS_SPACE_MAXADDR,  /* restricted low */
878                             BUS_SPACE_MAXADDR,  /* restricted hi */
879                             NULL,               /* addr filter() */
880                             NULL,               /* addr filter() arg */
881                             size,               /* max map size */
882                             1,                  /* num discontinuous */
883                             size,               /* max seg size */
884                             BUS_DMA_ALLOCNOW,   /* flags */
885                             NULL,               /* lock() */
886                             NULL,               /* lock() arg */
887                             &dma->tag);         /* returned dma tag */
888     if (rc != 0) {
889         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
890         memset(dma, 0, sizeof(*dma));
891         return (1);
892     }
893
894     rc = bus_dmamem_alloc(dma->tag,
895                           (void **)&dma->vaddr,
896                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
897                           &dma->map);
898     if (rc != 0) {
899         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
900         bus_dma_tag_destroy(dma->tag);
901         memset(dma, 0, sizeof(*dma));
902         return (1);
903     }
904
905     rc = bus_dmamap_load(dma->tag,
906                          dma->map,
907                          dma->vaddr,
908                          size,
909                          bxe_dma_map_addr, /* BLOGD in here */
910                          dma,
911                          BUS_DMA_NOWAIT);
912     if (rc != 0) {
913         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
914         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
915         bus_dma_tag_destroy(dma->tag);
916         memset(dma, 0, sizeof(*dma));
917         return (1);
918     }
919
920     return (0);
921 }
922
923 void
924 bxe_dma_free(struct bxe_softc *sc,
925              struct bxe_dma   *dma)
926 {
927     if (dma->size > 0) {
928         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
929
930         bus_dmamap_sync(dma->tag, dma->map,
931                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
932         bus_dmamap_unload(dma->tag, dma->map);
933         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
934         bus_dma_tag_destroy(dma->tag);
935     }
936
937     memset(dma, 0, sizeof(*dma));
938 }
939
940 /*
941  * These indirect read and write routines are only during init.
942  * The locking is handled by the MCP.
943  */
944
945 void
946 bxe_reg_wr_ind(struct bxe_softc *sc,
947                uint32_t         addr,
948                uint32_t         val)
949 {
950     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
951     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
952     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
953 }
954
955 uint32_t
956 bxe_reg_rd_ind(struct bxe_softc *sc,
957                uint32_t         addr)
958 {
959     uint32_t val;
960
961     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
962     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
963     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
964
965     return (val);
966 }
967
968 static int
969 bxe_acquire_hw_lock(struct bxe_softc *sc,
970                     uint32_t         resource)
971 {
972     uint32_t lock_status;
973     uint32_t resource_bit = (1 << resource);
974     int func = SC_FUNC(sc);
975     uint32_t hw_lock_control_reg;
976     int cnt;
977
978     /* validate the resource is within range */
979     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
980         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
981             " resource_bit 0x%x\n", resource, resource_bit);
982         return (-1);
983     }
984
985     if (func <= 5) {
986         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
987     } else {
988         hw_lock_control_reg =
989                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
990     }
991
992     /* validate the resource is not already taken */
993     lock_status = REG_RD(sc, hw_lock_control_reg);
994     if (lock_status & resource_bit) {
995         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
996               resource, lock_status, resource_bit);
997         return (-1);
998     }
999
1000     /* try every 5ms for 5 seconds */
1001     for (cnt = 0; cnt < 1000; cnt++) {
1002         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1003         lock_status = REG_RD(sc, hw_lock_control_reg);
1004         if (lock_status & resource_bit) {
1005             return (0);
1006         }
1007         DELAY(5000);
1008     }
1009
1010     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1011         resource, resource_bit);
1012     return (-1);
1013 }
1014
1015 static int
1016 bxe_release_hw_lock(struct bxe_softc *sc,
1017                     uint32_t         resource)
1018 {
1019     uint32_t lock_status;
1020     uint32_t resource_bit = (1 << resource);
1021     int func = SC_FUNC(sc);
1022     uint32_t hw_lock_control_reg;
1023
1024     /* validate the resource is within range */
1025     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1026         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1027             " resource_bit 0x%x\n", resource, resource_bit);
1028         return (-1);
1029     }
1030
1031     if (func <= 5) {
1032         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1033     } else {
1034         hw_lock_control_reg =
1035                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1036     }
1037
1038     /* validate the resource is currently taken */
1039     lock_status = REG_RD(sc, hw_lock_control_reg);
1040     if (!(lock_status & resource_bit)) {
1041         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1042               resource, lock_status, resource_bit);
1043         return (-1);
1044     }
1045
1046     REG_WR(sc, hw_lock_control_reg, resource_bit);
1047     return (0);
1048 }
1049 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1050 {
1051         BXE_PHY_LOCK(sc);
1052         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1053 }
1054
1055 static void bxe_release_phy_lock(struct bxe_softc *sc)
1056 {
1057         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1058         BXE_PHY_UNLOCK(sc);
1059 }
1060 /*
1061  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1062  * had we done things the other way around, if two pfs from the same port
1063  * would attempt to access nvram at the same time, we could run into a
1064  * scenario such as:
1065  * pf A takes the port lock.
1066  * pf B succeeds in taking the same lock since they are from the same port.
1067  * pf A takes the per pf misc lock. Performs eeprom access.
1068  * pf A finishes. Unlocks the per pf misc lock.
1069  * Pf B takes the lock and proceeds to perform it's own access.
1070  * pf A unlocks the per port lock, while pf B is still working (!).
1071  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1072  * access corrupted by pf B).*
1073  */
1074 static int
1075 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1076 {
1077     int port = SC_PORT(sc);
1078     int count, i;
1079     uint32_t val = 0;
1080
1081     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1082     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1083
1084     /* adjust timeout for emulation/FPGA */
1085     count = NVRAM_TIMEOUT_COUNT;
1086     if (CHIP_REV_IS_SLOW(sc)) {
1087         count *= 100;
1088     }
1089
1090     /* request access to nvram interface */
1091     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1092            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1093
1094     for (i = 0; i < count*10; i++) {
1095         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1096         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1097             break;
1098         }
1099
1100         DELAY(5);
1101     }
1102
1103     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1104         BLOGE(sc, "Cannot get access to nvram interface "
1105             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1106             port, val);
1107         return (-1);
1108     }
1109
1110     return (0);
1111 }
1112
1113 static int
1114 bxe_release_nvram_lock(struct bxe_softc *sc)
1115 {
1116     int port = SC_PORT(sc);
1117     int count, i;
1118     uint32_t val = 0;
1119
1120     /* adjust timeout for emulation/FPGA */
1121     count = NVRAM_TIMEOUT_COUNT;
1122     if (CHIP_REV_IS_SLOW(sc)) {
1123         count *= 100;
1124     }
1125
1126     /* relinquish nvram interface */
1127     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1128            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1129
1130     for (i = 0; i < count*10; i++) {
1131         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1132         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1133             break;
1134         }
1135
1136         DELAY(5);
1137     }
1138
1139     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1140         BLOGE(sc, "Cannot free access to nvram interface "
1141             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1142             port, val);
1143         return (-1);
1144     }
1145
1146     /* release HW lock: protect against other PFs in PF Direct Assignment */
1147     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1148
1149     return (0);
1150 }
1151
1152 static void
1153 bxe_enable_nvram_access(struct bxe_softc *sc)
1154 {
1155     uint32_t val;
1156
1157     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1158
1159     /* enable both bits, even on read */
1160     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1161            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1162 }
1163
1164 static void
1165 bxe_disable_nvram_access(struct bxe_softc *sc)
1166 {
1167     uint32_t val;
1168
1169     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1170
1171     /* disable both bits, even after read */
1172     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1173            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1174                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1175 }
1176
1177 static int
1178 bxe_nvram_read_dword(struct bxe_softc *sc,
1179                      uint32_t         offset,
1180                      uint32_t         *ret_val,
1181                      uint32_t         cmd_flags)
1182 {
1183     int count, i, rc;
1184     uint32_t val;
1185
1186     /* build the command word */
1187     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1188
1189     /* need to clear DONE bit separately */
1190     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1191
1192     /* address of the NVRAM to read from */
1193     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1194            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1195
1196     /* issue a read command */
1197     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1198
1199     /* adjust timeout for emulation/FPGA */
1200     count = NVRAM_TIMEOUT_COUNT;
1201     if (CHIP_REV_IS_SLOW(sc)) {
1202         count *= 100;
1203     }
1204
1205     /* wait for completion */
1206     *ret_val = 0;
1207     rc = -1;
1208     for (i = 0; i < count; i++) {
1209         DELAY(5);
1210         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1211
1212         if (val & MCPR_NVM_COMMAND_DONE) {
1213             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1214             /* we read nvram data in cpu order
1215              * but ethtool sees it as an array of bytes
1216              * converting to big-endian will do the work
1217              */
1218             *ret_val = htobe32(val);
1219             rc = 0;
1220             break;
1221         }
1222     }
1223
1224     if (rc == -1) {
1225         BLOGE(sc, "nvram read timeout expired "
1226             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1227             offset, cmd_flags, val);
1228     }
1229
1230     return (rc);
1231 }
1232
1233 static int
1234 bxe_nvram_read(struct bxe_softc *sc,
1235                uint32_t         offset,
1236                uint8_t          *ret_buf,
1237                int              buf_size)
1238 {
1239     uint32_t cmd_flags;
1240     uint32_t val;
1241     int rc;
1242
1243     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1244         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1245               offset, buf_size);
1246         return (-1);
1247     }
1248
1249     if ((offset + buf_size) > sc->devinfo.flash_size) {
1250         BLOGE(sc, "Invalid parameter, "
1251                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1252               offset, buf_size, sc->devinfo.flash_size);
1253         return (-1);
1254     }
1255
1256     /* request access to nvram interface */
1257     rc = bxe_acquire_nvram_lock(sc);
1258     if (rc) {
1259         return (rc);
1260     }
1261
1262     /* enable access to nvram interface */
1263     bxe_enable_nvram_access(sc);
1264
1265     /* read the first word(s) */
1266     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1267     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1268         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1269         memcpy(ret_buf, &val, 4);
1270
1271         /* advance to the next dword */
1272         offset += sizeof(uint32_t);
1273         ret_buf += sizeof(uint32_t);
1274         buf_size -= sizeof(uint32_t);
1275         cmd_flags = 0;
1276     }
1277
1278     if (rc == 0) {
1279         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1280         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1281         memcpy(ret_buf, &val, 4);
1282     }
1283
1284     /* disable access to nvram interface */
1285     bxe_disable_nvram_access(sc);
1286     bxe_release_nvram_lock(sc);
1287
1288     return (rc);
1289 }
1290
1291 static int
1292 bxe_nvram_write_dword(struct bxe_softc *sc,
1293                       uint32_t         offset,
1294                       uint32_t         val,
1295                       uint32_t         cmd_flags)
1296 {
1297     int count, i, rc;
1298
1299     /* build the command word */
1300     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1301
1302     /* need to clear DONE bit separately */
1303     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1304
1305     /* write the data */
1306     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1307
1308     /* address of the NVRAM to write to */
1309     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1310            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1311
1312     /* issue the write command */
1313     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1314
1315     /* adjust timeout for emulation/FPGA */
1316     count = NVRAM_TIMEOUT_COUNT;
1317     if (CHIP_REV_IS_SLOW(sc)) {
1318         count *= 100;
1319     }
1320
1321     /* wait for completion */
1322     rc = -1;
1323     for (i = 0; i < count; i++) {
1324         DELAY(5);
1325         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1326         if (val & MCPR_NVM_COMMAND_DONE) {
1327             rc = 0;
1328             break;
1329         }
1330     }
1331
1332     if (rc == -1) {
1333         BLOGE(sc, "nvram write timeout expired "
1334             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1335             offset, cmd_flags, val);
1336     }
1337
1338     return (rc);
1339 }
1340
1341 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1342
1343 static int
1344 bxe_nvram_write1(struct bxe_softc *sc,
1345                  uint32_t         offset,
1346                  uint8_t          *data_buf,
1347                  int              buf_size)
1348 {
1349     uint32_t cmd_flags;
1350     uint32_t align_offset;
1351     uint32_t val;
1352     int rc;
1353
1354     if ((offset + buf_size) > sc->devinfo.flash_size) {
1355         BLOGE(sc, "Invalid parameter, "
1356                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1357               offset, buf_size, sc->devinfo.flash_size);
1358         return (-1);
1359     }
1360
1361     /* request access to nvram interface */
1362     rc = bxe_acquire_nvram_lock(sc);
1363     if (rc) {
1364         return (rc);
1365     }
1366
1367     /* enable access to nvram interface */
1368     bxe_enable_nvram_access(sc);
1369
1370     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1371     align_offset = (offset & ~0x03);
1372     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1373
1374     if (rc == 0) {
1375         val &= ~(0xff << BYTE_OFFSET(offset));
1376         val |= (*data_buf << BYTE_OFFSET(offset));
1377
1378         /* nvram data is returned as an array of bytes
1379          * convert it back to cpu order
1380          */
1381         val = be32toh(val);
1382
1383         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1384     }
1385
1386     /* disable access to nvram interface */
1387     bxe_disable_nvram_access(sc);
1388     bxe_release_nvram_lock(sc);
1389
1390     return (rc);
1391 }
1392
1393 static int
1394 bxe_nvram_write(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 val;
1401     uint32_t written_so_far;
1402     int rc;
1403
1404     if (buf_size == 1) {
1405         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1406     }
1407
1408     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1409         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1410               offset, buf_size);
1411         return (-1);
1412     }
1413
1414     if (buf_size == 0) {
1415         return (0); /* nothing to do */
1416     }
1417
1418     if ((offset + buf_size) > sc->devinfo.flash_size) {
1419         BLOGE(sc, "Invalid parameter, "
1420                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1421               offset, buf_size, sc->devinfo.flash_size);
1422         return (-1);
1423     }
1424
1425     /* request access to nvram interface */
1426     rc = bxe_acquire_nvram_lock(sc);
1427     if (rc) {
1428         return (rc);
1429     }
1430
1431     /* enable access to nvram interface */
1432     bxe_enable_nvram_access(sc);
1433
1434     written_so_far = 0;
1435     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1436     while ((written_so_far < buf_size) && (rc == 0)) {
1437         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1438             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1439         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1440             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1441         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1442             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1443         }
1444
1445         memcpy(&val, data_buf, 4);
1446
1447         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1448
1449         /* advance to the next dword */
1450         offset += sizeof(uint32_t);
1451         data_buf += sizeof(uint32_t);
1452         written_so_far += sizeof(uint32_t);
1453         cmd_flags = 0;
1454     }
1455
1456     /* disable access to nvram interface */
1457     bxe_disable_nvram_access(sc);
1458     bxe_release_nvram_lock(sc);
1459
1460     return (rc);
1461 }
1462
1463 /* copy command into DMAE command memory and set DMAE command Go */
1464 void
1465 bxe_post_dmae(struct bxe_softc    *sc,
1466               struct dmae_cmd *dmae,
1467               int                 idx)
1468 {
1469     uint32_t cmd_offset;
1470     int i;
1471
1472     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1473     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1474         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1475     }
1476
1477     REG_WR(sc, dmae_reg_go_c[idx], 1);
1478 }
1479
1480 uint32_t
1481 bxe_dmae_opcode_add_comp(uint32_t opcode,
1482                          uint8_t  comp_type)
1483 {
1484     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1485                       DMAE_CMD_C_TYPE_ENABLE));
1486 }
1487
1488 uint32_t
1489 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1490 {
1491     return (opcode & ~DMAE_CMD_SRC_RESET);
1492 }
1493
1494 uint32_t
1495 bxe_dmae_opcode(struct bxe_softc *sc,
1496                 uint8_t          src_type,
1497                 uint8_t          dst_type,
1498                 uint8_t          with_comp,
1499                 uint8_t          comp_type)
1500 {
1501     uint32_t opcode = 0;
1502
1503     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1504                (dst_type << DMAE_CMD_DST_SHIFT));
1505
1506     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1507
1508     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1509
1510     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1511                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1512
1513     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1514
1515 #ifdef __BIG_ENDIAN
1516     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1517 #else
1518     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1519 #endif
1520
1521     if (with_comp) {
1522         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1523     }
1524
1525     return (opcode);
1526 }
1527
1528 static void
1529 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1530                         struct dmae_cmd *dmae,
1531                         uint8_t             src_type,
1532                         uint8_t             dst_type)
1533 {
1534     memset(dmae, 0, sizeof(struct dmae_cmd));
1535
1536     /* set the opcode */
1537     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1538                                    TRUE, DMAE_COMP_PCI);
1539
1540     /* fill in the completion parameters */
1541     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1542     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1543     dmae->comp_val     = DMAE_COMP_VAL;
1544 }
1545
1546 /* issue a DMAE command over the init channel and wait for completion */
1547 static int
1548 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1549                          struct dmae_cmd *dmae)
1550 {
1551     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1552     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1553
1554     BXE_DMAE_LOCK(sc);
1555
1556     /* reset completion */
1557     *wb_comp = 0;
1558
1559     /* post the command on the channel used for initializations */
1560     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1561
1562     /* wait for completion */
1563     DELAY(5);
1564
1565     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1566         if (!timeout ||
1567             (sc->recovery_state != BXE_RECOVERY_DONE &&
1568              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1569             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1570                 *wb_comp, sc->recovery_state);
1571             BXE_DMAE_UNLOCK(sc);
1572             return (DMAE_TIMEOUT);
1573         }
1574
1575         timeout--;
1576         DELAY(50);
1577     }
1578
1579     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1580         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1581                 *wb_comp, sc->recovery_state);
1582         BXE_DMAE_UNLOCK(sc);
1583         return (DMAE_PCI_ERROR);
1584     }
1585
1586     BXE_DMAE_UNLOCK(sc);
1587     return (0);
1588 }
1589
1590 void
1591 bxe_read_dmae(struct bxe_softc *sc,
1592               uint32_t         src_addr,
1593               uint32_t         len32)
1594 {
1595     struct dmae_cmd dmae;
1596     uint32_t *data;
1597     int i, rc;
1598
1599     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1600
1601     if (!sc->dmae_ready) {
1602         data = BXE_SP(sc, wb_data[0]);
1603
1604         for (i = 0; i < len32; i++) {
1605             data[i] = (CHIP_IS_E1(sc)) ?
1606                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1607                           REG_RD(sc, (src_addr + (i * 4)));
1608         }
1609
1610         return;
1611     }
1612
1613     /* set opcode and fixed command fields */
1614     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1615
1616     /* fill in addresses and len */
1617     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1618     dmae.src_addr_hi = 0;
1619     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1620     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1621     dmae.len         = len32;
1622
1623     /* issue the command and wait for completion */
1624     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1625         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1626     }
1627 }
1628
1629 void
1630 bxe_write_dmae(struct bxe_softc *sc,
1631                bus_addr_t       dma_addr,
1632                uint32_t         dst_addr,
1633                uint32_t         len32)
1634 {
1635     struct dmae_cmd dmae;
1636     int rc;
1637
1638     if (!sc->dmae_ready) {
1639         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1640
1641         if (CHIP_IS_E1(sc)) {
1642             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1643         } else {
1644             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1645         }
1646
1647         return;
1648     }
1649
1650     /* set opcode and fixed command fields */
1651     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1652
1653     /* fill in addresses and len */
1654     dmae.src_addr_lo = U64_LO(dma_addr);
1655     dmae.src_addr_hi = U64_HI(dma_addr);
1656     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1657     dmae.dst_addr_hi = 0;
1658     dmae.len         = len32;
1659
1660     /* issue the command and wait for completion */
1661     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1662         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1663     }
1664 }
1665
1666 void
1667 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1668                         bus_addr_t       phys_addr,
1669                         uint32_t         addr,
1670                         uint32_t         len)
1671 {
1672     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1673     int offset = 0;
1674
1675     while (len > dmae_wr_max) {
1676         bxe_write_dmae(sc,
1677                        (phys_addr + offset), /* src DMA address */
1678                        (addr + offset),      /* dst GRC address */
1679                        dmae_wr_max);
1680         offset += (dmae_wr_max * 4);
1681         len -= dmae_wr_max;
1682     }
1683
1684     bxe_write_dmae(sc,
1685                    (phys_addr + offset), /* src DMA address */
1686                    (addr + offset),      /* dst GRC address */
1687                    len);
1688 }
1689
1690 void
1691 bxe_set_ctx_validation(struct bxe_softc   *sc,
1692                        struct eth_context *cxt,
1693                        uint32_t           cid)
1694 {
1695     /* ustorm cxt validation */
1696     cxt->ustorm_ag_context.cdu_usage =
1697         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1698             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1699     /* xcontext validation */
1700     cxt->xstorm_ag_context.cdu_reserved =
1701         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1702             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1703 }
1704
1705 static void
1706 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1707                             uint8_t          port,
1708                             uint8_t          fw_sb_id,
1709                             uint8_t          sb_index,
1710                             uint8_t          ticks)
1711 {
1712     uint32_t addr =
1713         (BAR_CSTRORM_INTMEM +
1714          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1715
1716     REG_WR8(sc, addr, ticks);
1717
1718     BLOGD(sc, DBG_LOAD,
1719           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1720           port, fw_sb_id, sb_index, ticks);
1721 }
1722
1723 static void
1724 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1725                             uint8_t          port,
1726                             uint16_t         fw_sb_id,
1727                             uint8_t          sb_index,
1728                             uint8_t          disable)
1729 {
1730     uint32_t enable_flag =
1731         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1732     uint32_t addr =
1733         (BAR_CSTRORM_INTMEM +
1734          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1735     uint8_t flags;
1736
1737     /* clear and set */
1738     flags = REG_RD8(sc, addr);
1739     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1740     flags |= enable_flag;
1741     REG_WR8(sc, addr, flags);
1742
1743     BLOGD(sc, DBG_LOAD,
1744           "port %d fw_sb_id %d sb_index %d disable %d\n",
1745           port, fw_sb_id, sb_index, disable);
1746 }
1747
1748 void
1749 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1750                              uint8_t          fw_sb_id,
1751                              uint8_t          sb_index,
1752                              uint8_t          disable,
1753                              uint16_t         usec)
1754 {
1755     int port = SC_PORT(sc);
1756     uint8_t ticks = (usec / 4); /* XXX ??? */
1757
1758     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1759
1760     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1761     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1762 }
1763
1764 void
1765 elink_cb_udelay(struct bxe_softc *sc,
1766                 uint32_t         usecs)
1767 {
1768     DELAY(usecs);
1769 }
1770
1771 uint32_t
1772 elink_cb_reg_read(struct bxe_softc *sc,
1773                   uint32_t         reg_addr)
1774 {
1775     return (REG_RD(sc, reg_addr));
1776 }
1777
1778 void
1779 elink_cb_reg_write(struct bxe_softc *sc,
1780                    uint32_t         reg_addr,
1781                    uint32_t         val)
1782 {
1783     REG_WR(sc, reg_addr, val);
1784 }
1785
1786 void
1787 elink_cb_reg_wb_write(struct bxe_softc *sc,
1788                       uint32_t         offset,
1789                       uint32_t         *wb_write,
1790                       uint16_t         len)
1791 {
1792     REG_WR_DMAE(sc, offset, wb_write, len);
1793 }
1794
1795 void
1796 elink_cb_reg_wb_read(struct bxe_softc *sc,
1797                      uint32_t         offset,
1798                      uint32_t         *wb_write,
1799                      uint16_t         len)
1800 {
1801     REG_RD_DMAE(sc, offset, wb_write, len);
1802 }
1803
1804 uint8_t
1805 elink_cb_path_id(struct bxe_softc *sc)
1806 {
1807     return (SC_PATH(sc));
1808 }
1809
1810 void
1811 elink_cb_event_log(struct bxe_softc     *sc,
1812                    const elink_log_id_t elink_log_id,
1813                    ...)
1814 {
1815     /* XXX */
1816     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1817 }
1818
1819 static int
1820 bxe_set_spio(struct bxe_softc *sc,
1821              int              spio,
1822              uint32_t         mode)
1823 {
1824     uint32_t spio_reg;
1825
1826     /* Only 2 SPIOs are configurable */
1827     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1828         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1829         return (-1);
1830     }
1831
1832     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1833
1834     /* read SPIO and mask except the float bits */
1835     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1836
1837     switch (mode) {
1838     case MISC_SPIO_OUTPUT_LOW:
1839         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1840         /* clear FLOAT and set CLR */
1841         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1842         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1843         break;
1844
1845     case MISC_SPIO_OUTPUT_HIGH:
1846         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1847         /* clear FLOAT and set SET */
1848         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1849         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1850         break;
1851
1852     case MISC_SPIO_INPUT_HI_Z:
1853         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1854         /* set FLOAT */
1855         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1856         break;
1857
1858     default:
1859         break;
1860     }
1861
1862     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1863     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1864
1865     return (0);
1866 }
1867
1868 static int
1869 bxe_gpio_read(struct bxe_softc *sc,
1870               int              gpio_num,
1871               uint8_t          port)
1872 {
1873     /* The GPIO should be swapped if swap register is set and active */
1874     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1875                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1876     int gpio_shift = (gpio_num +
1877                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1878     uint32_t gpio_mask = (1 << gpio_shift);
1879     uint32_t gpio_reg;
1880
1881     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1882         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1883             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1884             gpio_mask);
1885         return (-1);
1886     }
1887
1888     /* read GPIO value */
1889     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1890
1891     /* get the requested pin value */
1892     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1893 }
1894
1895 static int
1896 bxe_gpio_write(struct bxe_softc *sc,
1897                int              gpio_num,
1898                uint32_t         mode,
1899                uint8_t          port)
1900 {
1901     /* The GPIO should be swapped if swap register is set and active */
1902     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1903                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1904     int gpio_shift = (gpio_num +
1905                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1906     uint32_t gpio_mask = (1 << gpio_shift);
1907     uint32_t gpio_reg;
1908
1909     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1910         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1911             " gpio_shift %d gpio_mask 0x%x\n",
1912             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1913         return (-1);
1914     }
1915
1916     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1917
1918     /* read GPIO and mask except the float bits */
1919     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1920
1921     switch (mode) {
1922     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1923         BLOGD(sc, DBG_PHY,
1924               "Set GPIO %d (shift %d) -> output low\n",
1925               gpio_num, gpio_shift);
1926         /* clear FLOAT and set CLR */
1927         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1928         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1929         break;
1930
1931     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1932         BLOGD(sc, DBG_PHY,
1933               "Set GPIO %d (shift %d) -> output high\n",
1934               gpio_num, gpio_shift);
1935         /* clear FLOAT and set SET */
1936         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1937         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1938         break;
1939
1940     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1941         BLOGD(sc, DBG_PHY,
1942               "Set GPIO %d (shift %d) -> input\n",
1943               gpio_num, gpio_shift);
1944         /* set FLOAT */
1945         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1946         break;
1947
1948     default:
1949         break;
1950     }
1951
1952     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1953     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1954
1955     return (0);
1956 }
1957
1958 static int
1959 bxe_gpio_mult_write(struct bxe_softc *sc,
1960                     uint8_t          pins,
1961                     uint32_t         mode)
1962 {
1963     uint32_t gpio_reg;
1964
1965     /* any port swapping should be handled by caller */
1966
1967     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1968
1969     /* read GPIO and mask except the float bits */
1970     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1971     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1972     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1973     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1974
1975     switch (mode) {
1976     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1977         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1978         /* set CLR */
1979         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1980         break;
1981
1982     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1983         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1984         /* set SET */
1985         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
1986         break;
1987
1988     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1989         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
1990         /* set FLOAT */
1991         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1992         break;
1993
1994     default:
1995         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
1996             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
1997         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1998         return (-1);
1999     }
2000
2001     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2002     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2003
2004     return (0);
2005 }
2006
2007 static int
2008 bxe_gpio_int_write(struct bxe_softc *sc,
2009                    int              gpio_num,
2010                    uint32_t         mode,
2011                    uint8_t          port)
2012 {
2013     /* The GPIO should be swapped if swap register is set and active */
2014     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2015                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2016     int gpio_shift = (gpio_num +
2017                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2018     uint32_t gpio_mask = (1 << gpio_shift);
2019     uint32_t gpio_reg;
2020
2021     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2022         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2023             " gpio_shift %d gpio_mask 0x%x\n",
2024             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2025         return (-1);
2026     }
2027
2028     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2029
2030     /* read GPIO int */
2031     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2032
2033     switch (mode) {
2034     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2035         BLOGD(sc, DBG_PHY,
2036               "Clear GPIO INT %d (shift %d) -> output low\n",
2037               gpio_num, gpio_shift);
2038         /* clear SET and set CLR */
2039         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2040         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2041         break;
2042
2043     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2044         BLOGD(sc, DBG_PHY,
2045               "Set GPIO INT %d (shift %d) -> output high\n",
2046               gpio_num, gpio_shift);
2047         /* clear CLR and set SET */
2048         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2049         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2050         break;
2051
2052     default:
2053         break;
2054     }
2055
2056     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2057     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2058
2059     return (0);
2060 }
2061
2062 uint32_t
2063 elink_cb_gpio_read(struct bxe_softc *sc,
2064                    uint16_t         gpio_num,
2065                    uint8_t          port)
2066 {
2067     return (bxe_gpio_read(sc, gpio_num, port));
2068 }
2069
2070 uint8_t
2071 elink_cb_gpio_write(struct bxe_softc *sc,
2072                     uint16_t         gpio_num,
2073                     uint8_t          mode, /* 0=low 1=high */
2074                     uint8_t          port)
2075 {
2076     return (bxe_gpio_write(sc, gpio_num, mode, port));
2077 }
2078
2079 uint8_t
2080 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2081                          uint8_t          pins,
2082                          uint8_t          mode) /* 0=low 1=high */
2083 {
2084     return (bxe_gpio_mult_write(sc, pins, mode));
2085 }
2086
2087 uint8_t
2088 elink_cb_gpio_int_write(struct bxe_softc *sc,
2089                         uint16_t         gpio_num,
2090                         uint8_t          mode, /* 0=low 1=high */
2091                         uint8_t          port)
2092 {
2093     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2094 }
2095
2096 void
2097 elink_cb_notify_link_changed(struct bxe_softc *sc)
2098 {
2099     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2100                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2101 }
2102
2103 /* send the MCP a request, block until there is a reply */
2104 uint32_t
2105 elink_cb_fw_command(struct bxe_softc *sc,
2106                     uint32_t         command,
2107                     uint32_t         param)
2108 {
2109     int mb_idx = SC_FW_MB_IDX(sc);
2110     uint32_t seq;
2111     uint32_t rc = 0;
2112     uint32_t cnt = 1;
2113     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2114
2115     BXE_FWMB_LOCK(sc);
2116
2117     seq = ++sc->fw_seq;
2118     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2119     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2120
2121     BLOGD(sc, DBG_PHY,
2122           "wrote command 0x%08x to FW MB param 0x%08x\n",
2123           (command | seq), param);
2124
2125     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2126     do {
2127         DELAY(delay * 1000);
2128         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2129     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2130
2131     BLOGD(sc, DBG_PHY,
2132           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2133           cnt*delay, rc, seq);
2134
2135     /* is this a reply to our command? */
2136     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2137         rc &= FW_MSG_CODE_MASK;
2138     } else {
2139         /* Ruh-roh! */
2140         BLOGE(sc, "FW failed to respond!\n");
2141         // XXX bxe_fw_dump(sc);
2142         rc = 0;
2143     }
2144
2145     BXE_FWMB_UNLOCK(sc);
2146     return (rc);
2147 }
2148
2149 static uint32_t
2150 bxe_fw_command(struct bxe_softc *sc,
2151                uint32_t         command,
2152                uint32_t         param)
2153 {
2154     return (elink_cb_fw_command(sc, command, param));
2155 }
2156
2157 static void
2158 __storm_memset_dma_mapping(struct bxe_softc *sc,
2159                            uint32_t         addr,
2160                            bus_addr_t       mapping)
2161 {
2162     REG_WR(sc, addr, U64_LO(mapping));
2163     REG_WR(sc, (addr + 4), U64_HI(mapping));
2164 }
2165
2166 static void
2167 storm_memset_spq_addr(struct bxe_softc *sc,
2168                       bus_addr_t       mapping,
2169                       uint16_t         abs_fid)
2170 {
2171     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2172                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2173     __storm_memset_dma_mapping(sc, addr, mapping);
2174 }
2175
2176 static void
2177 storm_memset_vf_to_pf(struct bxe_softc *sc,
2178                       uint16_t         abs_fid,
2179                       uint16_t         pf_id)
2180 {
2181     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2182     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2183     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2184     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2185 }
2186
2187 static void
2188 storm_memset_func_en(struct bxe_softc *sc,
2189                      uint16_t         abs_fid,
2190                      uint8_t          enable)
2191 {
2192     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2193     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2194     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2195     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2196 }
2197
2198 static void
2199 storm_memset_eq_data(struct bxe_softc       *sc,
2200                      struct event_ring_data *eq_data,
2201                      uint16_t               pfid)
2202 {
2203     uint32_t addr;
2204     size_t size;
2205
2206     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2207     size = sizeof(struct event_ring_data);
2208     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2209 }
2210
2211 static void
2212 storm_memset_eq_prod(struct bxe_softc *sc,
2213                      uint16_t         eq_prod,
2214                      uint16_t         pfid)
2215 {
2216     uint32_t addr = (BAR_CSTRORM_INTMEM +
2217                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2218     REG_WR16(sc, addr, eq_prod);
2219 }
2220
2221 /*
2222  * Post a slowpath command.
2223  *
2224  * A slowpath command is used to propagate a configuration change through
2225  * the controller in a controlled manner, allowing each STORM processor and
2226  * other H/W blocks to phase in the change.  The commands sent on the
2227  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2228  * completion of the ramrod will occur in different ways.  Here's a
2229  * breakdown of ramrods and how they complete:
2230  *
2231  * RAMROD_CMD_ID_ETH_PORT_SETUP
2232  *   Used to setup the leading connection on a port.  Completes on the
2233  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2234  *
2235  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2236  *   Used to setup an additional connection on a port.  Completes on the
2237  *   RCQ of the multi-queue/RSS connection being initialized.
2238  *
2239  * RAMROD_CMD_ID_ETH_STAT_QUERY
2240  *   Used to force the storm processors to update the statistics database
2241  *   in host memory.  This ramrod is send on the leading connection CID and
2242  *   completes as an index increment of the CSTORM on the default status
2243  *   block.
2244  *
2245  * RAMROD_CMD_ID_ETH_UPDATE
2246  *   Used to update the state of the leading connection, usually to udpate
2247  *   the RSS indirection table.  Completes on the RCQ of the leading
2248  *   connection. (Not currently used under FreeBSD until OS support becomes
2249  *   available.)
2250  *
2251  * RAMROD_CMD_ID_ETH_HALT
2252  *   Used when tearing down a connection prior to driver unload.  Completes
2253  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2254  *   use this on the leading connection.
2255  *
2256  * RAMROD_CMD_ID_ETH_SET_MAC
2257  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2258  *   the RCQ of the leading connection.
2259  *
2260  * RAMROD_CMD_ID_ETH_CFC_DEL
2261  *   Used when tearing down a conneciton prior to driver unload.  Completes
2262  *   on the RCQ of the leading connection (since the current connection
2263  *   has been completely removed from controller memory).
2264  *
2265  * RAMROD_CMD_ID_ETH_PORT_DEL
2266  *   Used to tear down the leading connection prior to driver unload,
2267  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2268  *   default status block.
2269  *
2270  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2271  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2272  *   RSS connection that is being offloaded.  (Not currently used under
2273  *   FreeBSD.)
2274  *
2275  * There can only be one command pending per function.
2276  *
2277  * Returns:
2278  *   0 = Success, !0 = Failure.
2279  */
2280
2281 /* must be called under the spq lock */
2282 static inline
2283 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2284 {
2285     struct eth_spe *next_spe = sc->spq_prod_bd;
2286
2287     if (sc->spq_prod_bd == sc->spq_last_bd) {
2288         /* wrap back to the first eth_spq */
2289         sc->spq_prod_bd = sc->spq;
2290         sc->spq_prod_idx = 0;
2291     } else {
2292         sc->spq_prod_bd++;
2293         sc->spq_prod_idx++;
2294     }
2295
2296     return (next_spe);
2297 }
2298
2299 /* must be called under the spq lock */
2300 static inline
2301 void bxe_sp_prod_update(struct bxe_softc *sc)
2302 {
2303     int func = SC_FUNC(sc);
2304
2305     /*
2306      * Make sure that BD data is updated before writing the producer.
2307      * BD data is written to the memory, the producer is read from the
2308      * memory, thus we need a full memory barrier to ensure the ordering.
2309      */
2310     mb();
2311
2312     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2313              sc->spq_prod_idx);
2314
2315     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2316                       BUS_SPACE_BARRIER_WRITE);
2317 }
2318
2319 /**
2320  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2321  *
2322  * @cmd:      command to check
2323  * @cmd_type: command type
2324  */
2325 static inline
2326 int bxe_is_contextless_ramrod(int cmd,
2327                               int cmd_type)
2328 {
2329     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2330         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2331         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2332         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2333         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2334         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2335         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2336         return (TRUE);
2337     } else {
2338         return (FALSE);
2339     }
2340 }
2341
2342 /**
2343  * bxe_sp_post - place a single command on an SP ring
2344  *
2345  * @sc:         driver handle
2346  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2347  * @cid:        SW CID the command is related to
2348  * @data_hi:    command private data address (high 32 bits)
2349  * @data_lo:    command private data address (low 32 bits)
2350  * @cmd_type:   command type (e.g. NONE, ETH)
2351  *
2352  * SP data is handled as if it's always an address pair, thus data fields are
2353  * not swapped to little endian in upper functions. Instead this function swaps
2354  * data as if it's two uint32 fields.
2355  */
2356 int
2357 bxe_sp_post(struct bxe_softc *sc,
2358             int              command,
2359             int              cid,
2360             uint32_t         data_hi,
2361             uint32_t         data_lo,
2362             int              cmd_type)
2363 {
2364     struct eth_spe *spe;
2365     uint16_t type;
2366     int common;
2367
2368     common = bxe_is_contextless_ramrod(command, cmd_type);
2369
2370     BXE_SP_LOCK(sc);
2371
2372     if (common) {
2373         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2374             BLOGE(sc, "EQ ring is full!\n");
2375             BXE_SP_UNLOCK(sc);
2376             return (-1);
2377         }
2378     } else {
2379         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2380             BLOGE(sc, "SPQ ring is full!\n");
2381             BXE_SP_UNLOCK(sc);
2382             return (-1);
2383         }
2384     }
2385
2386     spe = bxe_sp_get_next(sc);
2387
2388     /* CID needs port number to be encoded int it */
2389     spe->hdr.conn_and_cmd_data =
2390         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2391
2392     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2393
2394     /* TBD: Check if it works for VFs */
2395     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2396              SPE_HDR_T_FUNCTION_ID);
2397
2398     spe->hdr.type = htole16(type);
2399
2400     spe->data.update_data_addr.hi = htole32(data_hi);
2401     spe->data.update_data_addr.lo = htole32(data_lo);
2402
2403     /*
2404      * It's ok if the actual decrement is issued towards the memory
2405      * somewhere between the lock and unlock. Thus no more explict
2406      * memory barrier is needed.
2407      */
2408     if (common) {
2409         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2410     } else {
2411         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2412     }
2413
2414     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2415     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2416           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2417     BLOGD(sc, DBG_SP,
2418           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2419           sc->spq_prod_idx,
2420           (uint32_t)U64_HI(sc->spq_dma.paddr),
2421           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2422           command,
2423           common,
2424           HW_CID(sc, cid),
2425           data_hi,
2426           data_lo,
2427           type,
2428           atomic_load_acq_long(&sc->cq_spq_left),
2429           atomic_load_acq_long(&sc->eq_spq_left));
2430
2431     bxe_sp_prod_update(sc);
2432
2433     BXE_SP_UNLOCK(sc);
2434     return (0);
2435 }
2436
2437 /**
2438  * bxe_debug_print_ind_table - prints the indirection table configuration.
2439  *
2440  * @sc: driver hanlde
2441  * @p:  pointer to rss configuration
2442  */
2443
2444 /*
2445  * FreeBSD Device probe function.
2446  *
2447  * Compares the device found to the driver's list of supported devices and
2448  * reports back to the bsd loader whether this is the right driver for the device.
2449  * This is the driver entry function called from the "kldload" command.
2450  *
2451  * Returns:
2452  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2453  */
2454 static int
2455 bxe_probe(device_t dev)
2456 {
2457     struct bxe_device_type *t;
2458     char *descbuf;
2459     uint16_t did, sdid, svid, vid;
2460
2461     /* Find our device structure */
2462     t = bxe_devs;
2463
2464     /* Get the data for the device to be probed. */
2465     vid  = pci_get_vendor(dev);
2466     did  = pci_get_device(dev);
2467     svid = pci_get_subvendor(dev);
2468     sdid = pci_get_subdevice(dev);
2469
2470     /* Look through the list of known devices for a match. */
2471     while (t->bxe_name != NULL) {
2472         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2473             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2474             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2475             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2476             if (descbuf == NULL)
2477                 return (ENOMEM);
2478
2479             /* Print out the device identity. */
2480             snprintf(descbuf, BXE_DEVDESC_MAX,
2481                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2482                      (((pci_read_config(dev, PCIR_REVID, 4) &
2483                         0xf0) >> 4) + 'A'),
2484                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2485                      BXE_DRIVER_VERSION);
2486
2487             device_set_desc_copy(dev, descbuf);
2488             free(descbuf, M_TEMP);
2489             return (BUS_PROBE_DEFAULT);
2490         }
2491         t++;
2492     }
2493
2494     return (ENXIO);
2495 }
2496
2497 static void
2498 bxe_init_mutexes(struct bxe_softc *sc)
2499 {
2500 #ifdef BXE_CORE_LOCK_SX
2501     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2502              "bxe%d_core_lock", sc->unit);
2503     sx_init(&sc->core_sx, sc->core_sx_name);
2504 #else
2505     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2506              "bxe%d_core_lock", sc->unit);
2507     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2508 #endif
2509
2510     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2511              "bxe%d_sp_lock", sc->unit);
2512     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2513
2514     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2515              "bxe%d_dmae_lock", sc->unit);
2516     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2517
2518     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2519              "bxe%d_phy_lock", sc->unit);
2520     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2521
2522     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2523              "bxe%d_fwmb_lock", sc->unit);
2524     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2525
2526     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2527              "bxe%d_print_lock", sc->unit);
2528     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2529
2530     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2531              "bxe%d_stats_lock", sc->unit);
2532     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2533
2534     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2535              "bxe%d_mcast_lock", sc->unit);
2536     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2537 }
2538
2539 static void
2540 bxe_release_mutexes(struct bxe_softc *sc)
2541 {
2542 #ifdef BXE_CORE_LOCK_SX
2543     sx_destroy(&sc->core_sx);
2544 #else
2545     if (mtx_initialized(&sc->core_mtx)) {
2546         mtx_destroy(&sc->core_mtx);
2547     }
2548 #endif
2549
2550     if (mtx_initialized(&sc->sp_mtx)) {
2551         mtx_destroy(&sc->sp_mtx);
2552     }
2553
2554     if (mtx_initialized(&sc->dmae_mtx)) {
2555         mtx_destroy(&sc->dmae_mtx);
2556     }
2557
2558     if (mtx_initialized(&sc->port.phy_mtx)) {
2559         mtx_destroy(&sc->port.phy_mtx);
2560     }
2561
2562     if (mtx_initialized(&sc->fwmb_mtx)) {
2563         mtx_destroy(&sc->fwmb_mtx);
2564     }
2565
2566     if (mtx_initialized(&sc->print_mtx)) {
2567         mtx_destroy(&sc->print_mtx);
2568     }
2569
2570     if (mtx_initialized(&sc->stats_mtx)) {
2571         mtx_destroy(&sc->stats_mtx);
2572     }
2573
2574     if (mtx_initialized(&sc->mcast_mtx)) {
2575         mtx_destroy(&sc->mcast_mtx);
2576     }
2577 }
2578
2579 static void
2580 bxe_tx_disable(struct bxe_softc* sc)
2581 {
2582     if_t ifp = sc->ifp;
2583
2584     /* tell the stack the driver is stopped and TX queue is full */
2585     if (ifp !=  NULL) {
2586         if_setdrvflags(ifp, 0);
2587     }
2588 }
2589
2590 static void
2591 bxe_drv_pulse(struct bxe_softc *sc)
2592 {
2593     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2594              sc->fw_drv_pulse_wr_seq);
2595 }
2596
2597 static inline uint16_t
2598 bxe_tx_avail(struct bxe_softc *sc,
2599              struct bxe_fastpath *fp)
2600 {
2601     int16_t  used;
2602     uint16_t prod;
2603     uint16_t cons;
2604
2605     prod = fp->tx_bd_prod;
2606     cons = fp->tx_bd_cons;
2607
2608     used = SUB_S16(prod, cons);
2609
2610     return (int16_t)(sc->tx_ring_size) - used;
2611 }
2612
2613 static inline int
2614 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2615 {
2616     uint16_t hw_cons;
2617
2618     mb(); /* status block fields can change */
2619     hw_cons = le16toh(*fp->tx_cons_sb);
2620     return (hw_cons != fp->tx_pkt_cons);
2621 }
2622
2623 static inline uint8_t
2624 bxe_has_tx_work(struct bxe_fastpath *fp)
2625 {
2626     /* expand this for multi-cos if ever supported */
2627     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2628 }
2629
2630 static inline int
2631 bxe_has_rx_work(struct bxe_fastpath *fp)
2632 {
2633     uint16_t rx_cq_cons_sb;
2634
2635     mb(); /* status block fields can change */
2636     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2637     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2638         rx_cq_cons_sb++;
2639     return (fp->rx_cq_cons != rx_cq_cons_sb);
2640 }
2641
2642 static void
2643 bxe_sp_event(struct bxe_softc    *sc,
2644              struct bxe_fastpath *fp,
2645              union eth_rx_cqe    *rr_cqe)
2646 {
2647     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2648     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2649     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2650     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2651
2652     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2653           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2654
2655     switch (command) {
2656     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2657         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2658         drv_cmd = ECORE_Q_CMD_UPDATE;
2659         break;
2660
2661     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2662         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2663         drv_cmd = ECORE_Q_CMD_SETUP;
2664         break;
2665
2666     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2667         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2668         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2669         break;
2670
2671     case (RAMROD_CMD_ID_ETH_HALT):
2672         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2673         drv_cmd = ECORE_Q_CMD_HALT;
2674         break;
2675
2676     case (RAMROD_CMD_ID_ETH_TERMINATE):
2677         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2678         drv_cmd = ECORE_Q_CMD_TERMINATE;
2679         break;
2680
2681     case (RAMROD_CMD_ID_ETH_EMPTY):
2682         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2683         drv_cmd = ECORE_Q_CMD_EMPTY;
2684         break;
2685
2686     default:
2687         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2688               command, fp->index);
2689         return;
2690     }
2691
2692     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2693         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2694         /*
2695          * q_obj->complete_cmd() failure means that this was
2696          * an unexpected completion.
2697          *
2698          * In this case we don't want to increase the sc->spq_left
2699          * because apparently we haven't sent this command the first
2700          * place.
2701          */
2702         // bxe_panic(sc, ("Unexpected SP completion\n"));
2703         return;
2704     }
2705
2706     atomic_add_acq_long(&sc->cq_spq_left, 1);
2707
2708     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2709           atomic_load_acq_long(&sc->cq_spq_left));
2710 }
2711
2712 /*
2713  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2714  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2715  * the current aggregation queue as in-progress.
2716  */
2717 static void
2718 bxe_tpa_start(struct bxe_softc            *sc,
2719               struct bxe_fastpath         *fp,
2720               uint16_t                    queue,
2721               uint16_t                    cons,
2722               uint16_t                    prod,
2723               struct eth_fast_path_rx_cqe *cqe)
2724 {
2725     struct bxe_sw_rx_bd tmp_bd;
2726     struct bxe_sw_rx_bd *rx_buf;
2727     struct eth_rx_bd *rx_bd;
2728     int max_agg_queues;
2729     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2730     uint16_t index;
2731
2732     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2733                        "cons=%d prod=%d\n",
2734           fp->index, queue, cons, prod);
2735
2736     max_agg_queues = MAX_AGG_QS(sc);
2737
2738     KASSERT((queue < max_agg_queues),
2739             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2740              fp->index, queue, max_agg_queues));
2741
2742     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2743             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2744              fp->index, queue));
2745
2746     /* copy the existing mbuf and mapping from the TPA pool */
2747     tmp_bd = tpa_info->bd;
2748
2749     if (tmp_bd.m == NULL) {
2750         uint32_t *tmp;
2751
2752         tmp = (uint32_t *)cqe;
2753
2754         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2755               fp->index, queue, cons, prod);
2756         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2757             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2758             
2759         /* XXX Error handling? */
2760         return;
2761     }
2762
2763     /* change the TPA queue to the start state */
2764     tpa_info->state            = BXE_TPA_STATE_START;
2765     tpa_info->placement_offset = cqe->placement_offset;
2766     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2767     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2768     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2769
2770     fp->rx_tpa_queue_used |= (1 << queue);
2771
2772     /*
2773      * If all the buffer descriptors are filled with mbufs then fill in
2774      * the current consumer index with a new BD. Else if a maximum Rx
2775      * buffer limit is imposed then fill in the next producer index.
2776      */
2777     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2778                 prod : cons;
2779
2780     /* move the received mbuf and mapping to TPA pool */
2781     tpa_info->bd = fp->rx_mbuf_chain[cons];
2782
2783     /* release any existing RX BD mbuf mappings */
2784     if (cons != index) {
2785         rx_buf = &fp->rx_mbuf_chain[cons];
2786
2787         if (rx_buf->m_map != NULL) {
2788             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2789                             BUS_DMASYNC_POSTREAD);
2790             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2791         }
2792
2793         /*
2794          * We get here when the maximum number of rx buffers is less than
2795          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2796          * it out here without concern of a memory leak.
2797          */
2798         fp->rx_mbuf_chain[cons].m = NULL;
2799     }
2800
2801     /* update the Rx SW BD with the mbuf info from the TPA pool */
2802     fp->rx_mbuf_chain[index] = tmp_bd;
2803
2804     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2805     rx_bd = &fp->rx_chain[index];
2806     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2807     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2808 }
2809
2810 /*
2811  * When a TPA aggregation is completed, loop through the individual mbufs
2812  * of the aggregation, combining them into a single mbuf which will be sent
2813  * up the stack. Refill all freed SGEs with mbufs as we go along.
2814  */
2815 static int
2816 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2817                    struct bxe_fastpath       *fp,
2818                    struct bxe_sw_tpa_info    *tpa_info,
2819                    uint16_t                  queue,
2820                    uint16_t                  pages,
2821                    struct mbuf               *m,
2822                                struct eth_end_agg_rx_cqe *cqe,
2823                    uint16_t                  cqe_idx)
2824 {
2825     struct mbuf *m_frag;
2826     uint32_t frag_len, frag_size, i;
2827     uint16_t sge_idx;
2828     int rc = 0;
2829     int j;
2830
2831     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2832
2833     BLOGD(sc, DBG_LRO,
2834           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2835           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2836
2837     /* make sure the aggregated frame is not too big to handle */
2838     if (pages > 8 * PAGES_PER_SGE) {
2839
2840         uint32_t *tmp = (uint32_t *)cqe;
2841
2842         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2843                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2844               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2845               tpa_info->len_on_bd, frag_size);
2846
2847         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2848             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2849
2850         bxe_panic(sc, ("sge page count error\n"));
2851         return (EINVAL);
2852     }
2853
2854     /*
2855      * Scan through the scatter gather list pulling individual mbufs into a
2856      * single mbuf for the host stack.
2857      */
2858     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2859         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2860
2861         /*
2862          * Firmware gives the indices of the SGE as if the ring is an array
2863          * (meaning that the "next" element will consume 2 indices).
2864          */
2865         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2866
2867         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2868                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2869               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2870
2871         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2872
2873         /* allocate a new mbuf for the SGE */
2874         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2875         if (rc) {
2876             /* Leave all remaining SGEs in the ring! */
2877             return (rc);
2878         }
2879
2880         /* update the fragment length */
2881         m_frag->m_len = frag_len;
2882
2883         /* concatenate the fragment to the head mbuf */
2884         m_cat(m, m_frag);
2885         fp->eth_q_stats.mbuf_alloc_sge--;
2886
2887         /* update the TPA mbuf size and remaining fragment size */
2888         m->m_pkthdr.len += frag_len;
2889         frag_size -= frag_len;
2890     }
2891
2892     BLOGD(sc, DBG_LRO,
2893           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2894           fp->index, queue, frag_size);
2895
2896     return (rc);
2897 }
2898
2899 static inline void
2900 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2901 {
2902     int i, j;
2903
2904     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2905         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2906
2907         for (j = 0; j < 2; j++) {
2908             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2909             idx--;
2910         }
2911     }
2912 }
2913
2914 static inline void
2915 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2916 {
2917     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2918     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2919
2920     /*
2921      * Clear the two last indices in the page to 1. These are the indices that
2922      * correspond to the "next" element, hence will never be indicated and
2923      * should be removed from the calculations.
2924      */
2925     bxe_clear_sge_mask_next_elems(fp);
2926 }
2927
2928 static inline void
2929 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2930                         uint16_t            idx)
2931 {
2932     uint16_t last_max = fp->last_max_sge;
2933
2934     if (SUB_S16(idx, last_max) > 0) {
2935         fp->last_max_sge = idx;
2936     }
2937 }
2938
2939 static inline void
2940 bxe_update_sge_prod(struct bxe_softc          *sc,
2941                     struct bxe_fastpath       *fp,
2942                     uint16_t                  sge_len,
2943                     union eth_sgl_or_raw_data *cqe)
2944 {
2945     uint16_t last_max, last_elem, first_elem;
2946     uint16_t delta = 0;
2947     uint16_t i;
2948
2949     if (!sge_len) {
2950         return;
2951     }
2952
2953     /* first mark all used pages */
2954     for (i = 0; i < sge_len; i++) {
2955         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2956                             RX_SGE(le16toh(cqe->sgl[i])));
2957     }
2958
2959     BLOGD(sc, DBG_LRO,
2960           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2961           fp->index, sge_len - 1,
2962           le16toh(cqe->sgl[sge_len - 1]));
2963
2964     /* assume that the last SGE index is the biggest */
2965     bxe_update_last_max_sge(fp,
2966                             le16toh(cqe->sgl[sge_len - 1]));
2967
2968     last_max = RX_SGE(fp->last_max_sge);
2969     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2970     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2971
2972     /* if ring is not full */
2973     if (last_elem + 1 != first_elem) {
2974         last_elem++;
2975     }
2976
2977     /* now update the prod */
2978     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2979         if (__predict_true(fp->sge_mask[i])) {
2980             break;
2981         }
2982
2983         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
2984         delta += BIT_VEC64_ELEM_SZ;
2985     }
2986
2987     if (delta > 0) {
2988         fp->rx_sge_prod += delta;
2989         /* clear page-end entries */
2990         bxe_clear_sge_mask_next_elems(fp);
2991     }
2992
2993     BLOGD(sc, DBG_LRO,
2994           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
2995           fp->index, fp->last_max_sge, fp->rx_sge_prod);
2996 }
2997
2998 /*
2999  * The aggregation on the current TPA queue has completed. Pull the individual
3000  * mbuf fragments together into a single mbuf, perform all necessary checksum
3001  * calculations, and send the resuting mbuf to the stack.
3002  */
3003 static void
3004 bxe_tpa_stop(struct bxe_softc          *sc,
3005              struct bxe_fastpath       *fp,
3006              struct bxe_sw_tpa_info    *tpa_info,
3007              uint16_t                  queue,
3008              uint16_t                  pages,
3009                          struct eth_end_agg_rx_cqe *cqe,
3010              uint16_t                  cqe_idx)
3011 {
3012     if_t ifp = sc->ifp;
3013     struct mbuf *m;
3014     int rc = 0;
3015
3016     BLOGD(sc, DBG_LRO,
3017           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3018           fp->index, queue, tpa_info->placement_offset,
3019           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3020
3021     m = tpa_info->bd.m;
3022
3023     /* allocate a replacement before modifying existing mbuf */
3024     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3025     if (rc) {
3026         /* drop the frame and log an error */
3027         fp->eth_q_stats.rx_soft_errors++;
3028         goto bxe_tpa_stop_exit;
3029     }
3030
3031     /* we have a replacement, fixup the current mbuf */
3032     m_adj(m, tpa_info->placement_offset);
3033     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3034
3035     /* mark the checksums valid (taken care of by the firmware) */
3036     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3037     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3038     m->m_pkthdr.csum_data = 0xffff;
3039     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3040                                CSUM_IP_VALID   |
3041                                CSUM_DATA_VALID |
3042                                CSUM_PSEUDO_HDR);
3043
3044     /* aggregate all of the SGEs into a single mbuf */
3045     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3046     if (rc) {
3047         /* drop the packet and log an error */
3048         fp->eth_q_stats.rx_soft_errors++;
3049         m_freem(m);
3050     } else {
3051         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3052             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3053             m->m_flags |= M_VLANTAG;
3054         }
3055
3056         /* assign packet to this interface interface */
3057         if_setrcvif(m, ifp);
3058
3059 #if __FreeBSD_version >= 800000
3060         /* specify what RSS queue was used for this flow */
3061         m->m_pkthdr.flowid = fp->index;
3062         BXE_SET_FLOWID(m);
3063 #endif
3064
3065         if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3066         fp->eth_q_stats.rx_tpa_pkts++;
3067
3068         /* pass the frame to the stack */
3069         if_input(ifp, m);
3070     }
3071
3072     /* we passed an mbuf up the stack or dropped the frame */
3073     fp->eth_q_stats.mbuf_alloc_tpa--;
3074
3075 bxe_tpa_stop_exit:
3076
3077     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3078     fp->rx_tpa_queue_used &= ~(1 << queue);
3079 }
3080
3081 static uint8_t
3082 bxe_service_rxsgl(
3083                  struct bxe_fastpath *fp,
3084                  uint16_t len,
3085                  uint16_t lenonbd,
3086                  struct mbuf *m,
3087                  struct eth_fast_path_rx_cqe *cqe_fp)
3088 {
3089     struct mbuf *m_frag;
3090     uint16_t frags, frag_len;
3091     uint16_t sge_idx = 0;
3092     uint16_t j;
3093     uint8_t i, rc = 0;
3094     uint32_t frag_size;
3095
3096     /* adjust the mbuf */
3097     m->m_len = lenonbd;
3098
3099     frag_size =  len - lenonbd;
3100     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3101
3102     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3103         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3104
3105         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3106         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3107         m_frag->m_len = frag_len;
3108
3109        /* allocate a new mbuf for the SGE */
3110         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3111         if (rc) {
3112             /* Leave all remaining SGEs in the ring! */
3113             return (rc);
3114         }
3115         fp->eth_q_stats.mbuf_alloc_sge--;
3116
3117         /* concatenate the fragment to the head mbuf */
3118         m_cat(m, m_frag);
3119
3120         frag_size -= frag_len;
3121     }
3122
3123     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3124
3125     return rc;
3126 }
3127
3128 static uint8_t
3129 bxe_rxeof(struct bxe_softc    *sc,
3130           struct bxe_fastpath *fp)
3131 {
3132     if_t ifp = sc->ifp;
3133     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3134     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3135     int rx_pkts = 0;
3136     int rc = 0;
3137
3138     BXE_FP_RX_LOCK(fp);
3139
3140     /* CQ "next element" is of the size of the regular element */
3141     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3142     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3143         hw_cq_cons++;
3144     }
3145
3146     bd_cons = fp->rx_bd_cons;
3147     bd_prod = fp->rx_bd_prod;
3148     bd_prod_fw = bd_prod;
3149     sw_cq_cons = fp->rx_cq_cons;
3150     sw_cq_prod = fp->rx_cq_prod;
3151
3152     /*
3153      * Memory barrier necessary as speculative reads of the rx
3154      * buffer can be ahead of the index in the status block
3155      */
3156     rmb();
3157
3158     BLOGD(sc, DBG_RX,
3159           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3160           fp->index, hw_cq_cons, sw_cq_cons);
3161
3162     while (sw_cq_cons != hw_cq_cons) {
3163         struct bxe_sw_rx_bd *rx_buf = NULL;
3164         union eth_rx_cqe *cqe;
3165         struct eth_fast_path_rx_cqe *cqe_fp;
3166         uint8_t cqe_fp_flags;
3167         enum eth_rx_cqe_type cqe_fp_type;
3168         uint16_t len, lenonbd,  pad;
3169         struct mbuf *m = NULL;
3170
3171         comp_ring_cons = RCQ(sw_cq_cons);
3172         bd_prod = RX_BD(bd_prod);
3173         bd_cons = RX_BD(bd_cons);
3174
3175         cqe          = &fp->rcq_chain[comp_ring_cons];
3176         cqe_fp       = &cqe->fast_path_cqe;
3177         cqe_fp_flags = cqe_fp->type_error_flags;
3178         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3179
3180         BLOGD(sc, DBG_RX,
3181               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3182               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3183               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3184               fp->index,
3185               hw_cq_cons,
3186               sw_cq_cons,
3187               bd_prod,
3188               bd_cons,
3189               CQE_TYPE(cqe_fp_flags),
3190               cqe_fp_flags,
3191               cqe_fp->status_flags,
3192               le32toh(cqe_fp->rss_hash_result),
3193               le16toh(cqe_fp->vlan_tag),
3194               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3195               le16toh(cqe_fp->len_on_bd));
3196
3197         /* is this a slowpath msg? */
3198         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3199             bxe_sp_event(sc, fp, cqe);
3200             goto next_cqe;
3201         }
3202
3203         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3204
3205         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3206             struct bxe_sw_tpa_info *tpa_info;
3207             uint16_t frag_size, pages;
3208             uint8_t queue;
3209
3210             if (CQE_TYPE_START(cqe_fp_type)) {
3211                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3212                               bd_cons, bd_prod, cqe_fp);
3213                 m = NULL; /* packet not ready yet */
3214                 goto next_rx;
3215             }
3216
3217             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3218                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3219
3220             queue = cqe->end_agg_cqe.queue_index;
3221             tpa_info = &fp->rx_tpa_info[queue];
3222
3223             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3224                   fp->index, queue);
3225
3226             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3227                          tpa_info->len_on_bd);
3228             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3229
3230             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3231                          &cqe->end_agg_cqe, comp_ring_cons);
3232
3233             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3234
3235             goto next_cqe;
3236         }
3237
3238         /* non TPA */
3239
3240         /* is this an error packet? */
3241         if (__predict_false(cqe_fp_flags &
3242                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3243             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3244             fp->eth_q_stats.rx_soft_errors++;
3245             goto next_rx;
3246         }
3247
3248         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3249         lenonbd = le16toh(cqe_fp->len_on_bd);
3250         pad = cqe_fp->placement_offset;
3251
3252         m = rx_buf->m;
3253
3254         if (__predict_false(m == NULL)) {
3255             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3256                   bd_cons, fp->index);
3257             goto next_rx;
3258         }
3259
3260         /* XXX double copy if packet length under a threshold */
3261
3262         /*
3263          * If all the buffer descriptors are filled with mbufs then fill in
3264          * the current consumer index with a new BD. Else if a maximum Rx
3265          * buffer limit is imposed then fill in the next producer index.
3266          */
3267         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3268                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3269                                       bd_prod : bd_cons);
3270         if (rc != 0) {
3271
3272             /* we simply reuse the received mbuf and don't post it to the stack */
3273             m = NULL;
3274
3275             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3276                   fp->index, rc);
3277             fp->eth_q_stats.rx_soft_errors++;
3278
3279             if (sc->max_rx_bufs != RX_BD_USABLE) {
3280                 /* copy this consumer index to the producer index */
3281                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3282                        sizeof(struct bxe_sw_rx_bd));
3283                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3284             }
3285
3286             goto next_rx;
3287         }
3288
3289         /* current mbuf was detached from the bd */
3290         fp->eth_q_stats.mbuf_alloc_rx--;
3291
3292         /* we allocated a replacement mbuf, fixup the current one */
3293         m_adj(m, pad);
3294         m->m_pkthdr.len = m->m_len = len;
3295
3296         if ((len > 60) && (len > lenonbd)) {
3297             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3298             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3299             if (rc)
3300                 break;
3301             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3302         } else if (lenonbd < len) {
3303             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3304         }
3305
3306         /* assign packet to this interface interface */
3307         if_setrcvif(m, ifp);
3308
3309         /* assume no hardware checksum has complated */
3310         m->m_pkthdr.csum_flags = 0;
3311
3312         /* validate checksum if offload enabled */
3313         if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
3314             /* check for a valid IP frame */
3315             if (!(cqe->fast_path_cqe.status_flags &
3316                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3317                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3318                 if (__predict_false(cqe_fp_flags &
3319                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3320                     fp->eth_q_stats.rx_hw_csum_errors++;
3321                 } else {
3322                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3323                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3324                 }
3325             }
3326
3327             /* check for a valid TCP/UDP frame */
3328             if (!(cqe->fast_path_cqe.status_flags &
3329                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3330                 if (__predict_false(cqe_fp_flags &
3331                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3332                     fp->eth_q_stats.rx_hw_csum_errors++;
3333                 } else {
3334                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3335                     m->m_pkthdr.csum_data = 0xFFFF;
3336                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3337                                                CSUM_PSEUDO_HDR);
3338                 }
3339             }
3340         }
3341
3342         /* if there is a VLAN tag then flag that info */
3343         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3344             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3345             m->m_flags |= M_VLANTAG;
3346         }
3347
3348 #if __FreeBSD_version >= 800000
3349         /* specify what RSS queue was used for this flow */
3350         m->m_pkthdr.flowid = fp->index;
3351         BXE_SET_FLOWID(m);
3352 #endif
3353
3354 next_rx:
3355
3356         bd_cons    = RX_BD_NEXT(bd_cons);
3357         bd_prod    = RX_BD_NEXT(bd_prod);
3358         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3359
3360         /* pass the frame to the stack */
3361         if (__predict_true(m != NULL)) {
3362             if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
3363             rx_pkts++;
3364             if_input(ifp, m);
3365         }
3366
3367 next_cqe:
3368
3369         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3370         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3371
3372         /* limit spinning on the queue */
3373         if (rc != 0)
3374             break;
3375
3376         if (rx_pkts == sc->rx_budget) {
3377             fp->eth_q_stats.rx_budget_reached++;
3378             break;
3379         }
3380     } /* while work to do */
3381
3382     fp->rx_bd_cons = bd_cons;
3383     fp->rx_bd_prod = bd_prod_fw;
3384     fp->rx_cq_cons = sw_cq_cons;
3385     fp->rx_cq_prod = sw_cq_prod;
3386
3387     /* Update producers */
3388     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3389
3390     fp->eth_q_stats.rx_pkts += rx_pkts;
3391     fp->eth_q_stats.rx_calls++;
3392
3393     BXE_FP_RX_UNLOCK(fp);
3394
3395     return (sw_cq_cons != hw_cq_cons);
3396 }
3397
3398 static uint16_t
3399 bxe_free_tx_pkt(struct bxe_softc    *sc,
3400                 struct bxe_fastpath *fp,
3401                 uint16_t            idx)
3402 {
3403     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3404     struct eth_tx_start_bd *tx_start_bd;
3405     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3406     uint16_t new_cons;
3407     int nbd;
3408
3409     /* unmap the mbuf from non-paged memory */
3410     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3411
3412     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3413     nbd = le16toh(tx_start_bd->nbd) - 1;
3414
3415     new_cons = (tx_buf->first_bd + nbd);
3416
3417     /* free the mbuf */
3418     if (__predict_true(tx_buf->m != NULL)) {
3419         m_freem(tx_buf->m);
3420         fp->eth_q_stats.mbuf_alloc_tx--;
3421     } else {
3422         fp->eth_q_stats.tx_chain_lost_mbuf++;
3423     }
3424
3425     tx_buf->m = NULL;
3426     tx_buf->first_bd = 0;
3427
3428     return (new_cons);
3429 }
3430
3431 /* transmit timeout watchdog */
3432 static int
3433 bxe_watchdog(struct bxe_softc    *sc,
3434              struct bxe_fastpath *fp)
3435 {
3436     BXE_FP_TX_LOCK(fp);
3437
3438     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3439         BXE_FP_TX_UNLOCK(fp);
3440         return (0);
3441     }
3442
3443     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3444     if(sc->trigger_grcdump) {
3445          /* taking grcdump */
3446          bxe_grc_dump(sc);
3447     }
3448
3449     BXE_FP_TX_UNLOCK(fp);
3450
3451     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3452     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3453
3454     return (-1);
3455 }
3456
3457 /* processes transmit completions */
3458 static uint8_t
3459 bxe_txeof(struct bxe_softc    *sc,
3460           struct bxe_fastpath *fp)
3461 {
3462     if_t ifp = sc->ifp;
3463     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3464     uint16_t tx_bd_avail;
3465
3466     BXE_FP_TX_LOCK_ASSERT(fp);
3467
3468     bd_cons = fp->tx_bd_cons;
3469     hw_cons = le16toh(*fp->tx_cons_sb);
3470     sw_cons = fp->tx_pkt_cons;
3471
3472     while (sw_cons != hw_cons) {
3473         pkt_cons = TX_BD(sw_cons);
3474
3475         BLOGD(sc, DBG_TX,
3476               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3477               fp->index, hw_cons, sw_cons, pkt_cons);
3478
3479         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3480
3481         sw_cons++;
3482     }
3483
3484     fp->tx_pkt_cons = sw_cons;
3485     fp->tx_bd_cons  = bd_cons;
3486
3487     BLOGD(sc, DBG_TX,
3488           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3489           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3490
3491     mb();
3492
3493     tx_bd_avail = bxe_tx_avail(sc, fp);
3494
3495     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3496         if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
3497     } else {
3498         if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
3499     }
3500
3501     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3502         /* reset the watchdog timer if there are pending transmits */
3503         fp->watchdog_timer = BXE_TX_TIMEOUT;
3504         return (TRUE);
3505     } else {
3506         /* clear watchdog when there are no pending transmits */
3507         fp->watchdog_timer = 0;
3508         return (FALSE);
3509     }
3510 }
3511
3512 static void
3513 bxe_drain_tx_queues(struct bxe_softc *sc)
3514 {
3515     struct bxe_fastpath *fp;
3516     int i, count;
3517
3518     /* wait until all TX fastpath tasks have completed */
3519     for (i = 0; i < sc->num_queues; i++) {
3520         fp = &sc->fp[i];
3521
3522         count = 1000;
3523
3524         while (bxe_has_tx_work(fp)) {
3525
3526             BXE_FP_TX_LOCK(fp);
3527             bxe_txeof(sc, fp);
3528             BXE_FP_TX_UNLOCK(fp);
3529
3530             if (count == 0) {
3531                 BLOGE(sc, "Timeout waiting for fp[%d] "
3532                           "transmits to complete!\n", i);
3533                 bxe_panic(sc, ("tx drain failure\n"));
3534                 return;
3535             }
3536
3537             count--;
3538             DELAY(1000);
3539             rmb();
3540         }
3541     }
3542
3543     return;
3544 }
3545
3546 static int
3547 bxe_del_all_macs(struct bxe_softc          *sc,
3548                  struct ecore_vlan_mac_obj *mac_obj,
3549                  int                       mac_type,
3550                  uint8_t                   wait_for_comp)
3551 {
3552     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3553     int rc;
3554
3555     /* wait for completion of requested */
3556     if (wait_for_comp) {
3557         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3558     }
3559
3560     /* Set the mac type of addresses we want to clear */
3561     bxe_set_bit(mac_type, &vlan_mac_flags);
3562
3563     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3564     if (rc < 0) {
3565         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3566             rc, mac_type, wait_for_comp);
3567     }
3568
3569     return (rc);
3570 }
3571
3572 static int
3573 bxe_fill_accept_flags(struct bxe_softc *sc,
3574                       uint32_t         rx_mode,
3575                       unsigned long    *rx_accept_flags,
3576                       unsigned long    *tx_accept_flags)
3577 {
3578     /* Clear the flags first */
3579     *rx_accept_flags = 0;
3580     *tx_accept_flags = 0;
3581
3582     switch (rx_mode) {
3583     case BXE_RX_MODE_NONE:
3584         /*
3585          * 'drop all' supersedes any accept flags that may have been
3586          * passed to the function.
3587          */
3588         break;
3589
3590     case BXE_RX_MODE_NORMAL:
3591         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3592         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3593         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3594
3595         /* internal switching mode */
3596         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3597         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3598         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3599
3600         break;
3601
3602     case BXE_RX_MODE_ALLMULTI:
3603         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3604         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3605         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3606
3607         /* internal switching mode */
3608         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3609         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3610         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3611
3612         break;
3613
3614     case BXE_RX_MODE_PROMISC:
3615         /*
3616          * According to deffinition of SI mode, iface in promisc mode
3617          * should receive matched and unmatched (in resolution of port)
3618          * unicast packets.
3619          */
3620         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3621         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3622         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3623         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3624
3625         /* internal switching mode */
3626         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3627         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3628
3629         if (IS_MF_SI(sc)) {
3630             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3631         } else {
3632             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3633         }
3634
3635         break;
3636
3637     default:
3638         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3639         return (-1);
3640     }
3641
3642     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3643     if (rx_mode != BXE_RX_MODE_NONE) {
3644         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3645         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3646     }
3647
3648     return (0);
3649 }
3650
3651 static int
3652 bxe_set_q_rx_mode(struct bxe_softc *sc,
3653                   uint8_t          cl_id,
3654                   unsigned long    rx_mode_flags,
3655                   unsigned long    rx_accept_flags,
3656                   unsigned long    tx_accept_flags,
3657                   unsigned long    ramrod_flags)
3658 {
3659     struct ecore_rx_mode_ramrod_params ramrod_param;
3660     int rc;
3661
3662     memset(&ramrod_param, 0, sizeof(ramrod_param));
3663
3664     /* Prepare ramrod parameters */
3665     ramrod_param.cid = 0;
3666     ramrod_param.cl_id = cl_id;
3667     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3668     ramrod_param.func_id = SC_FUNC(sc);
3669
3670     ramrod_param.pstate = &sc->sp_state;
3671     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3672
3673     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3674     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3675
3676     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3677
3678     ramrod_param.ramrod_flags = ramrod_flags;
3679     ramrod_param.rx_mode_flags = rx_mode_flags;
3680
3681     ramrod_param.rx_accept_flags = rx_accept_flags;
3682     ramrod_param.tx_accept_flags = tx_accept_flags;
3683
3684     rc = ecore_config_rx_mode(sc, &ramrod_param);
3685     if (rc < 0) {
3686         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3687             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3688             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3689             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3690             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3691         return (rc);
3692     }
3693
3694     return (0);
3695 }
3696
3697 static int
3698 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3699 {
3700     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3701     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3702     int rc;
3703
3704     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3705                                &tx_accept_flags);
3706     if (rc) {
3707         return (rc);
3708     }
3709
3710     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3711     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3712
3713     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3714     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3715                               rx_accept_flags, tx_accept_flags,
3716                               ramrod_flags));
3717 }
3718
3719 /* returns the "mcp load_code" according to global load_count array */
3720 static int
3721 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3722 {
3723     int path = SC_PATH(sc);
3724     int port = SC_PORT(sc);
3725
3726     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3727           path, load_count[path][0], load_count[path][1],
3728           load_count[path][2]);
3729     load_count[path][0]++;
3730     load_count[path][1 + port]++;
3731     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3732           path, load_count[path][0], load_count[path][1],
3733           load_count[path][2]);
3734     if (load_count[path][0] == 1) {
3735         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3736     } else if (load_count[path][1 + port] == 1) {
3737         return (FW_MSG_CODE_DRV_LOAD_PORT);
3738     } else {
3739         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3740     }
3741 }
3742
3743 /* returns the "mcp load_code" according to global load_count array */
3744 static int
3745 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3746 {
3747     int port = SC_PORT(sc);
3748     int path = SC_PATH(sc);
3749
3750     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3751           path, load_count[path][0], load_count[path][1],
3752           load_count[path][2]);
3753     load_count[path][0]--;
3754     load_count[path][1 + port]--;
3755     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3756           path, load_count[path][0], load_count[path][1],
3757           load_count[path][2]);
3758     if (load_count[path][0] == 0) {
3759         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3760     } else if (load_count[path][1 + port] == 0) {
3761         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3762     } else {
3763         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3764     }
3765 }
3766
3767 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3768 static uint32_t
3769 bxe_send_unload_req(struct bxe_softc *sc,
3770                     int              unload_mode)
3771 {
3772     uint32_t reset_code = 0;
3773
3774     /* Select the UNLOAD request mode */
3775     if (unload_mode == UNLOAD_NORMAL) {
3776         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3777     } else {
3778         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3779     }
3780
3781     /* Send the request to the MCP */
3782     if (!BXE_NOMCP(sc)) {
3783         reset_code = bxe_fw_command(sc, reset_code, 0);
3784     } else {
3785         reset_code = bxe_nic_unload_no_mcp(sc);
3786     }
3787
3788     return (reset_code);
3789 }
3790
3791 /* send UNLOAD_DONE command to the MCP */
3792 static void
3793 bxe_send_unload_done(struct bxe_softc *sc,
3794                      uint8_t          keep_link)
3795 {
3796     uint32_t reset_param =
3797         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3798
3799     /* Report UNLOAD_DONE to MCP */
3800     if (!BXE_NOMCP(sc)) {
3801         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3802     }
3803 }
3804
3805 static int
3806 bxe_func_wait_started(struct bxe_softc *sc)
3807 {
3808     int tout = 50;
3809
3810     if (!sc->port.pmf) {
3811         return (0);
3812     }
3813
3814     /*
3815      * (assumption: No Attention from MCP at this stage)
3816      * PMF probably in the middle of TX disable/enable transaction
3817      * 1. Sync IRS for default SB
3818      * 2. Sync SP queue - this guarantees us that attention handling started
3819      * 3. Wait, that TX disable/enable transaction completes
3820      *
3821      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3822      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3823      * received completion for the transaction the state is TX_STOPPED.
3824      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3825      * transaction.
3826      */
3827
3828     /* XXX make sure default SB ISR is done */
3829     /* need a way to synchronize an irq (intr_mtx?) */
3830
3831     /* XXX flush any work queues */
3832
3833     while (ecore_func_get_state(sc, &sc->func_obj) !=
3834            ECORE_F_STATE_STARTED && tout--) {
3835         DELAY(20000);
3836     }
3837
3838     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3839         /*
3840          * Failed to complete the transaction in a "good way"
3841          * Force both transactions with CLR bit.
3842          */
3843         struct ecore_func_state_params func_params = { NULL };
3844
3845         BLOGE(sc, "Unexpected function state! "
3846                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3847
3848         func_params.f_obj = &sc->func_obj;
3849         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3850
3851         /* STARTED-->TX_STOPPED */
3852         func_params.cmd = ECORE_F_CMD_TX_STOP;
3853         ecore_func_state_change(sc, &func_params);
3854
3855         /* TX_STOPPED-->STARTED */
3856         func_params.cmd = ECORE_F_CMD_TX_START;
3857         return (ecore_func_state_change(sc, &func_params));
3858     }
3859
3860     return (0);
3861 }
3862
3863 static int
3864 bxe_stop_queue(struct bxe_softc *sc,
3865                int              index)
3866 {
3867     struct bxe_fastpath *fp = &sc->fp[index];
3868     struct ecore_queue_state_params q_params = { NULL };
3869     int rc;
3870
3871     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3872
3873     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3874     /* We want to wait for completion in this context */
3875     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3876
3877     /* Stop the primary connection: */
3878
3879     /* ...halt the connection */
3880     q_params.cmd = ECORE_Q_CMD_HALT;
3881     rc = ecore_queue_state_change(sc, &q_params);
3882     if (rc) {
3883         return (rc);
3884     }
3885
3886     /* ...terminate the connection */
3887     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3888     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3889     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3890     rc = ecore_queue_state_change(sc, &q_params);
3891     if (rc) {
3892         return (rc);
3893     }
3894
3895     /* ...delete cfc entry */
3896     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3897     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3898     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3899     return (ecore_queue_state_change(sc, &q_params));
3900 }
3901
3902 /* wait for the outstanding SP commands */
3903 static inline uint8_t
3904 bxe_wait_sp_comp(struct bxe_softc *sc,
3905                  unsigned long    mask)
3906 {
3907     unsigned long tmp;
3908     int tout = 5000; /* wait for 5 secs tops */
3909
3910     while (tout--) {
3911         mb();
3912         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3913             return (TRUE);
3914         }
3915
3916         DELAY(1000);
3917     }
3918
3919     mb();
3920
3921     tmp = atomic_load_acq_long(&sc->sp_state);
3922     if (tmp & mask) {
3923         BLOGE(sc, "Filtering completion timed out: "
3924                   "sp_state 0x%lx, mask 0x%lx\n",
3925               tmp, mask);
3926         return (FALSE);
3927     }
3928
3929     return (FALSE);
3930 }
3931
3932 static int
3933 bxe_func_stop(struct bxe_softc *sc)
3934 {
3935     struct ecore_func_state_params func_params = { NULL };
3936     int rc;
3937
3938     /* prepare parameters for function state transitions */
3939     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3940     func_params.f_obj = &sc->func_obj;
3941     func_params.cmd = ECORE_F_CMD_STOP;
3942
3943     /*
3944      * Try to stop the function the 'good way'. If it fails (in case
3945      * of a parity error during bxe_chip_cleanup()) and we are
3946      * not in a debug mode, perform a state transaction in order to
3947      * enable further HW_RESET transaction.
3948      */
3949     rc = ecore_func_state_change(sc, &func_params);
3950     if (rc) {
3951         BLOGE(sc, "FUNC_STOP ramrod failed. "
3952                   "Running a dry transaction (%d)\n", rc);
3953         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3954         return (ecore_func_state_change(sc, &func_params));
3955     }
3956
3957     return (0);
3958 }
3959
3960 static int
3961 bxe_reset_hw(struct bxe_softc *sc,
3962              uint32_t         load_code)
3963 {
3964     struct ecore_func_state_params func_params = { NULL };
3965
3966     /* Prepare parameters for function state transitions */
3967     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3968
3969     func_params.f_obj = &sc->func_obj;
3970     func_params.cmd = ECORE_F_CMD_HW_RESET;
3971
3972     func_params.params.hw_init.load_phase = load_code;
3973
3974     return (ecore_func_state_change(sc, &func_params));
3975 }
3976
3977 static void
3978 bxe_int_disable_sync(struct bxe_softc *sc,
3979                      int              disable_hw)
3980 {
3981     if (disable_hw) {
3982         /* prevent the HW from sending interrupts */
3983         bxe_int_disable(sc);
3984     }
3985
3986     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
3987     /* make sure all ISRs are done */
3988
3989     /* XXX make sure sp_task is not running */
3990     /* cancel and flush work queues */
3991 }
3992
3993 static void
3994 bxe_chip_cleanup(struct bxe_softc *sc,
3995                  uint32_t         unload_mode,
3996                  uint8_t          keep_link)
3997 {
3998     int port = SC_PORT(sc);
3999     struct ecore_mcast_ramrod_params rparam = { NULL };
4000     uint32_t reset_code;
4001     int i, rc = 0;
4002
4003     bxe_drain_tx_queues(sc);
4004
4005     /* give HW time to discard old tx messages */
4006     DELAY(1000);
4007
4008     /* Clean all ETH MACs */
4009     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4010     if (rc < 0) {
4011         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4012     }
4013
4014     /* Clean up UC list  */
4015     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4016     if (rc < 0) {
4017         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4018     }
4019
4020     /* Disable LLH */
4021     if (!CHIP_IS_E1(sc)) {
4022         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4023     }
4024
4025     /* Set "drop all" to stop Rx */
4026
4027     /*
4028      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4029      * a race between the completion code and this code.
4030      */
4031     BXE_MCAST_LOCK(sc);
4032
4033     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4034         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4035     } else {
4036         bxe_set_storm_rx_mode(sc);
4037     }
4038
4039     /* Clean up multicast configuration */
4040     rparam.mcast_obj = &sc->mcast_obj;
4041     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4042     if (rc < 0) {
4043         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4044     }
4045
4046     BXE_MCAST_UNLOCK(sc);
4047
4048     // XXX bxe_iov_chip_cleanup(sc);
4049
4050     /*
4051      * Send the UNLOAD_REQUEST to the MCP. This will return if
4052      * this function should perform FUNCTION, PORT, or COMMON HW
4053      * reset.
4054      */
4055     reset_code = bxe_send_unload_req(sc, unload_mode);
4056
4057     /*
4058      * (assumption: No Attention from MCP at this stage)
4059      * PMF probably in the middle of TX disable/enable transaction
4060      */
4061     rc = bxe_func_wait_started(sc);
4062     if (rc) {
4063         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4064     }
4065
4066     /*
4067      * Close multi and leading connections
4068      * Completions for ramrods are collected in a synchronous way
4069      */
4070     for (i = 0; i < sc->num_queues; i++) {
4071         if (bxe_stop_queue(sc, i)) {
4072             goto unload_error;
4073         }
4074     }
4075
4076     /*
4077      * If SP settings didn't get completed so far - something
4078      * very wrong has happen.
4079      */
4080     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4081         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4082     }
4083
4084 unload_error:
4085
4086     rc = bxe_func_stop(sc);
4087     if (rc) {
4088         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4089     }
4090
4091     /* disable HW interrupts */
4092     bxe_int_disable_sync(sc, TRUE);
4093
4094     /* detach interrupts */
4095     bxe_interrupt_detach(sc);
4096
4097     /* Reset the chip */
4098     rc = bxe_reset_hw(sc, reset_code);
4099     if (rc) {
4100         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4101     }
4102
4103     /* Report UNLOAD_DONE to MCP */
4104     bxe_send_unload_done(sc, keep_link);
4105 }
4106
4107 static void
4108 bxe_disable_close_the_gate(struct bxe_softc *sc)
4109 {
4110     uint32_t val;
4111     int port = SC_PORT(sc);
4112
4113     BLOGD(sc, DBG_LOAD,
4114           "Disabling 'close the gates'\n");
4115
4116     if (CHIP_IS_E1(sc)) {
4117         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4118                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4119         val = REG_RD(sc, addr);
4120         val &= ~(0x300);
4121         REG_WR(sc, addr, val);
4122     } else {
4123         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4124         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4125                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4126         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4127     }
4128 }
4129
4130 /*
4131  * Cleans the object that have internal lists without sending
4132  * ramrods. Should be run when interrutps are disabled.
4133  */
4134 static void
4135 bxe_squeeze_objects(struct bxe_softc *sc)
4136 {
4137     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4138     struct ecore_mcast_ramrod_params rparam = { NULL };
4139     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4140     int rc;
4141
4142     /* Cleanup MACs' object first... */
4143
4144     /* Wait for completion of requested */
4145     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4146     /* Perform a dry cleanup */
4147     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4148
4149     /* Clean ETH primary MAC */
4150     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4151     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4152                              &ramrod_flags);
4153     if (rc != 0) {
4154         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4155     }
4156
4157     /* Cleanup UC list */
4158     vlan_mac_flags = 0;
4159     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4160     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4161                              &ramrod_flags);
4162     if (rc != 0) {
4163         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4164     }
4165
4166     /* Now clean mcast object... */
4167
4168     rparam.mcast_obj = &sc->mcast_obj;
4169     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4170
4171     /* Add a DEL command... */
4172     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4173     if (rc < 0) {
4174         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4175     }
4176
4177     /* now wait until all pending commands are cleared */
4178
4179     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4180     while (rc != 0) {
4181         if (rc < 0) {
4182             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4183             return;
4184         }
4185
4186         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4187     }
4188 }
4189
4190 /* stop the controller */
4191 static __noinline int
4192 bxe_nic_unload(struct bxe_softc *sc,
4193                uint32_t         unload_mode,
4194                uint8_t          keep_link)
4195 {
4196     uint8_t global = FALSE;
4197     uint32_t val;
4198     int i;
4199
4200     BXE_CORE_LOCK_ASSERT(sc);
4201
4202     if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
4203
4204     for (i = 0; i < sc->num_queues; i++) {
4205         struct bxe_fastpath *fp;
4206
4207         fp = &sc->fp[i];
4208         BXE_FP_TX_LOCK(fp);
4209         BXE_FP_TX_UNLOCK(fp);
4210     }
4211
4212     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4213
4214     /* mark driver as unloaded in shmem2 */
4215     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4216         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4217         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4218                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4219     }
4220
4221     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4222         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4223         /*
4224          * We can get here if the driver has been unloaded
4225          * during parity error recovery and is either waiting for a
4226          * leader to complete or for other functions to unload and
4227          * then ifconfig down has been issued. In this case we want to
4228          * unload and let other functions to complete a recovery
4229          * process.
4230          */
4231         sc->recovery_state = BXE_RECOVERY_DONE;
4232         sc->is_leader = 0;
4233         bxe_release_leader_lock(sc);
4234         mb();
4235
4236         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4237         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4238             " state = 0x%x\n", sc->recovery_state, sc->state);
4239         return (-1);
4240     }
4241
4242     /*
4243      * Nothing to do during unload if previous bxe_nic_load()
4244      * did not completed successfully - all resourses are released.
4245      */
4246     if ((sc->state == BXE_STATE_CLOSED) ||
4247         (sc->state == BXE_STATE_ERROR)) {
4248         return (0);
4249     }
4250
4251     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4252     mb();
4253
4254     /* stop tx */
4255     bxe_tx_disable(sc);
4256
4257     sc->rx_mode = BXE_RX_MODE_NONE;
4258     /* XXX set rx mode ??? */
4259
4260     if (IS_PF(sc) && !sc->grcdump_done) {
4261         /* set ALWAYS_ALIVE bit in shmem */
4262         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4263
4264         bxe_drv_pulse(sc);
4265
4266         bxe_stats_handle(sc, STATS_EVENT_STOP);
4267         bxe_save_statistics(sc);
4268     }
4269
4270     /* wait till consumers catch up with producers in all queues */
4271     bxe_drain_tx_queues(sc);
4272
4273     /* if VF indicate to PF this function is going down (PF will delete sp
4274      * elements and clear initializations
4275      */
4276     if (IS_VF(sc)) {
4277         ; /* bxe_vfpf_close_vf(sc); */
4278     } else if (unload_mode != UNLOAD_RECOVERY) {
4279         /* if this is a normal/close unload need to clean up chip */
4280         if (!sc->grcdump_done)
4281             bxe_chip_cleanup(sc, unload_mode, keep_link);
4282     } else {
4283         /* Send the UNLOAD_REQUEST to the MCP */
4284         bxe_send_unload_req(sc, unload_mode);
4285
4286         /*
4287          * Prevent transactions to host from the functions on the
4288          * engine that doesn't reset global blocks in case of global
4289          * attention once gloabl blocks are reset and gates are opened
4290          * (the engine which leader will perform the recovery
4291          * last).
4292          */
4293         if (!CHIP_IS_E1x(sc)) {
4294             bxe_pf_disable(sc);
4295         }
4296
4297         /* disable HW interrupts */
4298         bxe_int_disable_sync(sc, TRUE);
4299
4300         /* detach interrupts */
4301         bxe_interrupt_detach(sc);
4302
4303         /* Report UNLOAD_DONE to MCP */
4304         bxe_send_unload_done(sc, FALSE);
4305     }
4306
4307     /*
4308      * At this stage no more interrupts will arrive so we may safely clean
4309      * the queue'able objects here in case they failed to get cleaned so far.
4310      */
4311     if (IS_PF(sc)) {
4312         bxe_squeeze_objects(sc);
4313     }
4314
4315     /* There should be no more pending SP commands at this stage */
4316     sc->sp_state = 0;
4317
4318     sc->port.pmf = 0;
4319
4320     bxe_free_fp_buffers(sc);
4321
4322     if (IS_PF(sc)) {
4323         bxe_free_mem(sc);
4324     }
4325
4326     bxe_free_fw_stats_mem(sc);
4327
4328     sc->state = BXE_STATE_CLOSED;
4329
4330     /*
4331      * Check if there are pending parity attentions. If there are - set
4332      * RECOVERY_IN_PROGRESS.
4333      */
4334     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4335         bxe_set_reset_in_progress(sc);
4336
4337         /* Set RESET_IS_GLOBAL if needed */
4338         if (global) {
4339             bxe_set_reset_global(sc);
4340         }
4341     }
4342
4343     /*
4344      * The last driver must disable a "close the gate" if there is no
4345      * parity attention or "process kill" pending.
4346      */
4347     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4348         bxe_reset_is_done(sc, SC_PATH(sc))) {
4349         bxe_disable_close_the_gate(sc);
4350     }
4351
4352     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4353
4354     return (0);
4355 }
4356
4357 /*
4358  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4359  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4360  */
4361 static int
4362 bxe_ifmedia_update(struct ifnet  *ifp)
4363 {
4364     struct bxe_softc *sc = (struct bxe_softc *)if_getsoftc(ifp);
4365     struct ifmedia *ifm;
4366
4367     ifm = &sc->ifmedia;
4368
4369     /* We only support Ethernet media type. */
4370     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4371         return (EINVAL);
4372     }
4373
4374     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4375     case IFM_AUTO:
4376          break;
4377     case IFM_10G_CX4:
4378     case IFM_10G_SR:
4379     case IFM_10G_T:
4380     case IFM_10G_TWINAX:
4381     default:
4382         /* We don't support changing the media type. */
4383         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4384               IFM_SUBTYPE(ifm->ifm_media));
4385         return (EINVAL);
4386     }
4387
4388     return (0);
4389 }
4390
4391 /*
4392  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4393  */
4394 static void
4395 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4396 {
4397     struct bxe_softc *sc = if_getsoftc(ifp);
4398
4399     /* Report link down if the driver isn't running. */
4400     if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
4401         ifmr->ifm_active |= IFM_NONE;
4402         return;
4403     }
4404
4405     /* Setup the default interface info. */
4406     ifmr->ifm_status = IFM_AVALID;
4407     ifmr->ifm_active = IFM_ETHER;
4408
4409     if (sc->link_vars.link_up) {
4410         ifmr->ifm_status |= IFM_ACTIVE;
4411     } else {
4412         ifmr->ifm_active |= IFM_NONE;
4413         return;
4414     }
4415
4416     ifmr->ifm_active |= sc->media;
4417
4418     if (sc->link_vars.duplex == DUPLEX_FULL) {
4419         ifmr->ifm_active |= IFM_FDX;
4420     } else {
4421         ifmr->ifm_active |= IFM_HDX;
4422     }
4423 }
4424
4425 static void
4426 bxe_handle_chip_tq(void *context,
4427                    int  pending)
4428 {
4429     struct bxe_softc *sc = (struct bxe_softc *)context;
4430     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4431
4432     switch (work)
4433     {
4434
4435     case CHIP_TQ_REINIT:
4436         if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
4437             /* restart the interface */
4438             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4439             bxe_periodic_stop(sc);
4440             BXE_CORE_LOCK(sc);
4441             bxe_stop_locked(sc);
4442             bxe_init_locked(sc);
4443             BXE_CORE_UNLOCK(sc);
4444         }
4445         break;
4446
4447     default:
4448         break;
4449     }
4450 }
4451
4452 /*
4453  * Handles any IOCTL calls from the operating system.
4454  *
4455  * Returns:
4456  *   0 = Success, >0 Failure
4457  */
4458 static int
4459 bxe_ioctl(if_t ifp,
4460           u_long       command,
4461           caddr_t      data)
4462 {
4463     struct bxe_softc *sc = if_getsoftc(ifp);
4464     struct ifreq *ifr = (struct ifreq *)data;
4465     int mask = 0;
4466     int reinit = 0;
4467     int error = 0;
4468
4469     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4470     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4471
4472     switch (command)
4473     {
4474     case SIOCSIFMTU:
4475         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4476               ifr->ifr_mtu);
4477
4478         if (sc->mtu == ifr->ifr_mtu) {
4479             /* nothing to change */
4480             break;
4481         }
4482
4483         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4484             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4485                   ifr->ifr_mtu, mtu_min, mtu_max);
4486             error = EINVAL;
4487             break;
4488         }
4489
4490         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4491                              (unsigned long)ifr->ifr_mtu);
4492         /* 
4493         atomic_store_rel_long((volatile unsigned long *)&if_getmtu(ifp),
4494                               (unsigned long)ifr->ifr_mtu);
4495         XXX - Not sure why it needs to be atomic
4496         */
4497         if_setmtu(ifp, ifr->ifr_mtu);
4498         reinit = 1;
4499         break;
4500
4501     case SIOCSIFFLAGS:
4502         /* toggle the interface state up or down */
4503         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4504
4505         BXE_CORE_LOCK(sc);
4506         /* check if the interface is up */
4507         if (if_getflags(ifp) & IFF_UP) {
4508             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4509                 /* set the receive mode flags */
4510                 bxe_set_rx_mode(sc);
4511             } else if(sc->state != BXE_STATE_DISABLED) {
4512                 bxe_init_locked(sc);
4513             }
4514         } else {
4515             if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4516                 bxe_periodic_stop(sc);
4517                 bxe_stop_locked(sc);
4518             }
4519         }
4520         BXE_CORE_UNLOCK(sc);
4521
4522         break;
4523
4524     case SIOCADDMULTI:
4525     case SIOCDELMULTI:
4526         /* add/delete multicast addresses */
4527         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4528
4529         /* check if the interface is up */
4530         if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
4531             /* set the receive mode flags */
4532             BXE_CORE_LOCK(sc);
4533             bxe_set_rx_mode(sc);
4534             BXE_CORE_UNLOCK(sc); 
4535         }
4536
4537         break;
4538
4539     case SIOCSIFCAP:
4540         /* find out which capabilities have changed */
4541         mask = (ifr->ifr_reqcap ^ if_getcapenable(ifp));
4542
4543         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4544               mask);
4545
4546         /* toggle the LRO capabilites enable flag */
4547         if (mask & IFCAP_LRO) {
4548             if_togglecapenable(ifp, IFCAP_LRO);
4549             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4550                   (if_getcapenable(ifp) & IFCAP_LRO) ? "ON" : "OFF");
4551             reinit = 1;
4552         }
4553
4554         /* toggle the TXCSUM checksum capabilites enable flag */
4555         if (mask & IFCAP_TXCSUM) {
4556             if_togglecapenable(ifp, IFCAP_TXCSUM);
4557             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4558                   (if_getcapenable(ifp) & IFCAP_TXCSUM) ? "ON" : "OFF");
4559             if (if_getcapenable(ifp) & IFCAP_TXCSUM) {
4560                 if_sethwassistbits(ifp, (CSUM_IP      | 
4561                                     CSUM_TCP      |
4562                                     CSUM_UDP      |
4563                                     CSUM_TSO      |
4564                                     CSUM_TCP_IPV6 |
4565                                     CSUM_UDP_IPV6), 0);
4566             } else {
4567                 if_clearhwassist(ifp); /* XXX */
4568             }
4569         }
4570
4571         /* toggle the RXCSUM checksum capabilities enable flag */
4572         if (mask & IFCAP_RXCSUM) {
4573             if_togglecapenable(ifp, IFCAP_RXCSUM);
4574             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4575                   (if_getcapenable(ifp) & IFCAP_RXCSUM) ? "ON" : "OFF");
4576             if (if_getcapenable(ifp) & IFCAP_RXCSUM) {
4577                 if_sethwassistbits(ifp, (CSUM_IP      |
4578                                     CSUM_TCP      |
4579                                     CSUM_UDP      |
4580                                     CSUM_TSO      |
4581                                     CSUM_TCP_IPV6 |
4582                                     CSUM_UDP_IPV6), 0);
4583             } else {
4584                 if_clearhwassist(ifp); /* XXX */
4585             }
4586         }
4587
4588         /* toggle TSO4 capabilities enabled flag */
4589         if (mask & IFCAP_TSO4) {
4590             if_togglecapenable(ifp, IFCAP_TSO4);
4591             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4592                   (if_getcapenable(ifp) & IFCAP_TSO4) ? "ON" : "OFF");
4593         }
4594
4595         /* toggle TSO6 capabilities enabled flag */
4596         if (mask & IFCAP_TSO6) {
4597             if_togglecapenable(ifp, IFCAP_TSO6);
4598             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4599                   (if_getcapenable(ifp) & IFCAP_TSO6) ? "ON" : "OFF");
4600         }
4601
4602         /* toggle VLAN_HWTSO capabilities enabled flag */
4603         if (mask & IFCAP_VLAN_HWTSO) {
4604
4605             if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
4606             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4607                   (if_getcapenable(ifp) & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4608         }
4609
4610         /* toggle VLAN_HWCSUM capabilities enabled flag */
4611         if (mask & IFCAP_VLAN_HWCSUM) {
4612             /* XXX investigate this... */
4613             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4614             error = EINVAL;
4615         }
4616
4617         /* toggle VLAN_MTU capabilities enable flag */
4618         if (mask & IFCAP_VLAN_MTU) {
4619             /* XXX investigate this... */
4620             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4621             error = EINVAL;
4622         }
4623
4624         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4625         if (mask & IFCAP_VLAN_HWTAGGING) {
4626             /* XXX investigate this... */
4627             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4628             error = EINVAL;
4629         }
4630
4631         /* toggle VLAN_HWFILTER capabilities enabled flag */
4632         if (mask & IFCAP_VLAN_HWFILTER) {
4633             /* XXX investigate this... */
4634             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4635             error = EINVAL;
4636         }
4637
4638         /* XXX not yet...
4639          * IFCAP_WOL_MAGIC
4640          */
4641
4642         break;
4643
4644     case SIOCSIFMEDIA:
4645     case SIOCGIFMEDIA:
4646         /* set/get interface media */
4647         BLOGD(sc, DBG_IOCTL,
4648               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4649               (command & 0xff));
4650         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4651         break;
4652
4653     default:
4654         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4655               (command & 0xff));
4656         error = ether_ioctl(ifp, command, data);
4657         break;
4658     }
4659
4660     if (reinit && (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
4661         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4662               "Re-initializing hardware from IOCTL change\n");
4663         bxe_periodic_stop(sc);
4664         BXE_CORE_LOCK(sc);
4665         bxe_stop_locked(sc);
4666         bxe_init_locked(sc);
4667         BXE_CORE_UNLOCK(sc);
4668     }
4669
4670     return (error);
4671 }
4672
4673 static __noinline void
4674 bxe_dump_mbuf(struct bxe_softc *sc,
4675               struct mbuf      *m,
4676               uint8_t          contents)
4677 {
4678     char * type;
4679     int i = 0;
4680
4681     if (!(sc->debug & DBG_MBUF)) {
4682         return;
4683     }
4684
4685     if (m == NULL) {
4686         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4687         return;
4688     }
4689
4690     while (m) {
4691
4692 #if __FreeBSD_version >= 1000000
4693         BLOGD(sc, DBG_MBUF,
4694               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4695               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4696
4697         if (m->m_flags & M_PKTHDR) {
4698              BLOGD(sc, DBG_MBUF,
4699                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4700                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4701                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4702         }
4703 #else
4704         BLOGD(sc, DBG_MBUF,
4705               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4706               i, m, m->m_len, m->m_flags,
4707               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4708
4709         if (m->m_flags & M_PKTHDR) {
4710              BLOGD(sc, DBG_MBUF,
4711                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4712                    i, m->m_pkthdr.len, m->m_flags,
4713                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4714                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4715                    "\22M_PROMISC\23M_NOFREE",
4716                    (int)m->m_pkthdr.csum_flags,
4717                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4718                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4719                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4720                    "\14CSUM_PSEUDO_HDR");
4721         }
4722 #endif /* #if __FreeBSD_version >= 1000000 */
4723
4724         if (m->m_flags & M_EXT) {
4725             switch (m->m_ext.ext_type) {
4726             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4727             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4728             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4729             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4730             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4731             case EXT_PACKET:     type = "EXT_PACKET";     break;
4732             case EXT_MBUF:       type = "EXT_MBUF";       break;
4733             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4734             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4735             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4736             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4737             default:             type = "UNKNOWN";        break;
4738             }
4739
4740             BLOGD(sc, DBG_MBUF,
4741                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4742                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4743         }
4744
4745         if (contents) {
4746             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4747         }
4748
4749         m = m->m_next;
4750         i++;
4751     }
4752 }
4753
4754 /*
4755  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4756  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4757  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4758  * The headers comes in a separate bd in FreeBSD so 13-3=10.
4759  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4760  */
4761 static int
4762 bxe_chktso_window(struct bxe_softc  *sc,
4763                   int               nsegs,
4764                   bus_dma_segment_t *segs,
4765                   struct mbuf       *m)
4766 {
4767     uint32_t num_wnds, wnd_size, wnd_sum;
4768     int32_t frag_idx, wnd_idx;
4769     unsigned short lso_mss;
4770     int defrag;
4771
4772     defrag = 0;
4773     wnd_sum = 0;
4774     wnd_size = 10;
4775     num_wnds = nsegs - wnd_size;
4776     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4777
4778     /*
4779      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4780      * first window sum of data while skipping the first assuming it is the
4781      * header in FreeBSD.
4782      */
4783     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4784         wnd_sum += htole16(segs[frag_idx].ds_len);
4785     }
4786
4787     /* check the first 10 bd window size */
4788     if (wnd_sum < lso_mss) {
4789         return (1);
4790     }
4791
4792     /* run through the windows */
4793     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4794         /* subtract the first mbuf->m_len of the last wndw(-header) */
4795         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4796         /* add the next mbuf len to the len of our new window */
4797         wnd_sum += htole16(segs[frag_idx].ds_len);
4798         if (wnd_sum < lso_mss) {
4799             return (1);
4800         }
4801     }
4802
4803     return (0);
4804 }
4805
4806 static uint8_t
4807 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4808                     struct mbuf         *m,
4809                     uint32_t            *parsing_data)
4810 {
4811     struct ether_vlan_header *eh = NULL;
4812     struct ip *ip4 = NULL;
4813     struct ip6_hdr *ip6 = NULL;
4814     caddr_t ip = NULL;
4815     struct tcphdr *th = NULL;
4816     int e_hlen, ip_hlen, l4_off;
4817     uint16_t proto;
4818
4819     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4820         /* no L4 checksum offload needed */
4821         return (0);
4822     }
4823
4824     /* get the Ethernet header */
4825     eh = mtod(m, struct ether_vlan_header *);
4826
4827     /* handle VLAN encapsulation if present */
4828     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4829         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4830         proto  = ntohs(eh->evl_proto);
4831     } else {
4832         e_hlen = ETHER_HDR_LEN;
4833         proto  = ntohs(eh->evl_encap_proto);
4834     }
4835
4836     switch (proto) {
4837     case ETHERTYPE_IP:
4838         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4839         ip4 = (m->m_len < sizeof(struct ip)) ?
4840                   (struct ip *)m->m_next->m_data :
4841                   (struct ip *)(m->m_data + e_hlen);
4842         /* ip_hl is number of 32-bit words */
4843         ip_hlen = (ip4->ip_hl << 2);
4844         ip = (caddr_t)ip4;
4845         break;
4846     case ETHERTYPE_IPV6:
4847         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4848         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4849                   (struct ip6_hdr *)m->m_next->m_data :
4850                   (struct ip6_hdr *)(m->m_data + e_hlen);
4851         /* XXX cannot support offload with IPv6 extensions */
4852         ip_hlen = sizeof(struct ip6_hdr);
4853         ip = (caddr_t)ip6;
4854         break;
4855     default:
4856         /* We can't offload in this case... */
4857         /* XXX error stat ??? */
4858         return (0);
4859     }
4860
4861     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4862     l4_off = (e_hlen + ip_hlen);
4863
4864     *parsing_data |=
4865         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4866          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4867
4868     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4869                                   CSUM_TSO |
4870                                   CSUM_TCP_IPV6)) {
4871         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4872         th = (struct tcphdr *)(ip + ip_hlen);
4873         /* th_off is number of 32-bit words */
4874         *parsing_data |= ((th->th_off <<
4875                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4876                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4877         return (l4_off + (th->th_off << 2)); /* entire header length */
4878     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4879                                          CSUM_UDP_IPV6)) {
4880         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4881         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4882     } else {
4883         /* XXX error stat ??? */
4884         return (0);
4885     }
4886 }
4887
4888 static uint8_t
4889 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4890                  struct mbuf                *m,
4891                  struct eth_tx_parse_bd_e1x *pbd)
4892 {
4893     struct ether_vlan_header *eh = NULL;
4894     struct ip *ip4 = NULL;
4895     struct ip6_hdr *ip6 = NULL;
4896     caddr_t ip = NULL;
4897     struct tcphdr *th = NULL;
4898     struct udphdr *uh = NULL;
4899     int e_hlen, ip_hlen;
4900     uint16_t proto;
4901     uint8_t hlen;
4902     uint16_t tmp_csum;
4903     uint32_t *tmp_uh;
4904
4905     /* get the Ethernet header */
4906     eh = mtod(m, struct ether_vlan_header *);
4907
4908     /* handle VLAN encapsulation if present */
4909     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4910         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4911         proto  = ntohs(eh->evl_proto);
4912     } else {
4913         e_hlen = ETHER_HDR_LEN;
4914         proto  = ntohs(eh->evl_encap_proto);
4915     }
4916
4917     switch (proto) {
4918     case ETHERTYPE_IP:
4919         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4920         ip4 = (m->m_len < sizeof(struct ip)) ?
4921                   (struct ip *)m->m_next->m_data :
4922                   (struct ip *)(m->m_data + e_hlen);
4923         /* ip_hl is number of 32-bit words */
4924         ip_hlen = (ip4->ip_hl << 1);
4925         ip = (caddr_t)ip4;
4926         break;
4927     case ETHERTYPE_IPV6:
4928         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4929         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4930                   (struct ip6_hdr *)m->m_next->m_data :
4931                   (struct ip6_hdr *)(m->m_data + e_hlen);
4932         /* XXX cannot support offload with IPv6 extensions */
4933         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4934         ip = (caddr_t)ip6;
4935         break;
4936     default:
4937         /* We can't offload in this case... */
4938         /* XXX error stat ??? */
4939         return (0);
4940     }
4941
4942     hlen = (e_hlen >> 1);
4943
4944     /* note that rest of global_data is indirectly zeroed here */
4945     if (m->m_flags & M_VLANTAG) {
4946         pbd->global_data =
4947             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4948     } else {
4949         pbd->global_data = htole16(hlen);
4950     }
4951
4952     pbd->ip_hlen_w = ip_hlen;
4953
4954     hlen += pbd->ip_hlen_w;
4955
4956     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4957
4958     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4959                                   CSUM_TSO |
4960                                   CSUM_TCP_IPV6)) {
4961         th = (struct tcphdr *)(ip + (ip_hlen << 1));
4962         /* th_off is number of 32-bit words */
4963         hlen += (uint16_t)(th->th_off << 1);
4964     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4965                                          CSUM_UDP_IPV6)) {
4966         uh = (struct udphdr *)(ip + (ip_hlen << 1));
4967         hlen += (sizeof(struct udphdr) / 2);
4968     } else {
4969         /* valid case as only CSUM_IP was set */
4970         return (0);
4971     }
4972
4973     pbd->total_hlen_w = htole16(hlen);
4974
4975     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4976                                   CSUM_TSO |
4977                                   CSUM_TCP_IPV6)) {
4978         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4979         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
4980     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4981                                          CSUM_UDP_IPV6)) {
4982         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4983
4984         /*
4985          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
4986          * checksums and does not know anything about the UDP header and where
4987          * the checksum field is located. It only knows about TCP. Therefore
4988          * we "lie" to the hardware for outgoing UDP packets w/ checksum
4989          * offload. Since the checksum field offset for TCP is 16 bytes and
4990          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
4991          * bytes less than the start of the UDP header. This allows the
4992          * hardware to write the checksum in the correct spot. But the
4993          * hardware will compute a checksum which includes the last 10 bytes
4994          * of the IP header. To correct this we tweak the stack computed
4995          * pseudo checksum by folding in the calculation of the inverse
4996          * checksum for those final 10 bytes of the IP header. This allows
4997          * the correct checksum to be computed by the hardware.
4998          */
4999
5000         /* set pointer 10 bytes before UDP header */
5001         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5002
5003         /* calculate a pseudo header checksum over the first 10 bytes */
5004         tmp_csum = in_pseudo(*tmp_uh,
5005                              *(tmp_uh + 1),
5006                              *(uint16_t *)(tmp_uh + 2));
5007
5008         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5009     }
5010
5011     return (hlen * 2); /* entire header length, number of bytes */
5012 }
5013
5014 static void
5015 bxe_set_pbd_lso_e2(struct mbuf *m,
5016                    uint32_t    *parsing_data)
5017 {
5018     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5019                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5020                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5021
5022     /* XXX test for IPv6 with extension header... */
5023 }
5024
5025 static void
5026 bxe_set_pbd_lso(struct mbuf                *m,
5027                 struct eth_tx_parse_bd_e1x *pbd)
5028 {
5029     struct ether_vlan_header *eh = NULL;
5030     struct ip *ip = NULL;
5031     struct tcphdr *th = NULL;
5032     int e_hlen;
5033
5034     /* get the Ethernet header */
5035     eh = mtod(m, struct ether_vlan_header *);
5036
5037     /* handle VLAN encapsulation if present */
5038     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5039                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5040
5041     /* get the IP and TCP header, with LSO entire header in first mbuf */
5042     /* XXX assuming IPv4 */
5043     ip = (struct ip *)(m->m_data + e_hlen);
5044     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5045
5046     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5047     pbd->tcp_send_seq = ntohl(th->th_seq);
5048     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5049
5050 #if 1
5051         /* XXX IPv4 */
5052         pbd->ip_id = ntohs(ip->ip_id);
5053         pbd->tcp_pseudo_csum =
5054             ntohs(in_pseudo(ip->ip_src.s_addr,
5055                             ip->ip_dst.s_addr,
5056                             htons(IPPROTO_TCP)));
5057 #else
5058         /* XXX IPv6 */
5059         pbd->tcp_pseudo_csum =
5060             ntohs(in_pseudo(&ip6->ip6_src,
5061                             &ip6->ip6_dst,
5062                             htons(IPPROTO_TCP)));
5063 #endif
5064
5065     pbd->global_data |=
5066         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5067 }
5068
5069 /*
5070  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5071  * visible to the controller.
5072  *
5073  * If an mbuf is submitted to this routine and cannot be given to the
5074  * controller (e.g. it has too many fragments) then the function may free
5075  * the mbuf and return to the caller.
5076  *
5077  * Returns:
5078  *   0 = Success, !0 = Failure
5079  *   Note the side effect that an mbuf may be freed if it causes a problem.
5080  */
5081 static int
5082 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5083 {
5084     bus_dma_segment_t segs[32];
5085     struct mbuf *m0;
5086     struct bxe_sw_tx_bd *tx_buf;
5087     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5088     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5089     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5090     struct eth_tx_bd *tx_data_bd;
5091     struct eth_tx_bd *tx_total_pkt_size_bd;
5092     struct eth_tx_start_bd *tx_start_bd;
5093     uint16_t bd_prod, pkt_prod, total_pkt_size;
5094     uint8_t mac_type;
5095     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5096     struct bxe_softc *sc;
5097     uint16_t tx_bd_avail;
5098     struct ether_vlan_header *eh;
5099     uint32_t pbd_e2_parsing_data = 0;
5100     uint8_t hlen = 0;
5101     int tmp_bd;
5102     int i;
5103
5104     sc = fp->sc;
5105
5106 #if __FreeBSD_version >= 800000
5107     M_ASSERTPKTHDR(*m_head);
5108 #endif /* #if __FreeBSD_version >= 800000 */
5109
5110     m0 = *m_head;
5111     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5112     tx_start_bd = NULL;
5113     tx_data_bd = NULL;
5114     tx_total_pkt_size_bd = NULL;
5115
5116     /* get the H/W pointer for packets and BDs */
5117     pkt_prod = fp->tx_pkt_prod;
5118     bd_prod = fp->tx_bd_prod;
5119
5120     mac_type = UNICAST_ADDRESS;
5121
5122     /* map the mbuf into the next open DMAable memory */
5123     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5124     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5125                                     tx_buf->m_map, m0,
5126                                     segs, &nsegs, BUS_DMA_NOWAIT);
5127
5128     /* mapping errors */
5129     if(__predict_false(error != 0)) {
5130         fp->eth_q_stats.tx_dma_mapping_failure++;
5131         if (error == ENOMEM) {
5132             /* resource issue, try again later */
5133             rc = ENOMEM;
5134         } else if (error == EFBIG) {
5135             /* possibly recoverable with defragmentation */
5136             fp->eth_q_stats.mbuf_defrag_attempts++;
5137             m0 = m_defrag(*m_head, M_NOWAIT);
5138             if (m0 == NULL) {
5139                 fp->eth_q_stats.mbuf_defrag_failures++;
5140                 rc = ENOBUFS;
5141             } else {
5142                 /* defrag successful, try mapping again */
5143                 *m_head = m0;
5144                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5145                                                 tx_buf->m_map, m0,
5146                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5147                 if (error) {
5148                     fp->eth_q_stats.tx_dma_mapping_failure++;
5149                     rc = error;
5150                 }
5151             }
5152         } else {
5153             /* unknown, unrecoverable mapping error */
5154             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5155             bxe_dump_mbuf(sc, m0, FALSE);
5156             rc = error;
5157         }
5158
5159         goto bxe_tx_encap_continue;
5160     }
5161
5162     tx_bd_avail = bxe_tx_avail(sc, fp);
5163
5164     /* make sure there is enough room in the send queue */
5165     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5166         /* Recoverable, try again later. */
5167         fp->eth_q_stats.tx_hw_queue_full++;
5168         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5169         rc = ENOMEM;
5170         goto bxe_tx_encap_continue;
5171     }
5172
5173     /* capture the current H/W TX chain high watermark */
5174     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5175                         (TX_BD_USABLE - tx_bd_avail))) {
5176         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5177     }
5178
5179     /* make sure it fits in the packet window */
5180     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5181         /*
5182          * The mbuf may be to big for the controller to handle. If the frame
5183          * is a TSO frame we'll need to do an additional check.
5184          */
5185         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5186             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5187                 goto bxe_tx_encap_continue; /* OK to send */
5188             } else {
5189                 fp->eth_q_stats.tx_window_violation_tso++;
5190             }
5191         } else {
5192             fp->eth_q_stats.tx_window_violation_std++;
5193         }
5194
5195         /* lets try to defragment this mbuf and remap it */
5196         fp->eth_q_stats.mbuf_defrag_attempts++;
5197         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5198
5199         m0 = m_defrag(*m_head, M_NOWAIT);
5200         if (m0 == NULL) {
5201             fp->eth_q_stats.mbuf_defrag_failures++;
5202             /* Ugh, just drop the frame... :( */
5203             rc = ENOBUFS;
5204         } else {
5205             /* defrag successful, try mapping again */
5206             *m_head = m0;
5207             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5208                                             tx_buf->m_map, m0,
5209                                             segs, &nsegs, BUS_DMA_NOWAIT);
5210             if (error) {
5211                 fp->eth_q_stats.tx_dma_mapping_failure++;
5212                 /* No sense in trying to defrag/copy chain, drop it. :( */
5213                 rc = error;
5214             }
5215             else {
5216                 /* if the chain is still too long then drop it */
5217                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5218                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5219                     rc = ENODEV;
5220                 }
5221             }
5222         }
5223     }
5224
5225 bxe_tx_encap_continue:
5226
5227     /* Check for errors */
5228     if (rc) {
5229         if (rc == ENOMEM) {
5230             /* recoverable try again later  */
5231         } else {
5232             fp->eth_q_stats.tx_soft_errors++;
5233             fp->eth_q_stats.mbuf_alloc_tx--;
5234             m_freem(*m_head);
5235             *m_head = NULL;
5236         }
5237
5238         return (rc);
5239     }
5240
5241     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5242     if (m0->m_flags & M_BCAST) {
5243         mac_type = BROADCAST_ADDRESS;
5244     } else if (m0->m_flags & M_MCAST) {
5245         mac_type = MULTICAST_ADDRESS;
5246     }
5247
5248     /* store the mbuf into the mbuf ring */
5249     tx_buf->m        = m0;
5250     tx_buf->first_bd = fp->tx_bd_prod;
5251     tx_buf->flags    = 0;
5252
5253     /* prepare the first transmit (start) BD for the mbuf */
5254     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5255
5256     BLOGD(sc, DBG_TX,
5257           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5258           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5259
5260     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5261     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5262     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5263     total_pkt_size += tx_start_bd->nbytes;
5264     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5265
5266     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5267
5268     /* all frames have at least Start BD + Parsing BD */
5269     nbds = nsegs + 1;
5270     tx_start_bd->nbd = htole16(nbds);
5271
5272     if (m0->m_flags & M_VLANTAG) {
5273         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5274         tx_start_bd->bd_flags.as_bitfield |=
5275             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5276     } else {
5277         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5278         if (IS_VF(sc)) {
5279             /* map ethernet header to find type and header length */
5280             eh = mtod(m0, struct ether_vlan_header *);
5281             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5282         } else {
5283             /* used by FW for packet accounting */
5284             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5285         }
5286     }
5287
5288     /*
5289      * add a parsing BD from the chain. The parsing BD is always added
5290      * though it is only used for TSO and chksum
5291      */
5292     bd_prod = TX_BD_NEXT(bd_prod);
5293
5294     if (m0->m_pkthdr.csum_flags) {
5295         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5296             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5297             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5298         }
5299
5300         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5301             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5302                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5303         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5304             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5305                                                   ETH_TX_BD_FLAGS_IS_UDP |
5306                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5307         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5308                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5309             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5310         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5311             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5312                                                   ETH_TX_BD_FLAGS_IS_UDP);
5313         }
5314     }
5315
5316     if (!CHIP_IS_E1x(sc)) {
5317         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5318         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5319
5320         if (m0->m_pkthdr.csum_flags) {
5321             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5322         }
5323
5324         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5325                  mac_type);
5326     } else {
5327         uint16_t global_data = 0;
5328
5329         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5330         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5331
5332         if (m0->m_pkthdr.csum_flags) {
5333             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5334         }
5335
5336         SET_FLAG(global_data,
5337                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5338         pbd_e1x->global_data |= htole16(global_data);
5339     }
5340
5341     /* setup the parsing BD with TSO specific info */
5342     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5343         fp->eth_q_stats.tx_ofld_frames_lso++;
5344         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5345
5346         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5347             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5348
5349             /* split the first BD into header/data making the fw job easy */
5350             nbds++;
5351             tx_start_bd->nbd = htole16(nbds);
5352             tx_start_bd->nbytes = htole16(hlen);
5353
5354             bd_prod = TX_BD_NEXT(bd_prod);
5355
5356             /* new transmit BD after the tx_parse_bd */
5357             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5358             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5359             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5360             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5361             if (tx_total_pkt_size_bd == NULL) {
5362                 tx_total_pkt_size_bd = tx_data_bd;
5363             }
5364
5365             BLOGD(sc, DBG_TX,
5366                   "TSO split header size is %d (%x:%x) nbds %d\n",
5367                   le16toh(tx_start_bd->nbytes),
5368                   le32toh(tx_start_bd->addr_hi),
5369                   le32toh(tx_start_bd->addr_lo),
5370                   nbds);
5371         }
5372
5373         if (!CHIP_IS_E1x(sc)) {
5374             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5375         } else {
5376             bxe_set_pbd_lso(m0, pbd_e1x);
5377         }
5378     }
5379
5380     if (pbd_e2_parsing_data) {
5381         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5382     }
5383
5384     /* prepare remaining BDs, start tx bd contains first seg/frag */
5385     for (i = 1; i < nsegs ; i++) {
5386         bd_prod = TX_BD_NEXT(bd_prod);
5387         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5388         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5389         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5390         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5391         if (tx_total_pkt_size_bd == NULL) {
5392             tx_total_pkt_size_bd = tx_data_bd;
5393         }
5394         total_pkt_size += tx_data_bd->nbytes;
5395     }
5396
5397     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5398
5399     if (tx_total_pkt_size_bd != NULL) {
5400         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5401     }
5402
5403     if (__predict_false(sc->debug & DBG_TX)) {
5404         tmp_bd = tx_buf->first_bd;
5405         for (i = 0; i < nbds; i++)
5406         {
5407             if (i == 0) {
5408                 BLOGD(sc, DBG_TX,
5409                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5410                       "bd_flags=0x%x hdr_nbds=%d\n",
5411                       tx_start_bd,
5412                       tmp_bd,
5413                       le16toh(tx_start_bd->nbd),
5414                       le16toh(tx_start_bd->vlan_or_ethertype),
5415                       tx_start_bd->bd_flags.as_bitfield,
5416                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5417             } else if (i == 1) {
5418                 if (pbd_e1x) {
5419                     BLOGD(sc, DBG_TX,
5420                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5421                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5422                           "tcp_seq=%u total_hlen_w=%u\n",
5423                           pbd_e1x,
5424                           tmp_bd,
5425                           pbd_e1x->global_data,
5426                           pbd_e1x->ip_hlen_w,
5427                           pbd_e1x->ip_id,
5428                           pbd_e1x->lso_mss,
5429                           pbd_e1x->tcp_flags,
5430                           pbd_e1x->tcp_pseudo_csum,
5431                           pbd_e1x->tcp_send_seq,
5432                           le16toh(pbd_e1x->total_hlen_w));
5433                 } else { /* if (pbd_e2) */
5434                     BLOGD(sc, DBG_TX,
5435                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5436                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5437                           pbd_e2,
5438                           tmp_bd,
5439                           pbd_e2->data.mac_addr.dst_hi,
5440                           pbd_e2->data.mac_addr.dst_mid,
5441                           pbd_e2->data.mac_addr.dst_lo,
5442                           pbd_e2->data.mac_addr.src_hi,
5443                           pbd_e2->data.mac_addr.src_mid,
5444                           pbd_e2->data.mac_addr.src_lo,
5445                           pbd_e2->parsing_data);
5446                 }
5447             }
5448
5449             if (i != 1) { /* skip parse db as it doesn't hold data */
5450                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5451                 BLOGD(sc, DBG_TX,
5452                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5453                       tx_data_bd,
5454                       tmp_bd,
5455                       le16toh(tx_data_bd->nbytes),
5456                       le32toh(tx_data_bd->addr_hi),
5457                       le32toh(tx_data_bd->addr_lo));
5458             }
5459
5460             tmp_bd = TX_BD_NEXT(tmp_bd);
5461         }
5462     }
5463
5464     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5465
5466     /* update TX BD producer index value for next TX */
5467     bd_prod = TX_BD_NEXT(bd_prod);
5468
5469     /*
5470      * If the chain of tx_bd's describing this frame is adjacent to or spans
5471      * an eth_tx_next_bd element then we need to increment the nbds value.
5472      */
5473     if (TX_BD_IDX(bd_prod) < nbds) {
5474         nbds++;
5475     }
5476
5477     /* don't allow reordering of writes for nbd and packets */
5478     mb();
5479
5480     fp->tx_db.data.prod += nbds;
5481
5482     /* producer points to the next free tx_bd at this point */
5483     fp->tx_pkt_prod++;
5484     fp->tx_bd_prod = bd_prod;
5485
5486     DOORBELL(sc, fp->index, fp->tx_db.raw);
5487
5488     fp->eth_q_stats.tx_pkts++;
5489
5490     /* Prevent speculative reads from getting ahead of the status block. */
5491     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5492                       0, 0, BUS_SPACE_BARRIER_READ);
5493
5494     /* Prevent speculative reads from getting ahead of the doorbell. */
5495     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5496                       0, 0, BUS_SPACE_BARRIER_READ);
5497
5498     return (0);
5499 }
5500
5501 static void
5502 bxe_tx_start_locked(struct bxe_softc *sc,
5503                     if_t ifp,
5504                     struct bxe_fastpath *fp)
5505 {
5506     struct mbuf *m = NULL;
5507     int tx_count = 0;
5508     uint16_t tx_bd_avail;
5509
5510     BXE_FP_TX_LOCK_ASSERT(fp);
5511
5512     /* keep adding entries while there are frames to send */
5513     while (!if_sendq_empty(ifp)) {
5514
5515         /*
5516          * check for any frames to send
5517          * dequeue can still be NULL even if queue is not empty
5518          */
5519         m = if_dequeue(ifp);
5520         if (__predict_false(m == NULL)) {
5521             break;
5522         }
5523
5524         /* the mbuf now belongs to us */
5525         fp->eth_q_stats.mbuf_alloc_tx++;
5526
5527         /*
5528          * Put the frame into the transmit ring. If we don't have room,
5529          * place the mbuf back at the head of the TX queue, set the
5530          * OACTIVE flag, and wait for the NIC to drain the chain.
5531          */
5532         if (__predict_false(bxe_tx_encap(fp, &m))) {
5533             fp->eth_q_stats.tx_encap_failures++;
5534             if (m != NULL) {
5535                 /* mark the TX queue as full and return the frame */
5536                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5537                 if_sendq_prepend(ifp, m);
5538                 fp->eth_q_stats.mbuf_alloc_tx--;
5539                 fp->eth_q_stats.tx_queue_xoff++;
5540             }
5541
5542             /* stop looking for more work */
5543             break;
5544         }
5545
5546         /* the frame was enqueued successfully */
5547         tx_count++;
5548
5549         /* send a copy of the frame to any BPF listeners. */
5550         if_etherbpfmtap(ifp, m);
5551
5552         tx_bd_avail = bxe_tx_avail(sc, fp);
5553
5554         /* handle any completions if we're running low */
5555         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5556             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5557             bxe_txeof(sc, fp);
5558             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5559                 break;
5560             }
5561         }
5562     }
5563
5564     /* all TX packets were dequeued and/or the tx ring is full */
5565     if (tx_count > 0) {
5566         /* reset the TX watchdog timeout timer */
5567         fp->watchdog_timer = BXE_TX_TIMEOUT;
5568     }
5569 }
5570
5571 /* Legacy (non-RSS) dispatch routine */
5572 static void
5573 bxe_tx_start(if_t ifp)
5574 {
5575     struct bxe_softc *sc;
5576     struct bxe_fastpath *fp;
5577
5578     sc = if_getsoftc(ifp);
5579
5580     if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
5581         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5582         return;
5583     }
5584
5585     if (!sc->link_vars.link_up) {
5586         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5587         return;
5588     }
5589
5590     fp = &sc->fp[0];
5591
5592     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5593         fp->eth_q_stats.tx_queue_full_return++;
5594         return;
5595     }
5596
5597     BXE_FP_TX_LOCK(fp);
5598     bxe_tx_start_locked(sc, ifp, fp);
5599     BXE_FP_TX_UNLOCK(fp);
5600 }
5601
5602 #if __FreeBSD_version >= 800000
5603
5604 static int
5605 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5606                        if_t                ifp,
5607                        struct bxe_fastpath *fp,
5608                        struct mbuf         *m)
5609 {
5610     struct buf_ring *tx_br = fp->tx_br;
5611     struct mbuf *next;
5612     int depth, rc, tx_count;
5613     uint16_t tx_bd_avail;
5614
5615     rc = tx_count = 0;
5616
5617     BXE_FP_TX_LOCK_ASSERT(fp);
5618
5619     if (!tx_br) {
5620         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5621         return (EINVAL);
5622     }
5623
5624     if (!sc->link_vars.link_up ||
5625         (if_getdrvflags(ifp) &
5626         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5627         if (m != NULL)
5628             rc = drbr_enqueue(ifp, tx_br, m);
5629         goto bxe_tx_mq_start_locked_exit;
5630     }
5631
5632     /* fetch the depth of the driver queue */
5633     depth = drbr_inuse_drv(ifp, tx_br);
5634     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5635         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5636     }
5637
5638     if (m == NULL) {
5639         /* no new work, check for pending frames */
5640         next = drbr_dequeue_drv(ifp, tx_br);
5641     } else if (drbr_needs_enqueue_drv(ifp, tx_br)) {
5642         /* have both new and pending work, maintain packet order */
5643         rc = drbr_enqueue(ifp, tx_br, m);
5644         if (rc != 0) {
5645             fp->eth_q_stats.tx_soft_errors++;
5646             goto bxe_tx_mq_start_locked_exit;
5647         }
5648         next = drbr_dequeue_drv(ifp, tx_br);
5649     } else {
5650         /* new work only and nothing pending */
5651         next = m;
5652     }
5653
5654     /* keep adding entries while there are frames to send */
5655     while (next != NULL) {
5656
5657         /* the mbuf now belongs to us */
5658         fp->eth_q_stats.mbuf_alloc_tx++;
5659
5660         /*
5661          * Put the frame into the transmit ring. If we don't have room,
5662          * place the mbuf back at the head of the TX queue, set the
5663          * OACTIVE flag, and wait for the NIC to drain the chain.
5664          */
5665         rc = bxe_tx_encap(fp, &next);
5666         if (__predict_false(rc != 0)) {
5667             fp->eth_q_stats.tx_encap_failures++;
5668             if (next != NULL) {
5669                 /* mark the TX queue as full and save the frame */
5670                 if_setdrvflagbits(ifp, IFF_DRV_OACTIVE, 0);
5671                 /* XXX this may reorder the frame */
5672                 rc = drbr_enqueue(ifp, tx_br, next);
5673                 fp->eth_q_stats.mbuf_alloc_tx--;
5674                 fp->eth_q_stats.tx_frames_deferred++;
5675             }
5676
5677             /* stop looking for more work */
5678             break;
5679         }
5680
5681         /* the transmit frame was enqueued successfully */
5682         tx_count++;
5683
5684         /* send a copy of the frame to any BPF listeners */
5685         if_etherbpfmtap(ifp, next);
5686
5687         tx_bd_avail = bxe_tx_avail(sc, fp);
5688
5689         /* handle any completions if we're running low */
5690         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5691             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5692             bxe_txeof(sc, fp);
5693             if (if_getdrvflags(ifp) & IFF_DRV_OACTIVE) {
5694                 break;
5695             }
5696         }
5697
5698         next = drbr_dequeue_drv(ifp, tx_br);
5699     }
5700
5701     /* all TX packets were dequeued and/or the tx ring is full */
5702     if (tx_count > 0) {
5703         /* reset the TX watchdog timeout timer */
5704         fp->watchdog_timer = BXE_TX_TIMEOUT;
5705     }
5706
5707 bxe_tx_mq_start_locked_exit:
5708
5709     return (rc);
5710 }
5711
5712 /* Multiqueue (TSS) dispatch routine. */
5713 static int
5714 bxe_tx_mq_start(struct ifnet *ifp,
5715                 struct mbuf  *m)
5716 {
5717     struct bxe_softc *sc = if_getsoftc(ifp);
5718     struct bxe_fastpath *fp;
5719     int fp_index, rc;
5720
5721     fp_index = 0; /* default is the first queue */
5722
5723     /* check if flowid is set */
5724
5725     if (BXE_VALID_FLOWID(m))
5726         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5727
5728     fp = &sc->fp[fp_index];
5729
5730     if (BXE_FP_TX_TRYLOCK(fp)) {
5731         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5732         BXE_FP_TX_UNLOCK(fp);
5733     } else
5734         rc = drbr_enqueue(ifp, fp->tx_br, m);
5735
5736     return (rc);
5737 }
5738
5739 static void
5740 bxe_mq_flush(struct ifnet *ifp)
5741 {
5742     struct bxe_softc *sc = if_getsoftc(ifp);
5743     struct bxe_fastpath *fp;
5744     struct mbuf *m;
5745     int i;
5746
5747     for (i = 0; i < sc->num_queues; i++) {
5748         fp = &sc->fp[i];
5749
5750         if (fp->state != BXE_FP_STATE_OPEN) {
5751             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5752                   fp->index, fp->state);
5753             continue;
5754         }
5755
5756         if (fp->tx_br != NULL) {
5757             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5758             BXE_FP_TX_LOCK(fp);
5759             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5760                 m_freem(m);
5761             }
5762             BXE_FP_TX_UNLOCK(fp);
5763         }
5764     }
5765
5766     if_qflush(ifp);
5767 }
5768
5769 #endif /* FreeBSD_version >= 800000 */
5770
5771 static uint16_t
5772 bxe_cid_ilt_lines(struct bxe_softc *sc)
5773 {
5774     if (IS_SRIOV(sc)) {
5775         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5776     }
5777     return (L2_ILT_LINES(sc));
5778 }
5779
5780 static void
5781 bxe_ilt_set_info(struct bxe_softc *sc)
5782 {
5783     struct ilt_client_info *ilt_client;
5784     struct ecore_ilt *ilt = sc->ilt;
5785     uint16_t line = 0;
5786
5787     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5788     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5789
5790     /* CDU */
5791     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5792     ilt_client->client_num = ILT_CLIENT_CDU;
5793     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5794     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5795     ilt_client->start = line;
5796     line += bxe_cid_ilt_lines(sc);
5797
5798     if (CNIC_SUPPORT(sc)) {
5799         line += CNIC_ILT_LINES;
5800     }
5801
5802     ilt_client->end = (line - 1);
5803
5804     BLOGD(sc, DBG_LOAD,
5805           "ilt client[CDU]: start %d, end %d, "
5806           "psz 0x%x, flags 0x%x, hw psz %d\n",
5807           ilt_client->start, ilt_client->end,
5808           ilt_client->page_size,
5809           ilt_client->flags,
5810           ilog2(ilt_client->page_size >> 12));
5811
5812     /* QM */
5813     if (QM_INIT(sc->qm_cid_count)) {
5814         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5815         ilt_client->client_num = ILT_CLIENT_QM;
5816         ilt_client->page_size = QM_ILT_PAGE_SZ;
5817         ilt_client->flags = 0;
5818         ilt_client->start = line;
5819
5820         /* 4 bytes for each cid */
5821         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5822                              QM_ILT_PAGE_SZ);
5823
5824         ilt_client->end = (line - 1);
5825
5826         BLOGD(sc, DBG_LOAD,
5827               "ilt client[QM]: start %d, end %d, "
5828               "psz 0x%x, flags 0x%x, hw psz %d\n",
5829               ilt_client->start, ilt_client->end,
5830               ilt_client->page_size, ilt_client->flags,
5831               ilog2(ilt_client->page_size >> 12));
5832     }
5833
5834     if (CNIC_SUPPORT(sc)) {
5835         /* SRC */
5836         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5837         ilt_client->client_num = ILT_CLIENT_SRC;
5838         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5839         ilt_client->flags = 0;
5840         ilt_client->start = line;
5841         line += SRC_ILT_LINES;
5842         ilt_client->end = (line - 1);
5843
5844         BLOGD(sc, DBG_LOAD,
5845               "ilt client[SRC]: start %d, end %d, "
5846               "psz 0x%x, flags 0x%x, hw psz %d\n",
5847               ilt_client->start, ilt_client->end,
5848               ilt_client->page_size, ilt_client->flags,
5849               ilog2(ilt_client->page_size >> 12));
5850
5851         /* TM */
5852         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5853         ilt_client->client_num = ILT_CLIENT_TM;
5854         ilt_client->page_size = TM_ILT_PAGE_SZ;
5855         ilt_client->flags = 0;
5856         ilt_client->start = line;
5857         line += TM_ILT_LINES;
5858         ilt_client->end = (line - 1);
5859
5860         BLOGD(sc, DBG_LOAD,
5861               "ilt client[TM]: start %d, end %d, "
5862               "psz 0x%x, flags 0x%x, hw psz %d\n",
5863               ilt_client->start, ilt_client->end,
5864               ilt_client->page_size, ilt_client->flags,
5865               ilog2(ilt_client->page_size >> 12));
5866     }
5867
5868     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5869 }
5870
5871 static void
5872 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5873 {
5874     int i;
5875     uint32_t rx_buf_size;
5876
5877     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5878
5879     for (i = 0; i < sc->num_queues; i++) {
5880         if(rx_buf_size <= MCLBYTES){
5881             sc->fp[i].rx_buf_size = rx_buf_size;
5882             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5883         }else if (rx_buf_size <= MJUMPAGESIZE){
5884             sc->fp[i].rx_buf_size = rx_buf_size;
5885             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5886         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5887             sc->fp[i].rx_buf_size = MCLBYTES;
5888             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5889         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5890             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5891             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5892         }else {
5893             sc->fp[i].rx_buf_size = MCLBYTES;
5894             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5895         }
5896     }
5897 }
5898
5899 static int
5900 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5901 {
5902     int rc = 0;
5903
5904     if ((sc->ilt =
5905          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5906                                     M_BXE_ILT,
5907                                     (M_NOWAIT | M_ZERO))) == NULL) {
5908         rc = 1;
5909     }
5910
5911     return (rc);
5912 }
5913
5914 static int
5915 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5916 {
5917     int rc = 0;
5918
5919     if ((sc->ilt->lines =
5920          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
5921                                     M_BXE_ILT,
5922                                     (M_NOWAIT | M_ZERO))) == NULL) {
5923         rc = 1;
5924     }
5925
5926     return (rc);
5927 }
5928
5929 static void
5930 bxe_free_ilt_mem(struct bxe_softc *sc)
5931 {
5932     if (sc->ilt != NULL) {
5933         free(sc->ilt, M_BXE_ILT);
5934         sc->ilt = NULL;
5935     }
5936 }
5937
5938 static void
5939 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
5940 {
5941     if (sc->ilt->lines != NULL) {
5942         free(sc->ilt->lines, M_BXE_ILT);
5943         sc->ilt->lines = NULL;
5944     }
5945 }
5946
5947 static void
5948 bxe_free_mem(struct bxe_softc *sc)
5949 {
5950     int i;
5951
5952     for (i = 0; i < L2_ILT_LINES(sc); i++) {
5953         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
5954         sc->context[i].vcxt = NULL;
5955         sc->context[i].size = 0;
5956     }
5957
5958     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
5959
5960     bxe_free_ilt_lines_mem(sc);
5961
5962 }
5963
5964 static int
5965 bxe_alloc_mem(struct bxe_softc *sc)
5966 {
5967     int context_size;
5968     int allocated;
5969     int i;
5970
5971     /*
5972      * Allocate memory for CDU context:
5973      * This memory is allocated separately and not in the generic ILT
5974      * functions because CDU differs in few aspects:
5975      * 1. There can be multiple entities allocating memory for context -
5976      * regular L2, CNIC, and SRIOV drivers. Each separately controls
5977      * its own ILT lines.
5978      * 2. Since CDU page-size is not a single 4KB page (which is the case
5979      * for the other ILT clients), to be efficient we want to support
5980      * allocation of sub-page-size in the last entry.
5981      * 3. Context pointers are used by the driver to pass to FW / update
5982      * the context (for the other ILT clients the pointers are used just to
5983      * free the memory during unload).
5984      */
5985     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
5986     for (i = 0, allocated = 0; allocated < context_size; i++) {
5987         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
5988                                   (context_size - allocated));
5989
5990         if (bxe_dma_alloc(sc, sc->context[i].size,
5991                           &sc->context[i].vcxt_dma,
5992                           "cdu context") != 0) {
5993             bxe_free_mem(sc);
5994             return (-1);
5995         }
5996
5997         sc->context[i].vcxt =
5998             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
5999
6000         allocated += sc->context[i].size;
6001     }
6002
6003     bxe_alloc_ilt_lines_mem(sc);
6004
6005     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6006           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6007     {
6008         for (i = 0; i < 4; i++) {
6009             BLOGD(sc, DBG_LOAD,
6010                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6011                   i,
6012                   sc->ilt->clients[i].page_size,
6013                   sc->ilt->clients[i].start,
6014                   sc->ilt->clients[i].end,
6015                   sc->ilt->clients[i].client_num,
6016                   sc->ilt->clients[i].flags);
6017         }
6018     }
6019     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6020         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6021         bxe_free_mem(sc);
6022         return (-1);
6023     }
6024
6025     return (0);
6026 }
6027
6028 static void
6029 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6030 {
6031     struct bxe_softc *sc;
6032     int i;
6033
6034     sc = fp->sc;
6035
6036     if (fp->rx_mbuf_tag == NULL) {
6037         return;
6038     }
6039
6040     /* free all mbufs and unload all maps */
6041     for (i = 0; i < RX_BD_TOTAL; i++) {
6042         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6043             bus_dmamap_sync(fp->rx_mbuf_tag,
6044                             fp->rx_mbuf_chain[i].m_map,
6045                             BUS_DMASYNC_POSTREAD);
6046             bus_dmamap_unload(fp->rx_mbuf_tag,
6047                               fp->rx_mbuf_chain[i].m_map);
6048         }
6049
6050         if (fp->rx_mbuf_chain[i].m != NULL) {
6051             m_freem(fp->rx_mbuf_chain[i].m);
6052             fp->rx_mbuf_chain[i].m = NULL;
6053             fp->eth_q_stats.mbuf_alloc_rx--;
6054         }
6055     }
6056 }
6057
6058 static void
6059 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6060 {
6061     struct bxe_softc *sc;
6062     int i, max_agg_queues;
6063
6064     sc = fp->sc;
6065
6066     if (fp->rx_mbuf_tag == NULL) {
6067         return;
6068     }
6069
6070     max_agg_queues = MAX_AGG_QS(sc);
6071
6072     /* release all mbufs and unload all DMA maps in the TPA pool */
6073     for (i = 0; i < max_agg_queues; i++) {
6074         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6075             bus_dmamap_sync(fp->rx_mbuf_tag,
6076                             fp->rx_tpa_info[i].bd.m_map,
6077                             BUS_DMASYNC_POSTREAD);
6078             bus_dmamap_unload(fp->rx_mbuf_tag,
6079                               fp->rx_tpa_info[i].bd.m_map);
6080         }
6081
6082         if (fp->rx_tpa_info[i].bd.m != NULL) {
6083             m_freem(fp->rx_tpa_info[i].bd.m);
6084             fp->rx_tpa_info[i].bd.m = NULL;
6085             fp->eth_q_stats.mbuf_alloc_tpa--;
6086         }
6087     }
6088 }
6089
6090 static void
6091 bxe_free_sge_chain(struct bxe_fastpath *fp)
6092 {
6093     struct bxe_softc *sc;
6094     int i;
6095
6096     sc = fp->sc;
6097
6098     if (fp->rx_sge_mbuf_tag == NULL) {
6099         return;
6100     }
6101
6102     /* rree all mbufs and unload all maps */
6103     for (i = 0; i < RX_SGE_TOTAL; i++) {
6104         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6105             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6106                             fp->rx_sge_mbuf_chain[i].m_map,
6107                             BUS_DMASYNC_POSTREAD);
6108             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6109                               fp->rx_sge_mbuf_chain[i].m_map);
6110         }
6111
6112         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6113             m_freem(fp->rx_sge_mbuf_chain[i].m);
6114             fp->rx_sge_mbuf_chain[i].m = NULL;
6115             fp->eth_q_stats.mbuf_alloc_sge--;
6116         }
6117     }
6118 }
6119
6120 static void
6121 bxe_free_fp_buffers(struct bxe_softc *sc)
6122 {
6123     struct bxe_fastpath *fp;
6124     int i;
6125
6126     for (i = 0; i < sc->num_queues; i++) {
6127         fp = &sc->fp[i];
6128
6129 #if __FreeBSD_version >= 800000
6130         if (fp->tx_br != NULL) {
6131             /* just in case bxe_mq_flush() wasn't called */
6132             if (mtx_initialized(&fp->tx_mtx)) {
6133                 struct mbuf *m;
6134
6135                 BXE_FP_TX_LOCK(fp);
6136                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6137                     m_freem(m);
6138                 BXE_FP_TX_UNLOCK(fp);
6139             }
6140         }
6141 #endif
6142
6143         /* free all RX buffers */
6144         bxe_free_rx_bd_chain(fp);
6145         bxe_free_tpa_pool(fp);
6146         bxe_free_sge_chain(fp);
6147
6148         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6149             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6150                   fp->eth_q_stats.mbuf_alloc_rx);
6151         }
6152
6153         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6154             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6155                   fp->eth_q_stats.mbuf_alloc_sge);
6156         }
6157
6158         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6159             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6160                   fp->eth_q_stats.mbuf_alloc_tpa);
6161         }
6162
6163         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6164             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6165                   fp->eth_q_stats.mbuf_alloc_tx);
6166         }
6167
6168         /* XXX verify all mbufs were reclaimed */
6169     }
6170 }
6171
6172 static int
6173 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6174                      uint16_t            prev_index,
6175                      uint16_t            index)
6176 {
6177     struct bxe_sw_rx_bd *rx_buf;
6178     struct eth_rx_bd *rx_bd;
6179     bus_dma_segment_t segs[1];
6180     bus_dmamap_t map;
6181     struct mbuf *m;
6182     int nsegs, rc;
6183
6184     rc = 0;
6185
6186     /* allocate the new RX BD mbuf */
6187     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6188     if (__predict_false(m == NULL)) {
6189         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6190         return (ENOBUFS);
6191     }
6192
6193     fp->eth_q_stats.mbuf_alloc_rx++;
6194
6195     /* initialize the mbuf buffer length */
6196     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6197
6198     /* map the mbuf into non-paged pool */
6199     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6200                                  fp->rx_mbuf_spare_map,
6201                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6202     if (__predict_false(rc != 0)) {
6203         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6204         m_freem(m);
6205         fp->eth_q_stats.mbuf_alloc_rx--;
6206         return (rc);
6207     }
6208
6209     /* all mbufs must map to a single segment */
6210     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6211
6212     /* release any existing RX BD mbuf mappings */
6213
6214     if (prev_index != index) {
6215         rx_buf = &fp->rx_mbuf_chain[prev_index];
6216
6217         if (rx_buf->m_map != NULL) {
6218             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6219                             BUS_DMASYNC_POSTREAD);
6220             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6221         }
6222
6223         /*
6224          * We only get here from bxe_rxeof() when the maximum number
6225          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6226          * holds the mbuf in the prev_index so it's OK to NULL it out
6227          * here without concern of a memory leak.
6228          */
6229         fp->rx_mbuf_chain[prev_index].m = NULL;
6230     }
6231
6232     rx_buf = &fp->rx_mbuf_chain[index];
6233
6234     if (rx_buf->m_map != NULL) {
6235         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6236                         BUS_DMASYNC_POSTREAD);
6237         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6238     }
6239
6240     /* save the mbuf and mapping info for a future packet */
6241     map = (prev_index != index) ?
6242               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6243     rx_buf->m_map = fp->rx_mbuf_spare_map;
6244     fp->rx_mbuf_spare_map = map;
6245     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6246                     BUS_DMASYNC_PREREAD);
6247     rx_buf->m = m;
6248
6249     rx_bd = &fp->rx_chain[index];
6250     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6251     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6252
6253     return (rc);
6254 }
6255
6256 static int
6257 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6258                       int                 queue)
6259 {
6260     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6261     bus_dma_segment_t segs[1];
6262     bus_dmamap_t map;
6263     struct mbuf *m;
6264     int nsegs;
6265     int rc = 0;
6266
6267     /* allocate the new TPA mbuf */
6268     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6269     if (__predict_false(m == NULL)) {
6270         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6271         return (ENOBUFS);
6272     }
6273
6274     fp->eth_q_stats.mbuf_alloc_tpa++;
6275
6276     /* initialize the mbuf buffer length */
6277     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6278
6279     /* map the mbuf into non-paged pool */
6280     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6281                                  fp->rx_tpa_info_mbuf_spare_map,
6282                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6283     if (__predict_false(rc != 0)) {
6284         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6285         m_free(m);
6286         fp->eth_q_stats.mbuf_alloc_tpa--;
6287         return (rc);
6288     }
6289
6290     /* all mbufs must map to a single segment */
6291     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6292
6293     /* release any existing TPA mbuf mapping */
6294     if (tpa_info->bd.m_map != NULL) {
6295         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6296                         BUS_DMASYNC_POSTREAD);
6297         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6298     }
6299
6300     /* save the mbuf and mapping info for the TPA mbuf */
6301     map = tpa_info->bd.m_map;
6302     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6303     fp->rx_tpa_info_mbuf_spare_map = map;
6304     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6305                     BUS_DMASYNC_PREREAD);
6306     tpa_info->bd.m = m;
6307     tpa_info->seg = segs[0];
6308
6309     return (rc);
6310 }
6311
6312 /*
6313  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6314  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6315  * chain.
6316  */
6317 static int
6318 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6319                       uint16_t            index)
6320 {
6321     struct bxe_sw_rx_bd *sge_buf;
6322     struct eth_rx_sge *sge;
6323     bus_dma_segment_t segs[1];
6324     bus_dmamap_t map;
6325     struct mbuf *m;
6326     int nsegs;
6327     int rc = 0;
6328
6329     /* allocate a new SGE mbuf */
6330     m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6331     if (__predict_false(m == NULL)) {
6332         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6333         return (ENOMEM);
6334     }
6335
6336     fp->eth_q_stats.mbuf_alloc_sge++;
6337
6338     /* initialize the mbuf buffer length */
6339     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6340
6341     /* map the SGE mbuf into non-paged pool */
6342     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6343                                  fp->rx_sge_mbuf_spare_map,
6344                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6345     if (__predict_false(rc != 0)) {
6346         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6347         m_freem(m);
6348         fp->eth_q_stats.mbuf_alloc_sge--;
6349         return (rc);
6350     }
6351
6352     /* all mbufs must map to a single segment */
6353     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6354
6355     sge_buf = &fp->rx_sge_mbuf_chain[index];
6356
6357     /* release any existing SGE mbuf mapping */
6358     if (sge_buf->m_map != NULL) {
6359         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6360                         BUS_DMASYNC_POSTREAD);
6361         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6362     }
6363
6364     /* save the mbuf and mapping info for a future packet */
6365     map = sge_buf->m_map;
6366     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6367     fp->rx_sge_mbuf_spare_map = map;
6368     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6369                     BUS_DMASYNC_PREREAD);
6370     sge_buf->m = m;
6371
6372     sge = &fp->rx_sge_chain[index];
6373     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6374     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6375
6376     return (rc);
6377 }
6378
6379 static __noinline int
6380 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6381 {
6382     struct bxe_fastpath *fp;
6383     int i, j, rc = 0;
6384     int ring_prod, cqe_ring_prod;
6385     int max_agg_queues;
6386
6387     for (i = 0; i < sc->num_queues; i++) {
6388         fp = &sc->fp[i];
6389
6390         ring_prod = cqe_ring_prod = 0;
6391         fp->rx_bd_cons = 0;
6392         fp->rx_cq_cons = 0;
6393
6394         /* allocate buffers for the RX BDs in RX BD chain */
6395         for (j = 0; j < sc->max_rx_bufs; j++) {
6396             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6397             if (rc != 0) {
6398                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6399                       i, rc);
6400                 goto bxe_alloc_fp_buffers_error;
6401             }
6402
6403             ring_prod     = RX_BD_NEXT(ring_prod);
6404             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6405         }
6406
6407         fp->rx_bd_prod = ring_prod;
6408         fp->rx_cq_prod = cqe_ring_prod;
6409         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6410
6411         max_agg_queues = MAX_AGG_QS(sc);
6412
6413         fp->tpa_enable = TRUE;
6414
6415         /* fill the TPA pool */
6416         for (j = 0; j < max_agg_queues; j++) {
6417             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6418             if (rc != 0) {
6419                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6420                           i, j);
6421                 fp->tpa_enable = FALSE;
6422                 goto bxe_alloc_fp_buffers_error;
6423             }
6424
6425             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6426         }
6427
6428         if (fp->tpa_enable) {
6429             /* fill the RX SGE chain */
6430             ring_prod = 0;
6431             for (j = 0; j < RX_SGE_USABLE; j++) {
6432                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6433                 if (rc != 0) {
6434                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6435                               i, ring_prod);
6436                     fp->tpa_enable = FALSE;
6437                     ring_prod = 0;
6438                     goto bxe_alloc_fp_buffers_error;
6439                 }
6440
6441                 ring_prod = RX_SGE_NEXT(ring_prod);
6442             }
6443
6444             fp->rx_sge_prod = ring_prod;
6445         }
6446     }
6447
6448     return (0);
6449
6450 bxe_alloc_fp_buffers_error:
6451
6452     /* unwind what was already allocated */
6453     bxe_free_rx_bd_chain(fp);
6454     bxe_free_tpa_pool(fp);
6455     bxe_free_sge_chain(fp);
6456
6457     return (ENOBUFS);
6458 }
6459
6460 static void
6461 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6462 {
6463     bxe_dma_free(sc, &sc->fw_stats_dma);
6464
6465     sc->fw_stats_num = 0;
6466
6467     sc->fw_stats_req_size = 0;
6468     sc->fw_stats_req = NULL;
6469     sc->fw_stats_req_mapping = 0;
6470
6471     sc->fw_stats_data_size = 0;
6472     sc->fw_stats_data = NULL;
6473     sc->fw_stats_data_mapping = 0;
6474 }
6475
6476 static int
6477 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6478 {
6479     uint8_t num_queue_stats;
6480     int num_groups;
6481
6482     /* number of queues for statistics is number of eth queues */
6483     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6484
6485     /*
6486      * Total number of FW statistics requests =
6487      *   1 for port stats + 1 for PF stats + num of queues
6488      */
6489     sc->fw_stats_num = (2 + num_queue_stats);
6490
6491     /*
6492      * Request is built from stats_query_header and an array of
6493      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6494      * rules. The real number or requests is configured in the
6495      * stats_query_header.
6496      */
6497     num_groups =
6498         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6499          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6500
6501     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6502           sc->fw_stats_num, num_groups);
6503
6504     sc->fw_stats_req_size =
6505         (sizeof(struct stats_query_header) +
6506          (num_groups * sizeof(struct stats_query_cmd_group)));
6507
6508     /*
6509      * Data for statistics requests + stats_counter.
6510      * stats_counter holds per-STORM counters that are incremented when
6511      * STORM has finished with the current request. Memory for FCoE
6512      * offloaded statistics are counted anyway, even if they will not be sent.
6513      * VF stats are not accounted for here as the data of VF stats is stored
6514      * in memory allocated by the VF, not here.
6515      */
6516     sc->fw_stats_data_size =
6517         (sizeof(struct stats_counter) +
6518          sizeof(struct per_port_stats) +
6519          sizeof(struct per_pf_stats) +
6520          /* sizeof(struct fcoe_statistics_params) + */
6521          (sizeof(struct per_queue_stats) * num_queue_stats));
6522
6523     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6524                       &sc->fw_stats_dma, "fw stats") != 0) {
6525         bxe_free_fw_stats_mem(sc);
6526         return (-1);
6527     }
6528
6529     /* set up the shortcuts */
6530
6531     sc->fw_stats_req =
6532         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6533     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6534
6535     sc->fw_stats_data =
6536         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6537                                      sc->fw_stats_req_size);
6538     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6539                                  sc->fw_stats_req_size);
6540
6541     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6542           (uintmax_t)sc->fw_stats_req_mapping);
6543
6544     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6545           (uintmax_t)sc->fw_stats_data_mapping);
6546
6547     return (0);
6548 }
6549
6550 /*
6551  * Bits map:
6552  * 0-7  - Engine0 load counter.
6553  * 8-15 - Engine1 load counter.
6554  * 16   - Engine0 RESET_IN_PROGRESS bit.
6555  * 17   - Engine1 RESET_IN_PROGRESS bit.
6556  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6557  *        function on the engine
6558  * 19   - Engine1 ONE_IS_LOADED.
6559  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6560  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6561  *        for just the one belonging to its engine).
6562  */
6563 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6564 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6565 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6566 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6567 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6568 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6569 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6570 #define BXE_GLOBAL_RESET_BIT      0x00040000
6571
6572 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6573 static void
6574 bxe_set_reset_global(struct bxe_softc *sc)
6575 {
6576     uint32_t val;
6577     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6578     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6579     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6580     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6581 }
6582
6583 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6584 static void
6585 bxe_clear_reset_global(struct bxe_softc *sc)
6586 {
6587     uint32_t val;
6588     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6589     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6590     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6591     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6592 }
6593
6594 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6595 static uint8_t
6596 bxe_reset_is_global(struct bxe_softc *sc)
6597 {
6598     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6599     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6600     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6601 }
6602
6603 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6604 static void
6605 bxe_set_reset_done(struct bxe_softc *sc)
6606 {
6607     uint32_t val;
6608     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6609                                  BXE_PATH0_RST_IN_PROG_BIT;
6610
6611     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6612
6613     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6614     /* Clear the bit */
6615     val &= ~bit;
6616     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6617
6618     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6619 }
6620
6621 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6622 static void
6623 bxe_set_reset_in_progress(struct bxe_softc *sc)
6624 {
6625     uint32_t val;
6626     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6627                                  BXE_PATH0_RST_IN_PROG_BIT;
6628
6629     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6630
6631     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6632     /* Set the bit */
6633     val |= bit;
6634     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6635
6636     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6637 }
6638
6639 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6640 static uint8_t
6641 bxe_reset_is_done(struct bxe_softc *sc,
6642                   int              engine)
6643 {
6644     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6645     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6646                             BXE_PATH0_RST_IN_PROG_BIT;
6647
6648     /* return false if bit is set */
6649     return (val & bit) ? FALSE : TRUE;
6650 }
6651
6652 /* get the load status for an engine, should be run under rtnl lock */
6653 static uint8_t
6654 bxe_get_load_status(struct bxe_softc *sc,
6655                     int              engine)
6656 {
6657     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6658                              BXE_PATH0_LOAD_CNT_MASK;
6659     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6660                               BXE_PATH0_LOAD_CNT_SHIFT;
6661     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6662
6663     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6664
6665     val = ((val & mask) >> shift);
6666
6667     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6668
6669     return (val != 0);
6670 }
6671
6672 /* set pf load mark */
6673 /* XXX needs to be under rtnl lock */
6674 static void
6675 bxe_set_pf_load(struct bxe_softc *sc)
6676 {
6677     uint32_t val;
6678     uint32_t val1;
6679     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6680                                   BXE_PATH0_LOAD_CNT_MASK;
6681     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6682                                    BXE_PATH0_LOAD_CNT_SHIFT;
6683
6684     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6685
6686     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6687     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6688
6689     /* get the current counter value */
6690     val1 = ((val & mask) >> shift);
6691
6692     /* set bit of this PF */
6693     val1 |= (1 << SC_ABS_FUNC(sc));
6694
6695     /* clear the old value */
6696     val &= ~mask;
6697
6698     /* set the new one */
6699     val |= ((val1 << shift) & mask);
6700
6701     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6702
6703     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6704 }
6705
6706 /* clear pf load mark */
6707 /* XXX needs to be under rtnl lock */
6708 static uint8_t
6709 bxe_clear_pf_load(struct bxe_softc *sc)
6710 {
6711     uint32_t val1, val;
6712     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6713                                   BXE_PATH0_LOAD_CNT_MASK;
6714     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6715                                    BXE_PATH0_LOAD_CNT_SHIFT;
6716
6717     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6718     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6719     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6720
6721     /* get the current counter value */
6722     val1 = (val & mask) >> shift;
6723
6724     /* clear bit of that PF */
6725     val1 &= ~(1 << SC_ABS_FUNC(sc));
6726
6727     /* clear the old value */
6728     val &= ~mask;
6729
6730     /* set the new one */
6731     val |= ((val1 << shift) & mask);
6732
6733     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6734     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6735     return (val1 != 0);
6736 }
6737
6738 /* send load requrest to mcp and analyze response */
6739 static int
6740 bxe_nic_load_request(struct bxe_softc *sc,
6741                      uint32_t         *load_code)
6742 {
6743     /* init fw_seq */
6744     sc->fw_seq =
6745         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6746          DRV_MSG_SEQ_NUMBER_MASK);
6747
6748     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6749
6750     /* get the current FW pulse sequence */
6751     sc->fw_drv_pulse_wr_seq =
6752         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6753          DRV_PULSE_SEQ_MASK);
6754
6755     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6756           sc->fw_drv_pulse_wr_seq);
6757
6758     /* load request */
6759     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6760                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6761
6762     /* if the MCP fails to respond we must abort */
6763     if (!(*load_code)) {
6764         BLOGE(sc, "MCP response failure!\n");
6765         return (-1);
6766     }
6767
6768     /* if MCP refused then must abort */
6769     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6770         BLOGE(sc, "MCP refused load request\n");
6771         return (-1);
6772     }
6773
6774     return (0);
6775 }
6776
6777 /*
6778  * Check whether another PF has already loaded FW to chip. In virtualized
6779  * environments a pf from anoth VM may have already initialized the device
6780  * including loading FW.
6781  */
6782 static int
6783 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6784                          uint32_t         load_code)
6785 {
6786     uint32_t my_fw, loaded_fw;
6787
6788     /* is another pf loaded on this engine? */
6789     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6790         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6791         /* build my FW version dword */
6792         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6793                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6794                  (BCM_5710_FW_REVISION_VERSION << 16) +
6795                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6796
6797         /* read loaded FW from chip */
6798         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6799         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6800               loaded_fw, my_fw);
6801
6802         /* abort nic load if version mismatch */
6803         if (my_fw != loaded_fw) {
6804             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6805                   loaded_fw, my_fw);
6806             return (-1);
6807         }
6808     }
6809
6810     return (0);
6811 }
6812
6813 /* mark PMF if applicable */
6814 static void
6815 bxe_nic_load_pmf(struct bxe_softc *sc,
6816                  uint32_t         load_code)
6817 {
6818     uint32_t ncsi_oem_data_addr;
6819
6820     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6821         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6822         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6823         /*
6824          * Barrier here for ordering between the writing to sc->port.pmf here
6825          * and reading it from the periodic task.
6826          */
6827         sc->port.pmf = 1;
6828         mb();
6829     } else {
6830         sc->port.pmf = 0;
6831     }
6832
6833     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6834
6835     /* XXX needed? */
6836     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6837         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6838             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6839             if (ncsi_oem_data_addr) {
6840                 REG_WR(sc,
6841                        (ncsi_oem_data_addr +
6842                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6843                        0);
6844             }
6845         }
6846     }
6847 }
6848
6849 static void
6850 bxe_read_mf_cfg(struct bxe_softc *sc)
6851 {
6852     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6853     int abs_func;
6854     int vn;
6855
6856     if (BXE_NOMCP(sc)) {
6857         return; /* what should be the default bvalue in this case */
6858     }
6859
6860     /*
6861      * The formula for computing the absolute function number is...
6862      * For 2 port configuration (4 functions per port):
6863      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6864      * For 4 port configuration (2 functions per port):
6865      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6866      */
6867     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6868         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6869         if (abs_func >= E1H_FUNC_MAX) {
6870             break;
6871         }
6872         sc->devinfo.mf_info.mf_config[vn] =
6873             MFCFG_RD(sc, func_mf_config[abs_func].config);
6874     }
6875
6876     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6877         FUNC_MF_CFG_FUNC_DISABLED) {
6878         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6879         sc->flags |= BXE_MF_FUNC_DIS;
6880     } else {
6881         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6882         sc->flags &= ~BXE_MF_FUNC_DIS;
6883     }
6884 }
6885
6886 /* acquire split MCP access lock register */
6887 static int bxe_acquire_alr(struct bxe_softc *sc)
6888 {
6889     uint32_t j, val;
6890
6891     for (j = 0; j < 1000; j++) {
6892         val = (1UL << 31);
6893         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6894         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6895         if (val & (1L << 31))
6896             break;
6897
6898         DELAY(5000);
6899     }
6900
6901     if (!(val & (1L << 31))) {
6902         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6903         return (-1);
6904     }
6905
6906     return (0);
6907 }
6908
6909 /* release split MCP access lock register */
6910 static void bxe_release_alr(struct bxe_softc *sc)
6911 {
6912     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6913 }
6914
6915 static void
6916 bxe_fan_failure(struct bxe_softc *sc)
6917 {
6918     int port = SC_PORT(sc);
6919     uint32_t ext_phy_config;
6920
6921     /* mark the failure */
6922     ext_phy_config =
6923         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
6924
6925     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
6926     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
6927     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
6928              ext_phy_config);
6929
6930     /* log the failure */
6931     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
6932               "the card to prevent permanent damage. "
6933               "Please contact OEM Support for assistance\n");
6934
6935     /* XXX */
6936 #if 1
6937     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
6938 #else
6939     /*
6940      * Schedule device reset (unload)
6941      * This is due to some boards consuming sufficient power when driver is
6942      * up to overheat if fan fails.
6943      */
6944     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
6945     schedule_delayed_work(&sc->sp_rtnl_task, 0);
6946 #endif
6947 }
6948
6949 /* this function is called upon a link interrupt */
6950 static void
6951 bxe_link_attn(struct bxe_softc *sc)
6952 {
6953     uint32_t pause_enabled = 0;
6954     struct host_port_stats *pstats;
6955     int cmng_fns;
6956
6957     /* Make sure that we are synced with the current statistics */
6958     bxe_stats_handle(sc, STATS_EVENT_STOP);
6959
6960     elink_link_update(&sc->link_params, &sc->link_vars);
6961
6962     if (sc->link_vars.link_up) {
6963
6964         /* dropless flow control */
6965         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
6966             pause_enabled = 0;
6967
6968             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
6969                 pause_enabled = 1;
6970             }
6971
6972             REG_WR(sc,
6973                    (BAR_USTRORM_INTMEM +
6974                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
6975                    pause_enabled);
6976         }
6977
6978         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
6979             pstats = BXE_SP(sc, port_stats);
6980             /* reset old mac stats */
6981             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
6982         }
6983
6984         if (sc->state == BXE_STATE_OPEN) {
6985             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
6986         }
6987     }
6988
6989     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
6990         cmng_fns = bxe_get_cmng_fns_mode(sc);
6991
6992         if (cmng_fns != CMNG_FNS_NONE) {
6993             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
6994             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
6995         } else {
6996             /* rate shaping and fairness are disabled */
6997             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
6998         }
6999     }
7000
7001     bxe_link_report_locked(sc);
7002
7003     if (IS_MF(sc)) {
7004         ; // XXX bxe_link_sync_notify(sc);
7005     }
7006 }
7007
7008 static void
7009 bxe_attn_int_asserted(struct bxe_softc *sc,
7010                       uint32_t         asserted)
7011 {
7012     int port = SC_PORT(sc);
7013     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7014                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7015     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7016                                         NIG_REG_MASK_INTERRUPT_PORT0;
7017     uint32_t aeu_mask;
7018     uint32_t nig_mask = 0;
7019     uint32_t reg_addr;
7020     uint32_t igu_acked;
7021     uint32_t cnt;
7022
7023     if (sc->attn_state & asserted) {
7024         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7025     }
7026
7027     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7028
7029     aeu_mask = REG_RD(sc, aeu_addr);
7030
7031     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7032           aeu_mask, asserted);
7033
7034     aeu_mask &= ~(asserted & 0x3ff);
7035
7036     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7037
7038     REG_WR(sc, aeu_addr, aeu_mask);
7039
7040     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7041
7042     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7043     sc->attn_state |= asserted;
7044     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7045
7046     if (asserted & ATTN_HARD_WIRED_MASK) {
7047         if (asserted & ATTN_NIG_FOR_FUNC) {
7048
7049             bxe_acquire_phy_lock(sc);
7050             /* save nig interrupt mask */
7051             nig_mask = REG_RD(sc, nig_int_mask_addr);
7052
7053             /* If nig_mask is not set, no need to call the update function */
7054             if (nig_mask) {
7055                 REG_WR(sc, nig_int_mask_addr, 0);
7056
7057                 bxe_link_attn(sc);
7058             }
7059
7060             /* handle unicore attn? */
7061         }
7062
7063         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7064             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7065         }
7066
7067         if (asserted & GPIO_2_FUNC) {
7068             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7069         }
7070
7071         if (asserted & GPIO_3_FUNC) {
7072             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7073         }
7074
7075         if (asserted & GPIO_4_FUNC) {
7076             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7077         }
7078
7079         if (port == 0) {
7080             if (asserted & ATTN_GENERAL_ATTN_1) {
7081                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7082                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7083             }
7084             if (asserted & ATTN_GENERAL_ATTN_2) {
7085                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7086                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7087             }
7088             if (asserted & ATTN_GENERAL_ATTN_3) {
7089                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7090                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7091             }
7092         } else {
7093             if (asserted & ATTN_GENERAL_ATTN_4) {
7094                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7095                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7096             }
7097             if (asserted & ATTN_GENERAL_ATTN_5) {
7098                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7099                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7100             }
7101             if (asserted & ATTN_GENERAL_ATTN_6) {
7102                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7103                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7104             }
7105         }
7106     } /* hardwired */
7107
7108     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7109         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7110     } else {
7111         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7112     }
7113
7114     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7115           asserted,
7116           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7117     REG_WR(sc, reg_addr, asserted);
7118
7119     /* now set back the mask */
7120     if (asserted & ATTN_NIG_FOR_FUNC) {
7121         /*
7122          * Verify that IGU ack through BAR was written before restoring
7123          * NIG mask. This loop should exit after 2-3 iterations max.
7124          */
7125         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7126             cnt = 0;
7127
7128             do {
7129                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7130             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7131                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7132
7133             if (!igu_acked) {
7134                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7135             }
7136
7137             mb();
7138         }
7139
7140         REG_WR(sc, nig_int_mask_addr, nig_mask);
7141
7142         bxe_release_phy_lock(sc);
7143     }
7144 }
7145
7146 static void
7147 bxe_print_next_block(struct bxe_softc *sc,
7148                      int              idx,
7149                      const char       *blk)
7150 {
7151     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7152 }
7153
7154 static int
7155 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7156                               uint32_t         sig,
7157                               int              par_num,
7158                               uint8_t          print)
7159 {
7160     uint32_t cur_bit = 0;
7161     int i = 0;
7162
7163     for (i = 0; sig; i++) {
7164         cur_bit = ((uint32_t)0x1 << i);
7165         if (sig & cur_bit) {
7166             switch (cur_bit) {
7167             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7168                 if (print)
7169                     bxe_print_next_block(sc, par_num++, "BRB");
7170                 break;
7171             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7172                 if (print)
7173                     bxe_print_next_block(sc, par_num++, "PARSER");
7174                 break;
7175             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7176                 if (print)
7177                     bxe_print_next_block(sc, par_num++, "TSDM");
7178                 break;
7179             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7180                 if (print)
7181                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7182                 break;
7183             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7184                 if (print)
7185                     bxe_print_next_block(sc, par_num++, "TCM");
7186                 break;
7187             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7188                 if (print)
7189                     bxe_print_next_block(sc, par_num++, "TSEMI");
7190                 break;
7191             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7192                 if (print)
7193                     bxe_print_next_block(sc, par_num++, "XPB");
7194                 break;
7195             }
7196
7197             /* Clear the bit */
7198             sig &= ~cur_bit;
7199         }
7200     }
7201
7202     return (par_num);
7203 }
7204
7205 static int
7206 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7207                               uint32_t         sig,
7208                               int              par_num,
7209                               uint8_t          *global,
7210                               uint8_t          print)
7211 {
7212     int i = 0;
7213     uint32_t cur_bit = 0;
7214     for (i = 0; sig; i++) {
7215         cur_bit = ((uint32_t)0x1 << i);
7216         if (sig & cur_bit) {
7217             switch (cur_bit) {
7218             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7219                 if (print)
7220                     bxe_print_next_block(sc, par_num++, "PBF");
7221                 break;
7222             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7223                 if (print)
7224                     bxe_print_next_block(sc, par_num++, "QM");
7225                 break;
7226             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7227                 if (print)
7228                     bxe_print_next_block(sc, par_num++, "TM");
7229                 break;
7230             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7231                 if (print)
7232                     bxe_print_next_block(sc, par_num++, "XSDM");
7233                 break;
7234             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7235                 if (print)
7236                     bxe_print_next_block(sc, par_num++, "XCM");
7237                 break;
7238             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7239                 if (print)
7240                     bxe_print_next_block(sc, par_num++, "XSEMI");
7241                 break;
7242             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7243                 if (print)
7244                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7245                 break;
7246             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7247                 if (print)
7248                     bxe_print_next_block(sc, par_num++, "NIG");
7249                 break;
7250             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7251                 if (print)
7252                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7253                 *global = TRUE;
7254                 break;
7255             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7256                 if (print)
7257                     bxe_print_next_block(sc, par_num++, "DEBUG");
7258                 break;
7259             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7260                 if (print)
7261                     bxe_print_next_block(sc, par_num++, "USDM");
7262                 break;
7263             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7264                 if (print)
7265                     bxe_print_next_block(sc, par_num++, "UCM");
7266                 break;
7267             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7268                 if (print)
7269                     bxe_print_next_block(sc, par_num++, "USEMI");
7270                 break;
7271             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7272                 if (print)
7273                     bxe_print_next_block(sc, par_num++, "UPB");
7274                 break;
7275             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7276                 if (print)
7277                     bxe_print_next_block(sc, par_num++, "CSDM");
7278                 break;
7279             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7280                 if (print)
7281                     bxe_print_next_block(sc, par_num++, "CCM");
7282                 break;
7283             }
7284
7285             /* Clear the bit */
7286             sig &= ~cur_bit;
7287         }
7288     }
7289
7290     return (par_num);
7291 }
7292
7293 static int
7294 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7295                               uint32_t         sig,
7296                               int              par_num,
7297                               uint8_t          print)
7298 {
7299     uint32_t cur_bit = 0;
7300     int i = 0;
7301
7302     for (i = 0; sig; i++) {
7303         cur_bit = ((uint32_t)0x1 << i);
7304         if (sig & cur_bit) {
7305             switch (cur_bit) {
7306             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7307                 if (print)
7308                     bxe_print_next_block(sc, par_num++, "CSEMI");
7309                 break;
7310             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7311                 if (print)
7312                     bxe_print_next_block(sc, par_num++, "PXP");
7313                 break;
7314             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7315                 if (print)
7316                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7317                 break;
7318             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7319                 if (print)
7320                     bxe_print_next_block(sc, par_num++, "CFC");
7321                 break;
7322             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7323                 if (print)
7324                     bxe_print_next_block(sc, par_num++, "CDU");
7325                 break;
7326             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7327                 if (print)
7328                     bxe_print_next_block(sc, par_num++, "DMAE");
7329                 break;
7330             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7331                 if (print)
7332                     bxe_print_next_block(sc, par_num++, "IGU");
7333                 break;
7334             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7335                 if (print)
7336                     bxe_print_next_block(sc, par_num++, "MISC");
7337                 break;
7338             }
7339
7340             /* Clear the bit */
7341             sig &= ~cur_bit;
7342         }
7343     }
7344
7345     return (par_num);
7346 }
7347
7348 static int
7349 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7350                               uint32_t         sig,
7351                               int              par_num,
7352                               uint8_t          *global,
7353                               uint8_t          print)
7354 {
7355     uint32_t cur_bit = 0;
7356     int i = 0;
7357
7358     for (i = 0; sig; i++) {
7359         cur_bit = ((uint32_t)0x1 << i);
7360         if (sig & cur_bit) {
7361             switch (cur_bit) {
7362             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7363                 if (print)
7364                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7365                 *global = TRUE;
7366                 break;
7367             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7368                 if (print)
7369                     bxe_print_next_block(sc, par_num++,
7370                               "MCP UMP RX");
7371                 *global = TRUE;
7372                 break;
7373             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7374                 if (print)
7375                     bxe_print_next_block(sc, par_num++,
7376                               "MCP UMP TX");
7377                 *global = TRUE;
7378                 break;
7379             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7380                 if (print)
7381                     bxe_print_next_block(sc, par_num++,
7382                               "MCP SCPAD");
7383                 *global = TRUE;
7384                 break;
7385             }
7386
7387             /* Clear the bit */
7388             sig &= ~cur_bit;
7389         }
7390     }
7391
7392     return (par_num);
7393 }
7394
7395 static int
7396 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7397                               uint32_t         sig,
7398                               int              par_num,
7399                               uint8_t          print)
7400 {
7401     uint32_t cur_bit = 0;
7402     int i = 0;
7403
7404     for (i = 0; sig; i++) {
7405         cur_bit = ((uint32_t)0x1 << i);
7406         if (sig & cur_bit) {
7407             switch (cur_bit) {
7408             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7409                 if (print)
7410                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7411                 break;
7412             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7413                 if (print)
7414                     bxe_print_next_block(sc, par_num++, "ATC");
7415                 break;
7416             }
7417
7418             /* Clear the bit */
7419             sig &= ~cur_bit;
7420         }
7421     }
7422
7423     return (par_num);
7424 }
7425
7426 static uint8_t
7427 bxe_parity_attn(struct bxe_softc *sc,
7428                 uint8_t          *global,
7429                 uint8_t          print,
7430                 uint32_t         *sig)
7431 {
7432     int par_num = 0;
7433
7434     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7435         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7436         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7437         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7438         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7439         BLOGE(sc, "Parity error: HW block parity attention:\n"
7440                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7441               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7442               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7443               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7444               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7445               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7446
7447         if (print)
7448             BLOGI(sc, "Parity errors detected in blocks: ");
7449
7450         par_num =
7451             bxe_check_blocks_with_parity0(sc, sig[0] &
7452                                           HW_PRTY_ASSERT_SET_0,
7453                                           par_num, print);
7454         par_num =
7455             bxe_check_blocks_with_parity1(sc, sig[1] &
7456                                           HW_PRTY_ASSERT_SET_1,
7457                                           par_num, global, print);
7458         par_num =
7459             bxe_check_blocks_with_parity2(sc, sig[2] &
7460                                           HW_PRTY_ASSERT_SET_2,
7461                                           par_num, print);
7462         par_num =
7463             bxe_check_blocks_with_parity3(sc, sig[3] &
7464                                           HW_PRTY_ASSERT_SET_3,
7465                                           par_num, global, print);
7466         par_num =
7467             bxe_check_blocks_with_parity4(sc, sig[4] &
7468                                           HW_PRTY_ASSERT_SET_4,
7469                                           par_num, print);
7470
7471         if (print)
7472             BLOGI(sc, "\n");
7473
7474         return (TRUE);
7475     }
7476
7477     return (FALSE);
7478 }
7479
7480 static uint8_t
7481 bxe_chk_parity_attn(struct bxe_softc *sc,
7482                     uint8_t          *global,
7483                     uint8_t          print)
7484 {
7485     struct attn_route attn = { {0} };
7486     int port = SC_PORT(sc);
7487
7488     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7489     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7490     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7491     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7492
7493     /*
7494      * Since MCP attentions can't be disabled inside the block, we need to
7495      * read AEU registers to see whether they're currently disabled
7496      */
7497     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7498                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7499                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7500                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7501
7502
7503     if (!CHIP_IS_E1x(sc))
7504         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7505
7506     return (bxe_parity_attn(sc, global, print, attn.sig));
7507 }
7508
7509 static void
7510 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7511                          uint32_t         attn)
7512 {
7513     uint32_t val;
7514
7515     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7516         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7517         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7518         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7519             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7520         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7521             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7522         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7523             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7524         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7525             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7526         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7527             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7528         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7529             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7530         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7531             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7532         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7533             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7534         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7535             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7536     }
7537
7538     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7539         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7540         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7541         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7542             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7543         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7544             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7545         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7546             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7547         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7548             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7549         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7550             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7551         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7552             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7553     }
7554
7555     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7556                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7557         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7558               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7559                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7560     }
7561 }
7562
7563 static void
7564 bxe_e1h_disable(struct bxe_softc *sc)
7565 {
7566     int port = SC_PORT(sc);
7567
7568     bxe_tx_disable(sc);
7569
7570     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7571 }
7572
7573 static void
7574 bxe_e1h_enable(struct bxe_softc *sc)
7575 {
7576     int port = SC_PORT(sc);
7577
7578     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7579
7580     // XXX bxe_tx_enable(sc);
7581 }
7582
7583 /*
7584  * called due to MCP event (on pmf):
7585  *   reread new bandwidth configuration
7586  *   configure FW
7587  *   notify others function about the change
7588  */
7589 static void
7590 bxe_config_mf_bw(struct bxe_softc *sc)
7591 {
7592     if (sc->link_vars.link_up) {
7593         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7594         // XXX bxe_link_sync_notify(sc);
7595     }
7596
7597     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7598 }
7599
7600 static void
7601 bxe_set_mf_bw(struct bxe_softc *sc)
7602 {
7603     bxe_config_mf_bw(sc);
7604     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7605 }
7606
7607 static void
7608 bxe_handle_eee_event(struct bxe_softc *sc)
7609 {
7610     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7611     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7612 }
7613
7614 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7615
7616 static void
7617 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7618 {
7619     struct eth_stats_info *ether_stat =
7620         &sc->sp->drv_info_to_mcp.ether_stat;
7621
7622     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7623             ETH_STAT_INFO_VERSION_LEN);
7624
7625     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7626     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7627                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7628                                           ether_stat->mac_local + MAC_PAD,
7629                                           MAC_PAD, ETH_ALEN);
7630
7631     ether_stat->mtu_size = sc->mtu;
7632
7633     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7634     if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
7635         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7636     }
7637
7638     // XXX ether_stat->feature_flags |= ???;
7639
7640     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7641
7642     ether_stat->txq_size = sc->tx_ring_size;
7643     ether_stat->rxq_size = sc->rx_ring_size;
7644 }
7645
7646 static void
7647 bxe_handle_drv_info_req(struct bxe_softc *sc)
7648 {
7649     enum drv_info_opcode op_code;
7650     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7651
7652     /* if drv_info version supported by MFW doesn't match - send NACK */
7653     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7654         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7655         return;
7656     }
7657
7658     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7659                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7660
7661     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7662
7663     switch (op_code) {
7664     case ETH_STATS_OPCODE:
7665         bxe_drv_info_ether_stat(sc);
7666         break;
7667     case FCOE_STATS_OPCODE:
7668     case ISCSI_STATS_OPCODE:
7669     default:
7670         /* if op code isn't supported - send NACK */
7671         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7672         return;
7673     }
7674
7675     /*
7676      * If we got drv_info attn from MFW then these fields are defined in
7677      * shmem2 for sure
7678      */
7679     SHMEM2_WR(sc, drv_info_host_addr_lo,
7680               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7681     SHMEM2_WR(sc, drv_info_host_addr_hi,
7682               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7683
7684     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7685 }
7686
7687 static void
7688 bxe_dcc_event(struct bxe_softc *sc,
7689               uint32_t         dcc_event)
7690 {
7691     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7692
7693     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7694         /*
7695          * This is the only place besides the function initialization
7696          * where the sc->flags can change so it is done without any
7697          * locks
7698          */
7699         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7700             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7701             sc->flags |= BXE_MF_FUNC_DIS;
7702             bxe_e1h_disable(sc);
7703         } else {
7704             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7705             sc->flags &= ~BXE_MF_FUNC_DIS;
7706             bxe_e1h_enable(sc);
7707         }
7708         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7709     }
7710
7711     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7712         bxe_config_mf_bw(sc);
7713         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7714     }
7715
7716     /* Report results to MCP */
7717     if (dcc_event)
7718         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7719     else
7720         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7721 }
7722
7723 static void
7724 bxe_pmf_update(struct bxe_softc *sc)
7725 {
7726     int port = SC_PORT(sc);
7727     uint32_t val;
7728
7729     sc->port.pmf = 1;
7730     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7731
7732     /*
7733      * We need the mb() to ensure the ordering between the writing to
7734      * sc->port.pmf here and reading it from the bxe_periodic_task().
7735      */
7736     mb();
7737
7738     /* queue a periodic task */
7739     // XXX schedule task...
7740
7741     // XXX bxe_dcbx_pmf_update(sc);
7742
7743     /* enable nig attention */
7744     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7745     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7746         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7747         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7748     } else if (!CHIP_IS_E1x(sc)) {
7749         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7750         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7751     }
7752
7753     bxe_stats_handle(sc, STATS_EVENT_PMF);
7754 }
7755
7756 static int
7757 bxe_mc_assert(struct bxe_softc *sc)
7758 {
7759     char last_idx;
7760     int i, rc = 0;
7761     uint32_t row0, row1, row2, row3;
7762
7763     /* XSTORM */
7764     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7765     if (last_idx)
7766         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7767
7768     /* print the asserts */
7769     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7770
7771         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7772         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7773         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7774         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7775
7776         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7777             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7778                   i, row3, row2, row1, row0);
7779             rc++;
7780         } else {
7781             break;
7782         }
7783     }
7784
7785     /* TSTORM */
7786     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7787     if (last_idx) {
7788         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7789     }
7790
7791     /* print the asserts */
7792     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7793
7794         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7795         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7796         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7797         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7798
7799         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7800             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7801                   i, row3, row2, row1, row0);
7802             rc++;
7803         } else {
7804             break;
7805         }
7806     }
7807
7808     /* CSTORM */
7809     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7810     if (last_idx) {
7811         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7812     }
7813
7814     /* print the asserts */
7815     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7816
7817         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7818         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7819         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7820         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7821
7822         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7823             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7824                   i, row3, row2, row1, row0);
7825             rc++;
7826         } else {
7827             break;
7828         }
7829     }
7830
7831     /* USTORM */
7832     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7833     if (last_idx) {
7834         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7835     }
7836
7837     /* print the asserts */
7838     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7839
7840         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7841         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7842         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7843         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7844
7845         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7846             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7847                   i, row3, row2, row1, row0);
7848             rc++;
7849         } else {
7850             break;
7851         }
7852     }
7853
7854     return (rc);
7855 }
7856
7857 static void
7858 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7859                          uint32_t         attn)
7860 {
7861     int func = SC_FUNC(sc);
7862     uint32_t val;
7863
7864     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7865
7866         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7867
7868             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7869             bxe_read_mf_cfg(sc);
7870             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7871                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7872             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7873
7874             if (val & DRV_STATUS_DCC_EVENT_MASK)
7875                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7876
7877             if (val & DRV_STATUS_SET_MF_BW)
7878                 bxe_set_mf_bw(sc);
7879
7880             if (val & DRV_STATUS_DRV_INFO_REQ)
7881                 bxe_handle_drv_info_req(sc);
7882
7883             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7884                 bxe_pmf_update(sc);
7885
7886             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7887                 bxe_handle_eee_event(sc);
7888
7889             if (sc->link_vars.periodic_flags &
7890                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7891                 /* sync with link */
7892                 bxe_acquire_phy_lock(sc);
7893                 sc->link_vars.periodic_flags &=
7894                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7895                 bxe_release_phy_lock(sc);
7896                 if (IS_MF(sc))
7897                     ; // XXX bxe_link_sync_notify(sc);
7898                 bxe_link_report(sc);
7899             }
7900
7901             /*
7902              * Always call it here: bxe_link_report() will
7903              * prevent the link indication duplication.
7904              */
7905             bxe_link_status_update(sc);
7906
7907         } else if (attn & BXE_MC_ASSERT_BITS) {
7908
7909             BLOGE(sc, "MC assert!\n");
7910             bxe_mc_assert(sc);
7911             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
7912             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
7913             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
7914             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
7915             bxe_panic(sc, ("MC assert!\n"));
7916
7917         } else if (attn & BXE_MCP_ASSERT) {
7918
7919             BLOGE(sc, "MCP assert!\n");
7920             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
7921             // XXX bxe_fw_dump(sc);
7922
7923         } else {
7924             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
7925         }
7926     }
7927
7928     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
7929         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
7930         if (attn & BXE_GRC_TIMEOUT) {
7931             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
7932             BLOGE(sc, "GRC time-out 0x%08x\n", val);
7933         }
7934         if (attn & BXE_GRC_RSV) {
7935             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
7936             BLOGE(sc, "GRC reserved 0x%08x\n", val);
7937         }
7938         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
7939     }
7940 }
7941
7942 static void
7943 bxe_attn_int_deasserted2(struct bxe_softc *sc,
7944                          uint32_t         attn)
7945 {
7946     int port = SC_PORT(sc);
7947     int reg_offset;
7948     uint32_t val0, mask0, val1, mask1;
7949     uint32_t val;
7950
7951     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
7952         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
7953         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
7954         /* CFC error attention */
7955         if (val & 0x2) {
7956             BLOGE(sc, "FATAL error from CFC\n");
7957         }
7958     }
7959
7960     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
7961         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
7962         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
7963         /* RQ_USDMDP_FIFO_OVERFLOW */
7964         if (val & 0x18000) {
7965             BLOGE(sc, "FATAL error from PXP\n");
7966         }
7967
7968         if (!CHIP_IS_E1x(sc)) {
7969             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
7970             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
7971         }
7972     }
7973
7974 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
7975 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
7976
7977     if (attn & AEU_PXP2_HW_INT_BIT) {
7978         /*  CQ47854 workaround do not panic on
7979          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
7980          */
7981         if (!CHIP_IS_E1x(sc)) {
7982             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
7983             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
7984             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
7985             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
7986             /*
7987              * If the only PXP2_EOP_ERROR_BIT is set in
7988              * STS0 and STS1 - clear it
7989              *
7990              * probably we lose additional attentions between
7991              * STS0 and STS_CLR0, in this case user will not
7992              * be notified about them
7993              */
7994             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
7995                 !(val1 & mask1))
7996                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
7997
7998             /* print the register, since no one can restore it */
7999             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8000
8001             /*
8002              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8003              * then notify
8004              */
8005             if (val0 & PXP2_EOP_ERROR_BIT) {
8006                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8007
8008                 /*
8009                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8010                  * set then clear attention from PXP2 block without panic
8011                  */
8012                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8013                     ((val1 & mask1) == 0))
8014                     attn &= ~AEU_PXP2_HW_INT_BIT;
8015             }
8016         }
8017     }
8018
8019     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8020         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8021                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8022
8023         val = REG_RD(sc, reg_offset);
8024         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8025         REG_WR(sc, reg_offset, val);
8026
8027         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8028               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8029         bxe_panic(sc, ("HW block attention set2\n"));
8030     }
8031 }
8032
8033 static void
8034 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8035                          uint32_t         attn)
8036 {
8037     int port = SC_PORT(sc);
8038     int reg_offset;
8039     uint32_t val;
8040
8041     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8042         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8043         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8044         /* DORQ discard attention */
8045         if (val & 0x2) {
8046             BLOGE(sc, "FATAL error from DORQ\n");
8047         }
8048     }
8049
8050     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8051         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8052                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8053
8054         val = REG_RD(sc, reg_offset);
8055         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8056         REG_WR(sc, reg_offset, val);
8057
8058         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8059               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8060         bxe_panic(sc, ("HW block attention set1\n"));
8061     }
8062 }
8063
8064 static void
8065 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8066                          uint32_t         attn)
8067 {
8068     int port = SC_PORT(sc);
8069     int reg_offset;
8070     uint32_t val;
8071
8072     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8073                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8074
8075     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8076         val = REG_RD(sc, reg_offset);
8077         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8078         REG_WR(sc, reg_offset, val);
8079
8080         BLOGW(sc, "SPIO5 hw attention\n");
8081
8082         /* Fan failure attention */
8083         elink_hw_reset_phy(&sc->link_params);
8084         bxe_fan_failure(sc);
8085     }
8086
8087     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8088         bxe_acquire_phy_lock(sc);
8089         elink_handle_module_detect_int(&sc->link_params);
8090         bxe_release_phy_lock(sc);
8091     }
8092
8093     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8094         val = REG_RD(sc, reg_offset);
8095         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8096         REG_WR(sc, reg_offset, val);
8097
8098         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8099                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8100     }
8101 }
8102
8103 static void
8104 bxe_attn_int_deasserted(struct bxe_softc *sc,
8105                         uint32_t         deasserted)
8106 {
8107     struct attn_route attn;
8108     struct attn_route *group_mask;
8109     int port = SC_PORT(sc);
8110     int index;
8111     uint32_t reg_addr;
8112     uint32_t val;
8113     uint32_t aeu_mask;
8114     uint8_t global = FALSE;
8115
8116     /*
8117      * Need to take HW lock because MCP or other port might also
8118      * try to handle this event.
8119      */
8120     bxe_acquire_alr(sc);
8121
8122     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8123         /* XXX
8124          * In case of parity errors don't handle attentions so that
8125          * other function would "see" parity errors.
8126          */
8127         sc->recovery_state = BXE_RECOVERY_INIT;
8128         // XXX schedule a recovery task...
8129         /* disable HW interrupts */
8130         bxe_int_disable(sc);
8131         bxe_release_alr(sc);
8132         return;
8133     }
8134
8135     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8136     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8137     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8138     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8139     if (!CHIP_IS_E1x(sc)) {
8140         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8141     } else {
8142         attn.sig[4] = 0;
8143     }
8144
8145     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8146           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8147
8148     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8149         if (deasserted & (1 << index)) {
8150             group_mask = &sc->attn_group[index];
8151
8152             BLOGD(sc, DBG_INTR,
8153                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8154                   group_mask->sig[0], group_mask->sig[1],
8155                   group_mask->sig[2], group_mask->sig[3],
8156                   group_mask->sig[4]);
8157
8158             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8159             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8160             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8161             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8162             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8163         }
8164     }
8165
8166     bxe_release_alr(sc);
8167
8168     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8169         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8170                     COMMAND_REG_ATTN_BITS_CLR);
8171     } else {
8172         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8173     }
8174
8175     val = ~deasserted;
8176     BLOGD(sc, DBG_INTR,
8177           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8178           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8179     REG_WR(sc, reg_addr, val);
8180
8181     if (~sc->attn_state & deasserted) {
8182         BLOGE(sc, "IGU error\n");
8183     }
8184
8185     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8186                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8187
8188     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8189
8190     aeu_mask = REG_RD(sc, reg_addr);
8191
8192     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8193           aeu_mask, deasserted);
8194     aeu_mask |= (deasserted & 0x3ff);
8195     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8196
8197     REG_WR(sc, reg_addr, aeu_mask);
8198     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8199
8200     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8201     sc->attn_state &= ~deasserted;
8202     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8203 }
8204
8205 static void
8206 bxe_attn_int(struct bxe_softc *sc)
8207 {
8208     /* read local copy of bits */
8209     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8210     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8211     uint32_t attn_state = sc->attn_state;
8212
8213     /* look for changed bits */
8214     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8215     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8216
8217     BLOGD(sc, DBG_INTR,
8218           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8219           attn_bits, attn_ack, asserted, deasserted);
8220
8221     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8222         BLOGE(sc, "BAD attention state\n");
8223     }
8224
8225     /* handle bits that were raised */
8226     if (asserted) {
8227         bxe_attn_int_asserted(sc, asserted);
8228     }
8229
8230     if (deasserted) {
8231         bxe_attn_int_deasserted(sc, deasserted);
8232     }
8233 }
8234
8235 static uint16_t
8236 bxe_update_dsb_idx(struct bxe_softc *sc)
8237 {
8238     struct host_sp_status_block *def_sb = sc->def_sb;
8239     uint16_t rc = 0;
8240
8241     mb(); /* status block is written to by the chip */
8242
8243     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8244         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8245         rc |= BXE_DEF_SB_ATT_IDX;
8246     }
8247
8248     if (sc->def_idx != def_sb->sp_sb.running_index) {
8249         sc->def_idx = def_sb->sp_sb.running_index;
8250         rc |= BXE_DEF_SB_IDX;
8251     }
8252
8253     mb();
8254
8255     return (rc);
8256 }
8257
8258 static inline struct ecore_queue_sp_obj *
8259 bxe_cid_to_q_obj(struct bxe_softc *sc,
8260                  uint32_t         cid)
8261 {
8262     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8263     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8264 }
8265
8266 static void
8267 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8268 {
8269     struct ecore_mcast_ramrod_params rparam;
8270     int rc;
8271
8272     memset(&rparam, 0, sizeof(rparam));
8273
8274     rparam.mcast_obj = &sc->mcast_obj;
8275
8276     BXE_MCAST_LOCK(sc);
8277
8278     /* clear pending state for the last command */
8279     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8280
8281     /* if there are pending mcast commands - send them */
8282     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8283         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8284         if (rc < 0) {
8285             BLOGD(sc, DBG_SP,
8286                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8287         }
8288     }
8289
8290     BXE_MCAST_UNLOCK(sc);
8291 }
8292
8293 static void
8294 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8295                               union event_ring_elem *elem)
8296 {
8297     unsigned long ramrod_flags = 0;
8298     int rc = 0;
8299     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8300     struct ecore_vlan_mac_obj *vlan_mac_obj;
8301
8302     /* always push next commands out, don't wait here */
8303     bit_set(&ramrod_flags, RAMROD_CONT);
8304
8305     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8306     case ECORE_FILTER_MAC_PENDING:
8307         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8308         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8309         break;
8310
8311     case ECORE_FILTER_MCAST_PENDING:
8312         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8313         /*
8314          * This is only relevant for 57710 where multicast MACs are
8315          * configured as unicast MACs using the same ramrod.
8316          */
8317         bxe_handle_mcast_eqe(sc);
8318         return;
8319
8320     default:
8321         BLOGE(sc, "Unsupported classification command: %d\n",
8322               elem->message.data.eth_event.echo);
8323         return;
8324     }
8325
8326     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8327
8328     if (rc < 0) {
8329         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8330     } else if (rc > 0) {
8331         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8332     }
8333 }
8334
8335 static void
8336 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8337                        union event_ring_elem *elem)
8338 {
8339     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8340
8341     /* send rx_mode command again if was requested */
8342     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8343                                &sc->sp_state)) {
8344         bxe_set_storm_rx_mode(sc);
8345     }
8346 }
8347
8348 static void
8349 bxe_update_eq_prod(struct bxe_softc *sc,
8350                    uint16_t         prod)
8351 {
8352     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8353     wmb(); /* keep prod updates ordered */
8354 }
8355
8356 static void
8357 bxe_eq_int(struct bxe_softc *sc)
8358 {
8359     uint16_t hw_cons, sw_cons, sw_prod;
8360     union event_ring_elem *elem;
8361     uint8_t echo;
8362     uint32_t cid;
8363     uint8_t opcode;
8364     int spqe_cnt = 0;
8365     struct ecore_queue_sp_obj *q_obj;
8366     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8367     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8368
8369     hw_cons = le16toh(*sc->eq_cons_sb);
8370
8371     /*
8372      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8373      * when we get to the next-page we need to adjust so the loop
8374      * condition below will be met. The next element is the size of a
8375      * regular element and hence incrementing by 1
8376      */
8377     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8378         hw_cons++;
8379     }
8380
8381     /*
8382      * This function may never run in parallel with itself for a
8383      * specific sc and no need for a read memory barrier here.
8384      */
8385     sw_cons = sc->eq_cons;
8386     sw_prod = sc->eq_prod;
8387
8388     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8389           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8390
8391     for (;
8392          sw_cons != hw_cons;
8393          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8394
8395         elem = &sc->eq[EQ_DESC(sw_cons)];
8396
8397         /* elem CID originates from FW, actually LE */
8398         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8399         opcode = elem->message.opcode;
8400
8401         /* handle eq element */
8402         switch (opcode) {
8403
8404         case EVENT_RING_OPCODE_STAT_QUERY:
8405             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8406                   sc->stats_comp++);
8407             /* nothing to do with stats comp */
8408             goto next_spqe;
8409
8410         case EVENT_RING_OPCODE_CFC_DEL:
8411             /* handle according to cid range */
8412             /* we may want to verify here that the sc state is HALTING */
8413             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8414             q_obj = bxe_cid_to_q_obj(sc, cid);
8415             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8416                 break;
8417             }
8418             goto next_spqe;
8419
8420         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8421             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8422             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8423                 break;
8424             }
8425             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8426             goto next_spqe;
8427
8428         case EVENT_RING_OPCODE_START_TRAFFIC:
8429             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8430             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8431                 break;
8432             }
8433             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8434             goto next_spqe;
8435
8436         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8437             echo = elem->message.data.function_update_event.echo;
8438             if (echo == SWITCH_UPDATE) {
8439                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8440                 if (f_obj->complete_cmd(sc, f_obj,
8441                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8442                     break;
8443                 }
8444             }
8445             else {
8446                 BLOGD(sc, DBG_SP,
8447                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8448             }
8449             goto next_spqe;
8450
8451         case EVENT_RING_OPCODE_FORWARD_SETUP:
8452             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8453             if (q_obj->complete_cmd(sc, q_obj,
8454                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8455                 break;
8456             }
8457             goto next_spqe;
8458
8459         case EVENT_RING_OPCODE_FUNCTION_START:
8460             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8461             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8462                 break;
8463             }
8464             goto next_spqe;
8465
8466         case EVENT_RING_OPCODE_FUNCTION_STOP:
8467             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8468             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8469                 break;
8470             }
8471             goto next_spqe;
8472         }
8473
8474         switch (opcode | sc->state) {
8475         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8476         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8477             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8478             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8479             rss_raw->clear_pending(rss_raw);
8480             break;
8481
8482         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8483         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8484         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8485         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8486         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8487         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8488             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8489             bxe_handle_classification_eqe(sc, elem);
8490             break;
8491
8492         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8493         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8494         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8495             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8496             bxe_handle_mcast_eqe(sc);
8497             break;
8498
8499         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8500         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8501         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8502             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8503             bxe_handle_rx_mode_eqe(sc, elem);
8504             break;
8505
8506         default:
8507             /* unknown event log error and continue */
8508             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8509                   elem->message.opcode, sc->state);
8510         }
8511
8512 next_spqe:
8513         spqe_cnt++;
8514     } /* for */
8515
8516     mb();
8517     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8518
8519     sc->eq_cons = sw_cons;
8520     sc->eq_prod = sw_prod;
8521
8522     /* make sure that above mem writes were issued towards the memory */
8523     wmb();
8524
8525     /* update producer */
8526     bxe_update_eq_prod(sc, sc->eq_prod);
8527 }
8528
8529 static void
8530 bxe_handle_sp_tq(void *context,
8531                  int  pending)
8532 {
8533     struct bxe_softc *sc = (struct bxe_softc *)context;
8534     uint16_t status;
8535
8536     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8537
8538     /* what work needs to be performed? */
8539     status = bxe_update_dsb_idx(sc);
8540
8541     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8542
8543     /* HW attentions */
8544     if (status & BXE_DEF_SB_ATT_IDX) {
8545         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8546         bxe_attn_int(sc);
8547         status &= ~BXE_DEF_SB_ATT_IDX;
8548     }
8549
8550     /* SP events: STAT_QUERY and others */
8551     if (status & BXE_DEF_SB_IDX) {
8552         /* handle EQ completions */
8553         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8554         bxe_eq_int(sc);
8555         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8556                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8557         status &= ~BXE_DEF_SB_IDX;
8558     }
8559
8560     /* if status is non zero then something went wrong */
8561     if (__predict_false(status)) {
8562         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8563     }
8564
8565     /* ack status block only if something was actually handled */
8566     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8567                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8568
8569     /*
8570      * Must be called after the EQ processing (since eq leads to sriov
8571      * ramrod completion flows).
8572      * This flow may have been scheduled by the arrival of a ramrod
8573      * completion, or by the sriov code rescheduling itself.
8574      */
8575     // XXX bxe_iov_sp_task(sc);
8576
8577 }
8578
8579 static void
8580 bxe_handle_fp_tq(void *context,
8581                  int  pending)
8582 {
8583     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8584     struct bxe_softc *sc = fp->sc;
8585     uint8_t more_tx = FALSE;
8586     uint8_t more_rx = FALSE;
8587
8588     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8589
8590     /* XXX
8591      * IFF_DRV_RUNNING state can't be checked here since we process
8592      * slowpath events on a client queue during setup. Instead
8593      * we need to add a "process/continue" flag here that the driver
8594      * can use to tell the task here not to do anything.
8595      */
8596 #if 0
8597     if (!(if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING)) {
8598         return;
8599     }
8600 #endif
8601
8602     /* update the fastpath index */
8603     bxe_update_fp_sb_idx(fp);
8604
8605     /* XXX add loop here if ever support multiple tx CoS */
8606     /* fp->txdata[cos] */
8607     if (bxe_has_tx_work(fp)) {
8608         BXE_FP_TX_LOCK(fp);
8609         more_tx = bxe_txeof(sc, fp);
8610         BXE_FP_TX_UNLOCK(fp);
8611     }
8612
8613     if (bxe_has_rx_work(fp)) {
8614         more_rx = bxe_rxeof(sc, fp);
8615     }
8616
8617     if (more_rx /*|| more_tx*/) {
8618         /* still more work to do */
8619         taskqueue_enqueue(fp->tq, &fp->tq_task);
8620         return;
8621     }
8622
8623     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8624                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8625 }
8626
8627 static void
8628 bxe_task_fp(struct bxe_fastpath *fp)
8629 {
8630     struct bxe_softc *sc = fp->sc;
8631     uint8_t more_tx = FALSE;
8632     uint8_t more_rx = FALSE;
8633
8634     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8635
8636     /* update the fastpath index */
8637     bxe_update_fp_sb_idx(fp);
8638
8639     /* XXX add loop here if ever support multiple tx CoS */
8640     /* fp->txdata[cos] */
8641     if (bxe_has_tx_work(fp)) {
8642         BXE_FP_TX_LOCK(fp);
8643         more_tx = bxe_txeof(sc, fp);
8644         BXE_FP_TX_UNLOCK(fp);
8645     }
8646
8647     if (bxe_has_rx_work(fp)) {
8648         more_rx = bxe_rxeof(sc, fp);
8649     }
8650
8651     if (more_rx /*|| more_tx*/) {
8652         /* still more work to do, bail out if this ISR and process later */
8653         taskqueue_enqueue(fp->tq, &fp->tq_task);
8654         return;
8655     }
8656
8657     /*
8658      * Here we write the fastpath index taken before doing any tx or rx work.
8659      * It is very well possible other hw events occurred up to this point and
8660      * they were actually processed accordingly above. Since we're going to
8661      * write an older fastpath index, an interrupt is coming which we might
8662      * not do any work in.
8663      */
8664     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8665                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8666 }
8667
8668 /*
8669  * Legacy interrupt entry point.
8670  *
8671  * Verifies that the controller generated the interrupt and
8672  * then calls a separate routine to handle the various
8673  * interrupt causes: link, RX, and TX.
8674  */
8675 static void
8676 bxe_intr_legacy(void *xsc)
8677 {
8678     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8679     struct bxe_fastpath *fp;
8680     uint16_t status, mask;
8681     int i;
8682
8683     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8684
8685     /*
8686      * 0 for ustorm, 1 for cstorm
8687      * the bits returned from ack_int() are 0-15
8688      * bit 0 = attention status block
8689      * bit 1 = fast path status block
8690      * a mask of 0x2 or more = tx/rx event
8691      * a mask of 1 = slow path event
8692      */
8693
8694     status = bxe_ack_int(sc);
8695
8696     /* the interrupt is not for us */
8697     if (__predict_false(status == 0)) {
8698         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8699         return;
8700     }
8701
8702     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8703
8704     FOR_EACH_ETH_QUEUE(sc, i) {
8705         fp = &sc->fp[i];
8706         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8707         if (status & mask) {
8708             /* acknowledge and disable further fastpath interrupts */
8709             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8710             bxe_task_fp(fp);
8711             status &= ~mask;
8712         }
8713     }
8714
8715     if (__predict_false(status & 0x1)) {
8716         /* acknowledge and disable further slowpath interrupts */
8717         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8718
8719         /* schedule slowpath handler */
8720         taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8721
8722         status &= ~0x1;
8723     }
8724
8725     if (__predict_false(status)) {
8726         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8727     }
8728 }
8729
8730 /* slowpath interrupt entry point */
8731 static void
8732 bxe_intr_sp(void *xsc)
8733 {
8734     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8735
8736     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8737
8738     /* acknowledge and disable further slowpath interrupts */
8739     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8740
8741     /* schedule slowpath handler */
8742     taskqueue_enqueue(sc->sp_tq, &sc->sp_tq_task);
8743 }
8744
8745 /* fastpath interrupt entry point */
8746 static void
8747 bxe_intr_fp(void *xfp)
8748 {
8749     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8750     struct bxe_softc *sc = fp->sc;
8751
8752     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8753
8754     BLOGD(sc, DBG_INTR,
8755           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8756           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8757
8758     /* acknowledge and disable further fastpath interrupts */
8759     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8760
8761     bxe_task_fp(fp);
8762 }
8763
8764 /* Release all interrupts allocated by the driver. */
8765 static void
8766 bxe_interrupt_free(struct bxe_softc *sc)
8767 {
8768     int i;
8769
8770     switch (sc->interrupt_mode) {
8771     case INTR_MODE_INTX:
8772         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8773         if (sc->intr[0].resource != NULL) {
8774             bus_release_resource(sc->dev,
8775                                  SYS_RES_IRQ,
8776                                  sc->intr[0].rid,
8777                                  sc->intr[0].resource);
8778         }
8779         break;
8780     case INTR_MODE_MSI:
8781         for (i = 0; i < sc->intr_count; i++) {
8782             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8783             if (sc->intr[i].resource && sc->intr[i].rid) {
8784                 bus_release_resource(sc->dev,
8785                                      SYS_RES_IRQ,
8786                                      sc->intr[i].rid,
8787                                      sc->intr[i].resource);
8788             }
8789         }
8790         pci_release_msi(sc->dev);
8791         break;
8792     case INTR_MODE_MSIX:
8793         for (i = 0; i < sc->intr_count; i++) {
8794             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8795             if (sc->intr[i].resource && sc->intr[i].rid) {
8796                 bus_release_resource(sc->dev,
8797                                      SYS_RES_IRQ,
8798                                      sc->intr[i].rid,
8799                                      sc->intr[i].resource);
8800             }
8801         }
8802         pci_release_msi(sc->dev);
8803         break;
8804     default:
8805         /* nothing to do as initial allocation failed */
8806         break;
8807     }
8808 }
8809
8810 /*
8811  * This function determines and allocates the appropriate
8812  * interrupt based on system capabilites and user request.
8813  *
8814  * The user may force a particular interrupt mode, specify
8815  * the number of receive queues, specify the method for
8816  * distribuitng received frames to receive queues, or use
8817  * the default settings which will automatically select the
8818  * best supported combination.  In addition, the OS may or
8819  * may not support certain combinations of these settings.
8820  * This routine attempts to reconcile the settings requested
8821  * by the user with the capabilites available from the system
8822  * to select the optimal combination of features.
8823  *
8824  * Returns:
8825  *   0 = Success, !0 = Failure.
8826  */
8827 static int
8828 bxe_interrupt_alloc(struct bxe_softc *sc)
8829 {
8830     int msix_count = 0;
8831     int msi_count = 0;
8832     int num_requested = 0;
8833     int num_allocated = 0;
8834     int rid, i, j;
8835     int rc;
8836
8837     /* get the number of available MSI/MSI-X interrupts from the OS */
8838     if (sc->interrupt_mode > 0) {
8839         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8840             msix_count = pci_msix_count(sc->dev);
8841         }
8842
8843         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8844             msi_count = pci_msi_count(sc->dev);
8845         }
8846
8847         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8848               msi_count, msix_count);
8849     }
8850
8851     do { /* try allocating MSI-X interrupt resources (at least 2) */
8852         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8853             break;
8854         }
8855
8856         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8857             (msix_count < 2)) {
8858             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8859             break;
8860         }
8861
8862         /* ask for the necessary number of MSI-X vectors */
8863         num_requested = min((sc->num_queues + 1), msix_count);
8864
8865         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8866
8867         num_allocated = num_requested;
8868         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8869             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8870             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8871             break;
8872         }
8873
8874         if (num_allocated < 2) { /* possible? */
8875             BLOGE(sc, "MSI-X allocation less than 2!\n");
8876             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8877             pci_release_msi(sc->dev);
8878             break;
8879         }
8880
8881         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8882               num_requested, num_allocated);
8883
8884         /* best effort so use the number of vectors allocated to us */
8885         sc->intr_count = num_allocated;
8886         sc->num_queues = num_allocated - 1;
8887
8888         rid = 1; /* initial resource identifier */
8889
8890         /* allocate the MSI-X vectors */
8891         for (i = 0; i < num_allocated; i++) {
8892             sc->intr[i].rid = (rid + i);
8893
8894             if ((sc->intr[i].resource =
8895                  bus_alloc_resource_any(sc->dev,
8896                                         SYS_RES_IRQ,
8897                                         &sc->intr[i].rid,
8898                                         RF_ACTIVE)) == NULL) {
8899                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8900                       i, (rid + i));
8901
8902                 for (j = (i - 1); j >= 0; j--) {
8903                     bus_release_resource(sc->dev,
8904                                          SYS_RES_IRQ,
8905                                          sc->intr[j].rid,
8906                                          sc->intr[j].resource);
8907                 }
8908
8909                 sc->intr_count = 0;
8910                 sc->num_queues = 0;
8911                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8912                 pci_release_msi(sc->dev);
8913                 break;
8914             }
8915
8916             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
8917         }
8918     } while (0);
8919
8920     do { /* try allocating MSI vector resources (at least 2) */
8921         if (sc->interrupt_mode != INTR_MODE_MSI) {
8922             break;
8923         }
8924
8925         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
8926             (msi_count < 1)) {
8927             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8928             break;
8929         }
8930
8931         /* ask for a single MSI vector */
8932         num_requested = 1;
8933
8934         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
8935
8936         num_allocated = num_requested;
8937         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
8938             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
8939             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8940             break;
8941         }
8942
8943         if (num_allocated != 1) { /* possible? */
8944             BLOGE(sc, "MSI allocation is not 1!\n");
8945             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8946             pci_release_msi(sc->dev);
8947             break;
8948         }
8949
8950         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
8951               num_requested, num_allocated);
8952
8953         /* best effort so use the number of vectors allocated to us */
8954         sc->intr_count = num_allocated;
8955         sc->num_queues = num_allocated;
8956
8957         rid = 1; /* initial resource identifier */
8958
8959         sc->intr[0].rid = rid;
8960
8961         if ((sc->intr[0].resource =
8962              bus_alloc_resource_any(sc->dev,
8963                                     SYS_RES_IRQ,
8964                                     &sc->intr[0].rid,
8965                                     RF_ACTIVE)) == NULL) {
8966             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
8967             sc->intr_count = 0;
8968             sc->num_queues = 0;
8969             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8970             pci_release_msi(sc->dev);
8971             break;
8972         }
8973
8974         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
8975     } while (0);
8976
8977     do { /* try allocating INTx vector resources */
8978         if (sc->interrupt_mode != INTR_MODE_INTX) {
8979             break;
8980         }
8981
8982         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
8983
8984         /* only one vector for INTx */
8985         sc->intr_count = 1;
8986         sc->num_queues = 1;
8987
8988         rid = 0; /* initial resource identifier */
8989
8990         sc->intr[0].rid = rid;
8991
8992         if ((sc->intr[0].resource =
8993              bus_alloc_resource_any(sc->dev,
8994                                     SYS_RES_IRQ,
8995                                     &sc->intr[0].rid,
8996                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
8997             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
8998             sc->intr_count = 0;
8999             sc->num_queues = 0;
9000             sc->interrupt_mode = -1; /* Failed! */
9001             break;
9002         }
9003
9004         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9005     } while (0);
9006
9007     if (sc->interrupt_mode == -1) {
9008         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9009         rc = 1;
9010     } else {
9011         BLOGD(sc, DBG_LOAD,
9012               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9013               sc->interrupt_mode, sc->num_queues);
9014         rc = 0;
9015     }
9016
9017     return (rc);
9018 }
9019
9020 static void
9021 bxe_interrupt_detach(struct bxe_softc *sc)
9022 {
9023     struct bxe_fastpath *fp;
9024     int i;
9025
9026     /* release interrupt resources */
9027     for (i = 0; i < sc->intr_count; i++) {
9028         if (sc->intr[i].resource && sc->intr[i].tag) {
9029             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9030             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9031         }
9032     }
9033
9034     for (i = 0; i < sc->num_queues; i++) {
9035         fp = &sc->fp[i];
9036         if (fp->tq) {
9037             taskqueue_drain(fp->tq, &fp->tq_task);
9038             taskqueue_free(fp->tq);
9039             fp->tq = NULL;
9040         }
9041     }
9042
9043
9044     if (sc->sp_tq) {
9045         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9046         taskqueue_free(sc->sp_tq);
9047         sc->sp_tq = NULL;
9048     }
9049 }
9050
9051 /*
9052  * Enables interrupts and attach to the ISR.
9053  *
9054  * When using multiple MSI/MSI-X vectors the first vector
9055  * is used for slowpath operations while all remaining
9056  * vectors are used for fastpath operations.  If only a
9057  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9058  * ISR must look for both slowpath and fastpath completions.
9059  */
9060 static int
9061 bxe_interrupt_attach(struct bxe_softc *sc)
9062 {
9063     struct bxe_fastpath *fp;
9064     int rc = 0;
9065     int i;
9066
9067     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9068              "bxe%d_sp_tq", sc->unit);
9069     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9070     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9071                                       taskqueue_thread_enqueue,
9072                                       &sc->sp_tq);
9073     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9074                             "%s", sc->sp_tq_name);
9075
9076
9077     for (i = 0; i < sc->num_queues; i++) {
9078         fp = &sc->fp[i];
9079         snprintf(fp->tq_name, sizeof(fp->tq_name),
9080                  "bxe%d_fp%d_tq", sc->unit, i);
9081         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9082         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9083                                        taskqueue_thread_enqueue,
9084                                        &fp->tq);
9085         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9086                                 "%s", fp->tq_name);
9087     }
9088
9089     /* setup interrupt handlers */
9090     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9091         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9092
9093         /*
9094          * Setup the interrupt handler. Note that we pass the driver instance
9095          * to the interrupt handler for the slowpath.
9096          */
9097         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9098                                  (INTR_TYPE_NET | INTR_MPSAFE),
9099                                  NULL, bxe_intr_sp, sc,
9100                                  &sc->intr[0].tag)) != 0) {
9101             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9102             goto bxe_interrupt_attach_exit;
9103         }
9104
9105         bus_describe_intr(sc->dev, sc->intr[0].resource,
9106                           sc->intr[0].tag, "sp");
9107
9108         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9109
9110         /* initialize the fastpath vectors (note the first was used for sp) */
9111         for (i = 0; i < sc->num_queues; i++) {
9112             fp = &sc->fp[i];
9113             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9114
9115             /*
9116              * Setup the interrupt handler. Note that we pass the
9117              * fastpath context to the interrupt handler in this
9118              * case.
9119              */
9120             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9121                                      (INTR_TYPE_NET | INTR_MPSAFE),
9122                                      NULL, bxe_intr_fp, fp,
9123                                      &sc->intr[i + 1].tag)) != 0) {
9124                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9125                       (i + 1), rc);
9126                 goto bxe_interrupt_attach_exit;
9127             }
9128
9129             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9130                               sc->intr[i + 1].tag, "fp%02d", i);
9131
9132             /* bind the fastpath instance to a cpu */
9133             if (sc->num_queues > 1) {
9134                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9135             }
9136
9137             fp->state = BXE_FP_STATE_IRQ;
9138         }
9139     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9140         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9141
9142         /*
9143          * Setup the interrupt handler. Note that we pass the
9144          * driver instance to the interrupt handler which
9145          * will handle both the slowpath and fastpath.
9146          */
9147         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9148                                  (INTR_TYPE_NET | INTR_MPSAFE),
9149                                  NULL, bxe_intr_legacy, sc,
9150                                  &sc->intr[0].tag)) != 0) {
9151             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9152             goto bxe_interrupt_attach_exit;
9153         }
9154
9155     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9156         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9157
9158         /*
9159          * Setup the interrupt handler. Note that we pass the
9160          * driver instance to the interrupt handler which
9161          * will handle both the slowpath and fastpath.
9162          */
9163         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9164                                  (INTR_TYPE_NET | INTR_MPSAFE),
9165                                  NULL, bxe_intr_legacy, sc,
9166                                  &sc->intr[0].tag)) != 0) {
9167             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9168             goto bxe_interrupt_attach_exit;
9169         }
9170     }
9171
9172 bxe_interrupt_attach_exit:
9173
9174     return (rc);
9175 }
9176
9177 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9178 static int  bxe_init_hw_common(struct bxe_softc *sc);
9179 static int  bxe_init_hw_port(struct bxe_softc *sc);
9180 static int  bxe_init_hw_func(struct bxe_softc *sc);
9181 static void bxe_reset_common(struct bxe_softc *sc);
9182 static void bxe_reset_port(struct bxe_softc *sc);
9183 static void bxe_reset_func(struct bxe_softc *sc);
9184 static int  bxe_gunzip_init(struct bxe_softc *sc);
9185 static void bxe_gunzip_end(struct bxe_softc *sc);
9186 static int  bxe_init_firmware(struct bxe_softc *sc);
9187 static void bxe_release_firmware(struct bxe_softc *sc);
9188
9189 static struct
9190 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9191     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9192     .init_hw_cmn      = bxe_init_hw_common,
9193     .init_hw_port     = bxe_init_hw_port,
9194     .init_hw_func     = bxe_init_hw_func,
9195
9196     .reset_hw_cmn     = bxe_reset_common,
9197     .reset_hw_port    = bxe_reset_port,
9198     .reset_hw_func    = bxe_reset_func,
9199
9200     .gunzip_init      = bxe_gunzip_init,
9201     .gunzip_end       = bxe_gunzip_end,
9202
9203     .init_fw          = bxe_init_firmware,
9204     .release_fw       = bxe_release_firmware,
9205 };
9206
9207 static void
9208 bxe_init_func_obj(struct bxe_softc *sc)
9209 {
9210     sc->dmae_ready = 0;
9211
9212     ecore_init_func_obj(sc,
9213                         &sc->func_obj,
9214                         BXE_SP(sc, func_rdata),
9215                         BXE_SP_MAPPING(sc, func_rdata),
9216                         BXE_SP(sc, func_afex_rdata),
9217                         BXE_SP_MAPPING(sc, func_afex_rdata),
9218                         &bxe_func_sp_drv);
9219 }
9220
9221 static int
9222 bxe_init_hw(struct bxe_softc *sc,
9223             uint32_t         load_code)
9224 {
9225     struct ecore_func_state_params func_params = { NULL };
9226     int rc;
9227
9228     /* prepare the parameters for function state transitions */
9229     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9230
9231     func_params.f_obj = &sc->func_obj;
9232     func_params.cmd = ECORE_F_CMD_HW_INIT;
9233
9234     func_params.params.hw_init.load_phase = load_code;
9235
9236     /*
9237      * Via a plethora of function pointers, we will eventually reach
9238      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9239      */
9240     rc = ecore_func_state_change(sc, &func_params);
9241
9242     return (rc);
9243 }
9244
9245 static void
9246 bxe_fill(struct bxe_softc *sc,
9247          uint32_t         addr,
9248          int              fill,
9249          uint32_t         len)
9250 {
9251     uint32_t i;
9252
9253     if (!(len % 4) && !(addr % 4)) {
9254         for (i = 0; i < len; i += 4) {
9255             REG_WR(sc, (addr + i), fill);
9256         }
9257     } else {
9258         for (i = 0; i < len; i++) {
9259             REG_WR8(sc, (addr + i), fill);
9260         }
9261     }
9262 }
9263
9264 /* writes FP SP data to FW - data_size in dwords */
9265 static void
9266 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9267                   int              fw_sb_id,
9268                   uint32_t         *sb_data_p,
9269                   uint32_t         data_size)
9270 {
9271     int index;
9272
9273     for (index = 0; index < data_size; index++) {
9274         REG_WR(sc,
9275                (BAR_CSTRORM_INTMEM +
9276                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9277                 (sizeof(uint32_t) * index)),
9278                *(sb_data_p + index));
9279     }
9280 }
9281
9282 static void
9283 bxe_zero_fp_sb(struct bxe_softc *sc,
9284                int              fw_sb_id)
9285 {
9286     struct hc_status_block_data_e2 sb_data_e2;
9287     struct hc_status_block_data_e1x sb_data_e1x;
9288     uint32_t *sb_data_p;
9289     uint32_t data_size = 0;
9290
9291     if (!CHIP_IS_E1x(sc)) {
9292         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9293         sb_data_e2.common.state = SB_DISABLED;
9294         sb_data_e2.common.p_func.vf_valid = FALSE;
9295         sb_data_p = (uint32_t *)&sb_data_e2;
9296         data_size = (sizeof(struct hc_status_block_data_e2) /
9297                      sizeof(uint32_t));
9298     } else {
9299         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9300         sb_data_e1x.common.state = SB_DISABLED;
9301         sb_data_e1x.common.p_func.vf_valid = FALSE;
9302         sb_data_p = (uint32_t *)&sb_data_e1x;
9303         data_size = (sizeof(struct hc_status_block_data_e1x) /
9304                      sizeof(uint32_t));
9305     }
9306
9307     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9308
9309     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9310              0, CSTORM_STATUS_BLOCK_SIZE);
9311     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9312              0, CSTORM_SYNC_BLOCK_SIZE);
9313 }
9314
9315 static void
9316 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9317                   struct hc_sp_status_block_data *sp_sb_data)
9318 {
9319     int i;
9320
9321     for (i = 0;
9322          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9323          i++) {
9324         REG_WR(sc,
9325                (BAR_CSTRORM_INTMEM +
9326                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9327                 (i * sizeof(uint32_t))),
9328                *((uint32_t *)sp_sb_data + i));
9329     }
9330 }
9331
9332 static void
9333 bxe_zero_sp_sb(struct bxe_softc *sc)
9334 {
9335     struct hc_sp_status_block_data sp_sb_data;
9336
9337     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9338
9339     sp_sb_data.state           = SB_DISABLED;
9340     sp_sb_data.p_func.vf_valid = FALSE;
9341
9342     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9343
9344     bxe_fill(sc,
9345              (BAR_CSTRORM_INTMEM +
9346               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9347               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9348     bxe_fill(sc,
9349              (BAR_CSTRORM_INTMEM +
9350               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9351               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9352 }
9353
9354 static void
9355 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9356                              int                       igu_sb_id,
9357                              int                       igu_seg_id)
9358 {
9359     hc_sm->igu_sb_id      = igu_sb_id;
9360     hc_sm->igu_seg_id     = igu_seg_id;
9361     hc_sm->timer_value    = 0xFF;
9362     hc_sm->time_to_expire = 0xFFFFFFFF;
9363 }
9364
9365 static void
9366 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9367 {
9368     /* zero out state machine indices */
9369
9370     /* rx indices */
9371     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9372
9373     /* tx indices */
9374     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9375     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9376     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9377     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9378
9379     /* map indices */
9380
9381     /* rx indices */
9382     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9383         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9384
9385     /* tx indices */
9386     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9387         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9388     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9389         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9390     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9391         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9392     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9393         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9394 }
9395
9396 static void
9397 bxe_init_sb(struct bxe_softc *sc,
9398             bus_addr_t       busaddr,
9399             int              vfid,
9400             uint8_t          vf_valid,
9401             int              fw_sb_id,
9402             int              igu_sb_id)
9403 {
9404     struct hc_status_block_data_e2  sb_data_e2;
9405     struct hc_status_block_data_e1x sb_data_e1x;
9406     struct hc_status_block_sm       *hc_sm_p;
9407     uint32_t *sb_data_p;
9408     int igu_seg_id;
9409     int data_size;
9410
9411     if (CHIP_INT_MODE_IS_BC(sc)) {
9412         igu_seg_id = HC_SEG_ACCESS_NORM;
9413     } else {
9414         igu_seg_id = IGU_SEG_ACCESS_NORM;
9415     }
9416
9417     bxe_zero_fp_sb(sc, fw_sb_id);
9418
9419     if (!CHIP_IS_E1x(sc)) {
9420         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9421         sb_data_e2.common.state = SB_ENABLED;
9422         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9423         sb_data_e2.common.p_func.vf_id = vfid;
9424         sb_data_e2.common.p_func.vf_valid = vf_valid;
9425         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9426         sb_data_e2.common.same_igu_sb_1b = TRUE;
9427         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9428         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9429         hc_sm_p = sb_data_e2.common.state_machine;
9430         sb_data_p = (uint32_t *)&sb_data_e2;
9431         data_size = (sizeof(struct hc_status_block_data_e2) /
9432                      sizeof(uint32_t));
9433         bxe_map_sb_state_machines(sb_data_e2.index_data);
9434     } else {
9435         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9436         sb_data_e1x.common.state = SB_ENABLED;
9437         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9438         sb_data_e1x.common.p_func.vf_id = 0xff;
9439         sb_data_e1x.common.p_func.vf_valid = FALSE;
9440         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9441         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9442         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9443         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9444         hc_sm_p = sb_data_e1x.common.state_machine;
9445         sb_data_p = (uint32_t *)&sb_data_e1x;
9446         data_size = (sizeof(struct hc_status_block_data_e1x) /
9447                      sizeof(uint32_t));
9448         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9449     }
9450
9451     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9452     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9453
9454     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9455
9456     /* write indices to HW - PCI guarantees endianity of regpairs */
9457     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9458 }
9459
9460 static inline uint8_t
9461 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9462 {
9463     if (CHIP_IS_E1x(fp->sc)) {
9464         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9465     } else {
9466         return (fp->cl_id);
9467     }
9468 }
9469
9470 static inline uint32_t
9471 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9472                            struct bxe_fastpath *fp)
9473 {
9474     uint32_t offset = BAR_USTRORM_INTMEM;
9475
9476     if (!CHIP_IS_E1x(sc)) {
9477         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9478     } else {
9479         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9480     }
9481
9482     return (offset);
9483 }
9484
9485 static void
9486 bxe_init_eth_fp(struct bxe_softc *sc,
9487                 int              idx)
9488 {
9489     struct bxe_fastpath *fp = &sc->fp[idx];
9490     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9491     unsigned long q_type = 0;
9492     int cos;
9493
9494     fp->sc    = sc;
9495     fp->index = idx;
9496
9497     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9498     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9499
9500     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9501                     (SC_L_ID(sc) + idx) :
9502                     /* want client ID same as IGU SB ID for non-E1 */
9503                     fp->igu_sb_id;
9504     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9505
9506     /* setup sb indices */
9507     if (!CHIP_IS_E1x(sc)) {
9508         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9509         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9510     } else {
9511         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9512         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9513     }
9514
9515     /* init shortcut */
9516     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9517
9518     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9519
9520     /*
9521      * XXX If multiple CoS is ever supported then each fastpath structure
9522      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9523      */
9524     for (cos = 0; cos < sc->max_cos; cos++) {
9525         cids[cos] = idx;
9526     }
9527     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9528
9529     /* nothing more for a VF to do */
9530     if (IS_VF(sc)) {
9531         return;
9532     }
9533
9534     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9535                 fp->fw_sb_id, fp->igu_sb_id);
9536
9537     bxe_update_fp_sb_idx(fp);
9538
9539     /* Configure Queue State object */
9540     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9541     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9542
9543     ecore_init_queue_obj(sc,
9544                          &sc->sp_objs[idx].q_obj,
9545                          fp->cl_id,
9546                          cids,
9547                          sc->max_cos,
9548                          SC_FUNC(sc),
9549                          BXE_SP(sc, q_rdata),
9550                          BXE_SP_MAPPING(sc, q_rdata),
9551                          q_type);
9552
9553     /* configure classification DBs */
9554     ecore_init_mac_obj(sc,
9555                        &sc->sp_objs[idx].mac_obj,
9556                        fp->cl_id,
9557                        idx,
9558                        SC_FUNC(sc),
9559                        BXE_SP(sc, mac_rdata),
9560                        BXE_SP_MAPPING(sc, mac_rdata),
9561                        ECORE_FILTER_MAC_PENDING,
9562                        &sc->sp_state,
9563                        ECORE_OBJ_TYPE_RX_TX,
9564                        &sc->macs_pool);
9565
9566     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9567           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9568 }
9569
9570 static inline void
9571 bxe_update_rx_prod(struct bxe_softc    *sc,
9572                    struct bxe_fastpath *fp,
9573                    uint16_t            rx_bd_prod,
9574                    uint16_t            rx_cq_prod,
9575                    uint16_t            rx_sge_prod)
9576 {
9577     struct ustorm_eth_rx_producers rx_prods = { 0 };
9578     uint32_t i;
9579
9580     /* update producers */
9581     rx_prods.bd_prod  = rx_bd_prod;
9582     rx_prods.cqe_prod = rx_cq_prod;
9583     rx_prods.sge_prod = rx_sge_prod;
9584
9585     /*
9586      * Make sure that the BD and SGE data is updated before updating the
9587      * producers since FW might read the BD/SGE right after the producer
9588      * is updated.
9589      * This is only applicable for weak-ordered memory model archs such
9590      * as IA-64. The following barrier is also mandatory since FW will
9591      * assumes BDs must have buffers.
9592      */
9593     wmb();
9594
9595     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9596         REG_WR(sc,
9597                (fp->ustorm_rx_prods_offset + (i * 4)),
9598                ((uint32_t *)&rx_prods)[i]);
9599     }
9600
9601     wmb(); /* keep prod updates ordered */
9602
9603     BLOGD(sc, DBG_RX,
9604           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9605           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9606 }
9607
9608 static void
9609 bxe_init_rx_rings(struct bxe_softc *sc)
9610 {
9611     struct bxe_fastpath *fp;
9612     int i;
9613
9614     for (i = 0; i < sc->num_queues; i++) {
9615         fp = &sc->fp[i];
9616
9617         fp->rx_bd_cons = 0;
9618
9619         /*
9620          * Activate the BD ring...
9621          * Warning, this will generate an interrupt (to the TSTORM)
9622          * so this can only be done after the chip is initialized
9623          */
9624         bxe_update_rx_prod(sc, fp,
9625                            fp->rx_bd_prod,
9626                            fp->rx_cq_prod,
9627                            fp->rx_sge_prod);
9628
9629         if (i != 0) {
9630             continue;
9631         }
9632
9633         if (CHIP_IS_E1(sc)) {
9634             REG_WR(sc,
9635                    (BAR_USTRORM_INTMEM +
9636                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9637                    U64_LO(fp->rcq_dma.paddr));
9638             REG_WR(sc,
9639                    (BAR_USTRORM_INTMEM +
9640                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9641                    U64_HI(fp->rcq_dma.paddr));
9642         }
9643     }
9644 }
9645
9646 static void
9647 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9648 {
9649     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9650     fp->tx_db.data.zero_fill1 = 0;
9651     fp->tx_db.data.prod = 0;
9652
9653     fp->tx_pkt_prod = 0;
9654     fp->tx_pkt_cons = 0;
9655     fp->tx_bd_prod = 0;
9656     fp->tx_bd_cons = 0;
9657     fp->eth_q_stats.tx_pkts = 0;
9658 }
9659
9660 static inline void
9661 bxe_init_tx_rings(struct bxe_softc *sc)
9662 {
9663     int i;
9664
9665     for (i = 0; i < sc->num_queues; i++) {
9666         bxe_init_tx_ring_one(&sc->fp[i]);
9667     }
9668 }
9669
9670 static void
9671 bxe_init_def_sb(struct bxe_softc *sc)
9672 {
9673     struct host_sp_status_block *def_sb = sc->def_sb;
9674     bus_addr_t mapping = sc->def_sb_dma.paddr;
9675     int igu_sp_sb_index;
9676     int igu_seg_id;
9677     int port = SC_PORT(sc);
9678     int func = SC_FUNC(sc);
9679     int reg_offset, reg_offset_en5;
9680     uint64_t section;
9681     int index, sindex;
9682     struct hc_sp_status_block_data sp_sb_data;
9683
9684     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9685
9686     if (CHIP_INT_MODE_IS_BC(sc)) {
9687         igu_sp_sb_index = DEF_SB_IGU_ID;
9688         igu_seg_id = HC_SEG_ACCESS_DEF;
9689     } else {
9690         igu_sp_sb_index = sc->igu_dsb_id;
9691         igu_seg_id = IGU_SEG_ACCESS_DEF;
9692     }
9693
9694     /* attentions */
9695     section = ((uint64_t)mapping +
9696                offsetof(struct host_sp_status_block, atten_status_block));
9697     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9698     sc->attn_state = 0;
9699
9700     reg_offset = (port) ?
9701                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9702                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9703     reg_offset_en5 = (port) ?
9704                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9705                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9706
9707     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9708         /* take care of sig[0]..sig[4] */
9709         for (sindex = 0; sindex < 4; sindex++) {
9710             sc->attn_group[index].sig[sindex] =
9711                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9712         }
9713
9714         if (!CHIP_IS_E1x(sc)) {
9715             /*
9716              * enable5 is separate from the rest of the registers,
9717              * and the address skip is 4 and not 16 between the
9718              * different groups
9719              */
9720             sc->attn_group[index].sig[4] =
9721                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9722         } else {
9723             sc->attn_group[index].sig[4] = 0;
9724         }
9725     }
9726
9727     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9728         reg_offset = (port) ?
9729                          HC_REG_ATTN_MSG1_ADDR_L :
9730                          HC_REG_ATTN_MSG0_ADDR_L;
9731         REG_WR(sc, reg_offset, U64_LO(section));
9732         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9733     } else if (!CHIP_IS_E1x(sc)) {
9734         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9735         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9736     }
9737
9738     section = ((uint64_t)mapping +
9739                offsetof(struct host_sp_status_block, sp_sb));
9740
9741     bxe_zero_sp_sb(sc);
9742
9743     /* PCI guarantees endianity of regpair */
9744     sp_sb_data.state           = SB_ENABLED;
9745     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9746     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9747     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9748     sp_sb_data.igu_seg_id      = igu_seg_id;
9749     sp_sb_data.p_func.pf_id    = func;
9750     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9751     sp_sb_data.p_func.vf_id    = 0xff;
9752
9753     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9754
9755     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9756 }
9757
9758 static void
9759 bxe_init_sp_ring(struct bxe_softc *sc)
9760 {
9761     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9762     sc->spq_prod_idx = 0;
9763     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9764     sc->spq_prod_bd = sc->spq;
9765     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9766 }
9767
9768 static void
9769 bxe_init_eq_ring(struct bxe_softc *sc)
9770 {
9771     union event_ring_elem *elem;
9772     int i;
9773
9774     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9775         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9776
9777         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9778                                                  BCM_PAGE_SIZE *
9779                                                  (i % NUM_EQ_PAGES)));
9780         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9781                                                  BCM_PAGE_SIZE *
9782                                                  (i % NUM_EQ_PAGES)));
9783     }
9784
9785     sc->eq_cons    = 0;
9786     sc->eq_prod    = NUM_EQ_DESC;
9787     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9788
9789     atomic_store_rel_long(&sc->eq_spq_left,
9790                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9791                                NUM_EQ_DESC) - 1));
9792 }
9793
9794 static void
9795 bxe_init_internal_common(struct bxe_softc *sc)
9796 {
9797     int i;
9798
9799     /*
9800      * Zero this manually as its initialization is currently missing
9801      * in the initTool.
9802      */
9803     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9804         REG_WR(sc,
9805                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9806                0);
9807     }
9808
9809     if (!CHIP_IS_E1x(sc)) {
9810         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9811                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9812     }
9813 }
9814
9815 static void
9816 bxe_init_internal(struct bxe_softc *sc,
9817                   uint32_t         load_code)
9818 {
9819     switch (load_code) {
9820     case FW_MSG_CODE_DRV_LOAD_COMMON:
9821     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9822         bxe_init_internal_common(sc);
9823         /* no break */
9824
9825     case FW_MSG_CODE_DRV_LOAD_PORT:
9826         /* nothing to do */
9827         /* no break */
9828
9829     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9830         /* internal memory per function is initialized inside bxe_pf_init */
9831         break;
9832
9833     default:
9834         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9835         break;
9836     }
9837 }
9838
9839 static void
9840 storm_memset_func_cfg(struct bxe_softc                         *sc,
9841                       struct tstorm_eth_function_common_config *tcfg,
9842                       uint16_t                                  abs_fid)
9843 {
9844     uint32_t addr;
9845     size_t size;
9846
9847     addr = (BAR_TSTRORM_INTMEM +
9848             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9849     size = sizeof(struct tstorm_eth_function_common_config);
9850     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9851 }
9852
9853 static void
9854 bxe_func_init(struct bxe_softc            *sc,
9855               struct bxe_func_init_params *p)
9856 {
9857     struct tstorm_eth_function_common_config tcfg = { 0 };
9858
9859     if (CHIP_IS_E1x(sc)) {
9860         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9861     }
9862
9863     /* Enable the function in the FW */
9864     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9865     storm_memset_func_en(sc, p->func_id, 1);
9866
9867     /* spq */
9868     if (p->func_flgs & FUNC_FLG_SPQ) {
9869         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9870         REG_WR(sc,
9871                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9872                p->spq_prod);
9873     }
9874 }
9875
9876 /*
9877  * Calculates the sum of vn_min_rates.
9878  * It's needed for further normalizing of the min_rates.
9879  * Returns:
9880  *   sum of vn_min_rates.
9881  *     or
9882  *   0 - if all the min_rates are 0.
9883  * In the later case fainess algorithm should be deactivated.
9884  * If all min rates are not zero then those that are zeroes will be set to 1.
9885  */
9886 static void
9887 bxe_calc_vn_min(struct bxe_softc       *sc,
9888                 struct cmng_init_input *input)
9889 {
9890     uint32_t vn_cfg;
9891     uint32_t vn_min_rate;
9892     int all_zero = 1;
9893     int vn;
9894
9895     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9896         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9897         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9898                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9899
9900         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9901             /* skip hidden VNs */
9902             vn_min_rate = 0;
9903         } else if (!vn_min_rate) {
9904             /* If min rate is zero - set it to 100 */
9905             vn_min_rate = DEF_MIN_RATE;
9906         } else {
9907             all_zero = 0;
9908         }
9909
9910         input->vnic_min_rate[vn] = vn_min_rate;
9911     }
9912
9913     /* if ETS or all min rates are zeros - disable fairness */
9914     if (BXE_IS_ETS_ENABLED(sc)) {
9915         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9916         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
9917     } else if (all_zero) {
9918         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9919         BLOGD(sc, DBG_LOAD,
9920               "Fariness disabled (all MIN values are zeroes)\n");
9921     } else {
9922         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9923     }
9924 }
9925
9926 static inline uint16_t
9927 bxe_extract_max_cfg(struct bxe_softc *sc,
9928                     uint32_t         mf_cfg)
9929 {
9930     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
9931                         FUNC_MF_CFG_MAX_BW_SHIFT);
9932
9933     if (!max_cfg) {
9934         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
9935         max_cfg = 100;
9936     }
9937
9938     return (max_cfg);
9939 }
9940
9941 static void
9942 bxe_calc_vn_max(struct bxe_softc       *sc,
9943                 int                    vn,
9944                 struct cmng_init_input *input)
9945 {
9946     uint16_t vn_max_rate;
9947     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9948     uint32_t max_cfg;
9949
9950     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9951         vn_max_rate = 0;
9952     } else {
9953         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
9954
9955         if (IS_MF_SI(sc)) {
9956             /* max_cfg in percents of linkspeed */
9957             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
9958         } else { /* SD modes */
9959             /* max_cfg is absolute in 100Mb units */
9960             vn_max_rate = (max_cfg * 100);
9961         }
9962     }
9963
9964     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
9965
9966     input->vnic_max_rate[vn] = vn_max_rate;
9967 }
9968
9969 static void
9970 bxe_cmng_fns_init(struct bxe_softc *sc,
9971                   uint8_t          read_cfg,
9972                   uint8_t          cmng_type)
9973 {
9974     struct cmng_init_input input;
9975     int vn;
9976
9977     memset(&input, 0, sizeof(struct cmng_init_input));
9978
9979     input.port_rate = sc->link_vars.line_speed;
9980
9981     if (cmng_type == CMNG_FNS_MINMAX) {
9982         /* read mf conf from shmem */
9983         if (read_cfg) {
9984             bxe_read_mf_cfg(sc);
9985         }
9986
9987         /* get VN min rate and enable fairness if not 0 */
9988         bxe_calc_vn_min(sc, &input);
9989
9990         /* get VN max rate */
9991         if (sc->port.pmf) {
9992             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9993                 bxe_calc_vn_max(sc, vn, &input);
9994             }
9995         }
9996
9997         /* always enable rate shaping and fairness */
9998         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
9999
10000         ecore_init_cmng(&input, &sc->cmng);
10001         return;
10002     }
10003
10004     /* rate shaping and fairness are disabled */
10005     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10006 }
10007
10008 static int
10009 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10010 {
10011     if (CHIP_REV_IS_SLOW(sc)) {
10012         return (CMNG_FNS_NONE);
10013     }
10014
10015     if (IS_MF(sc)) {
10016         return (CMNG_FNS_MINMAX);
10017     }
10018
10019     return (CMNG_FNS_NONE);
10020 }
10021
10022 static void
10023 storm_memset_cmng(struct bxe_softc *sc,
10024                   struct cmng_init *cmng,
10025                   uint8_t          port)
10026 {
10027     int vn;
10028     int func;
10029     uint32_t addr;
10030     size_t size;
10031
10032     addr = (BAR_XSTRORM_INTMEM +
10033             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10034     size = sizeof(struct cmng_struct_per_port);
10035     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10036
10037     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10038         func = func_by_vn(sc, vn);
10039
10040         addr = (BAR_XSTRORM_INTMEM +
10041                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10042         size = sizeof(struct rate_shaping_vars_per_vn);
10043         ecore_storm_memset_struct(sc, addr, size,
10044                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10045
10046         addr = (BAR_XSTRORM_INTMEM +
10047                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10048         size = sizeof(struct fairness_vars_per_vn);
10049         ecore_storm_memset_struct(sc, addr, size,
10050                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10051     }
10052 }
10053
10054 static void
10055 bxe_pf_init(struct bxe_softc *sc)
10056 {
10057     struct bxe_func_init_params func_init = { 0 };
10058     struct event_ring_data eq_data = { { 0 } };
10059     uint16_t flags;
10060
10061     if (!CHIP_IS_E1x(sc)) {
10062         /* reset IGU PF statistics: MSIX + ATTN */
10063         /* PF */
10064         REG_WR(sc,
10065                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10066                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10067                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10068                0);
10069         /* ATTN */
10070         REG_WR(sc,
10071                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10072                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10073                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10074                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10075                0);
10076     }
10077
10078     /* function setup flags */
10079     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10080
10081     /*
10082      * This flag is relevant for E1x only.
10083      * E2 doesn't have a TPA configuration in a function level.
10084      */
10085     flags |= (if_getcapenable(sc->ifp) & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10086
10087     func_init.func_flgs = flags;
10088     func_init.pf_id     = SC_FUNC(sc);
10089     func_init.func_id   = SC_FUNC(sc);
10090     func_init.spq_map   = sc->spq_dma.paddr;
10091     func_init.spq_prod  = sc->spq_prod_idx;
10092
10093     bxe_func_init(sc, &func_init);
10094
10095     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10096
10097     /*
10098      * Congestion management values depend on the link rate.
10099      * There is no active link so initial link rate is set to 10Gbps.
10100      * When the link comes up the congestion management values are
10101      * re-calculated according to the actual link rate.
10102      */
10103     sc->link_vars.line_speed = SPEED_10000;
10104     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10105
10106     /* Only the PMF sets the HW */
10107     if (sc->port.pmf) {
10108         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10109     }
10110
10111     /* init Event Queue - PCI bus guarantees correct endainity */
10112     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10113     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10114     eq_data.producer     = sc->eq_prod;
10115     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10116     eq_data.sb_id        = DEF_SB_ID;
10117     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10118 }
10119
10120 static void
10121 bxe_hc_int_enable(struct bxe_softc *sc)
10122 {
10123     int port = SC_PORT(sc);
10124     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10125     uint32_t val = REG_RD(sc, addr);
10126     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10127     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10128                            (sc->intr_count == 1)) ? TRUE : FALSE;
10129     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10130
10131     if (msix) {
10132         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10133                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10134         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10135                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10136         if (single_msix) {
10137             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10138         }
10139     } else if (msi) {
10140         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10141         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10142                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10143                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10144     } else {
10145         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10146                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10147                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10148                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10149
10150         if (!CHIP_IS_E1(sc)) {
10151             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10152                   val, port, addr);
10153
10154             REG_WR(sc, addr, val);
10155
10156             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10157         }
10158     }
10159
10160     if (CHIP_IS_E1(sc)) {
10161         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10162     }
10163
10164     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10165           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10166
10167     REG_WR(sc, addr, val);
10168
10169     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10170     mb();
10171
10172     if (!CHIP_IS_E1(sc)) {
10173         /* init leading/trailing edge */
10174         if (IS_MF(sc)) {
10175             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10176             if (sc->port.pmf) {
10177                 /* enable nig and gpio3 attention */
10178                 val |= 0x1100;
10179             }
10180         } else {
10181             val = 0xffff;
10182         }
10183
10184         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10185         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10186     }
10187
10188     /* make sure that interrupts are indeed enabled from here on */
10189     mb();
10190 }
10191
10192 static void
10193 bxe_igu_int_enable(struct bxe_softc *sc)
10194 {
10195     uint32_t val;
10196     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10197     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10198                            (sc->intr_count == 1)) ? TRUE : FALSE;
10199     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10200
10201     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10202
10203     if (msix) {
10204         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10205                  IGU_PF_CONF_SINGLE_ISR_EN);
10206         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10207                 IGU_PF_CONF_ATTN_BIT_EN);
10208         if (single_msix) {
10209             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10210         }
10211     } else if (msi) {
10212         val &= ~IGU_PF_CONF_INT_LINE_EN;
10213         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10214                 IGU_PF_CONF_ATTN_BIT_EN |
10215                 IGU_PF_CONF_SINGLE_ISR_EN);
10216     } else {
10217         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10218         val |= (IGU_PF_CONF_INT_LINE_EN |
10219                 IGU_PF_CONF_ATTN_BIT_EN |
10220                 IGU_PF_CONF_SINGLE_ISR_EN);
10221     }
10222
10223     /* clean previous status - need to configure igu prior to ack*/
10224     if ((!msix) || single_msix) {
10225         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10226         bxe_ack_int(sc);
10227     }
10228
10229     val |= IGU_PF_CONF_FUNC_EN;
10230
10231     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10232           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10233
10234     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10235
10236     mb();
10237
10238     /* init leading/trailing edge */
10239     if (IS_MF(sc)) {
10240         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10241         if (sc->port.pmf) {
10242             /* enable nig and gpio3 attention */
10243             val |= 0x1100;
10244         }
10245     } else {
10246         val = 0xffff;
10247     }
10248
10249     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10250     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10251
10252     /* make sure that interrupts are indeed enabled from here on */
10253     mb();
10254 }
10255
10256 static void
10257 bxe_int_enable(struct bxe_softc *sc)
10258 {
10259     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10260         bxe_hc_int_enable(sc);
10261     } else {
10262         bxe_igu_int_enable(sc);
10263     }
10264 }
10265
10266 static void
10267 bxe_hc_int_disable(struct bxe_softc *sc)
10268 {
10269     int port = SC_PORT(sc);
10270     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10271     uint32_t val = REG_RD(sc, addr);
10272
10273     /*
10274      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10275      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10276      * block
10277      */
10278     if (CHIP_IS_E1(sc)) {
10279         /*
10280          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10281          * to prevent from HC sending interrupts after we exit the function
10282          */
10283         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10284
10285         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10286                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10287                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10288     } else {
10289         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10290                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10291                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10292                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10293     }
10294
10295     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10296
10297     /* flush all outstanding writes */
10298     mb();
10299
10300     REG_WR(sc, addr, val);
10301     if (REG_RD(sc, addr) != val) {
10302         BLOGE(sc, "proper val not read from HC IGU!\n");
10303     }
10304 }
10305
10306 static void
10307 bxe_igu_int_disable(struct bxe_softc *sc)
10308 {
10309     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10310
10311     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10312              IGU_PF_CONF_INT_LINE_EN |
10313              IGU_PF_CONF_ATTN_BIT_EN);
10314
10315     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10316
10317     /* flush all outstanding writes */
10318     mb();
10319
10320     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10321     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10322         BLOGE(sc, "proper val not read from IGU!\n");
10323     }
10324 }
10325
10326 static void
10327 bxe_int_disable(struct bxe_softc *sc)
10328 {
10329     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10330         bxe_hc_int_disable(sc);
10331     } else {
10332         bxe_igu_int_disable(sc);
10333     }
10334 }
10335
10336 static void
10337 bxe_nic_init(struct bxe_softc *sc,
10338              int              load_code)
10339 {
10340     int i;
10341
10342     for (i = 0; i < sc->num_queues; i++) {
10343         bxe_init_eth_fp(sc, i);
10344     }
10345
10346     rmb(); /* ensure status block indices were read */
10347
10348     bxe_init_rx_rings(sc);
10349     bxe_init_tx_rings(sc);
10350
10351     if (IS_VF(sc)) {
10352         return;
10353     }
10354
10355     /* initialize MOD_ABS interrupts */
10356     elink_init_mod_abs_int(sc, &sc->link_vars,
10357                            sc->devinfo.chip_id,
10358                            sc->devinfo.shmem_base,
10359                            sc->devinfo.shmem2_base,
10360                            SC_PORT(sc));
10361
10362     bxe_init_def_sb(sc);
10363     bxe_update_dsb_idx(sc);
10364     bxe_init_sp_ring(sc);
10365     bxe_init_eq_ring(sc);
10366     bxe_init_internal(sc, load_code);
10367     bxe_pf_init(sc);
10368     bxe_stats_init(sc);
10369
10370     /* flush all before enabling interrupts */
10371     mb();
10372
10373     bxe_int_enable(sc);
10374
10375     /* check for SPIO5 */
10376     bxe_attn_int_deasserted0(sc,
10377                              REG_RD(sc,
10378                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10379                                      SC_PORT(sc)*4)) &
10380                              AEU_INPUTS_ATTN_BITS_SPIO5);
10381 }
10382
10383 static inline void
10384 bxe_init_objs(struct bxe_softc *sc)
10385 {
10386     /* mcast rules must be added to tx if tx switching is enabled */
10387     ecore_obj_type o_type =
10388         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10389                                          ECORE_OBJ_TYPE_RX;
10390
10391     /* RX_MODE controlling object */
10392     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10393
10394     /* multicast configuration controlling object */
10395     ecore_init_mcast_obj(sc,
10396                          &sc->mcast_obj,
10397                          sc->fp[0].cl_id,
10398                          sc->fp[0].index,
10399                          SC_FUNC(sc),
10400                          SC_FUNC(sc),
10401                          BXE_SP(sc, mcast_rdata),
10402                          BXE_SP_MAPPING(sc, mcast_rdata),
10403                          ECORE_FILTER_MCAST_PENDING,
10404                          &sc->sp_state,
10405                          o_type);
10406
10407     /* Setup CAM credit pools */
10408     ecore_init_mac_credit_pool(sc,
10409                                &sc->macs_pool,
10410                                SC_FUNC(sc),
10411                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10412                                                  VNICS_PER_PATH(sc));
10413
10414     ecore_init_vlan_credit_pool(sc,
10415                                 &sc->vlans_pool,
10416                                 SC_ABS_FUNC(sc) >> 1,
10417                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10418                                                   VNICS_PER_PATH(sc));
10419
10420     /* RSS configuration object */
10421     ecore_init_rss_config_obj(sc,
10422                               &sc->rss_conf_obj,
10423                               sc->fp[0].cl_id,
10424                               sc->fp[0].index,
10425                               SC_FUNC(sc),
10426                               SC_FUNC(sc),
10427                               BXE_SP(sc, rss_rdata),
10428                               BXE_SP_MAPPING(sc, rss_rdata),
10429                               ECORE_FILTER_RSS_CONF_PENDING,
10430                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10431 }
10432
10433 /*
10434  * Initialize the function. This must be called before sending CLIENT_SETUP
10435  * for the first client.
10436  */
10437 static inline int
10438 bxe_func_start(struct bxe_softc *sc)
10439 {
10440     struct ecore_func_state_params func_params = { NULL };
10441     struct ecore_func_start_params *start_params = &func_params.params.start;
10442
10443     /* Prepare parameters for function state transitions */
10444     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10445
10446     func_params.f_obj = &sc->func_obj;
10447     func_params.cmd = ECORE_F_CMD_START;
10448
10449     /* Function parameters */
10450     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10451     start_params->sd_vlan_tag = OVLAN(sc);
10452
10453     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10454         start_params->network_cos_mode = STATIC_COS;
10455     } else { /* CHIP_IS_E1X */
10456         start_params->network_cos_mode = FW_WRR;
10457     }
10458
10459     //start_params->gre_tunnel_mode = 0;
10460     //start_params->gre_tunnel_rss  = 0;
10461
10462     return (ecore_func_state_change(sc, &func_params));
10463 }
10464
10465 static int
10466 bxe_set_power_state(struct bxe_softc *sc,
10467                     uint8_t          state)
10468 {
10469     uint16_t pmcsr;
10470
10471     /* If there is no power capability, silently succeed */
10472     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10473         BLOGW(sc, "No power capability\n");
10474         return (0);
10475     }
10476
10477     pmcsr = pci_read_config(sc->dev,
10478                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10479                             2);
10480
10481     switch (state) {
10482     case PCI_PM_D0:
10483         pci_write_config(sc->dev,
10484                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10485                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10486
10487         if (pmcsr & PCIM_PSTAT_DMASK) {
10488             /* delay required during transition out of D3hot */
10489             DELAY(20000);
10490         }
10491
10492         break;
10493
10494     case PCI_PM_D3hot:
10495         /* XXX if there are other clients above don't shut down the power */
10496
10497         /* don't shut down the power for emulation and FPGA */
10498         if (CHIP_REV_IS_SLOW(sc)) {
10499             return (0);
10500         }
10501
10502         pmcsr &= ~PCIM_PSTAT_DMASK;
10503         pmcsr |= PCIM_PSTAT_D3;
10504
10505         if (sc->wol) {
10506             pmcsr |= PCIM_PSTAT_PMEENABLE;
10507         }
10508
10509         pci_write_config(sc->dev,
10510                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10511                          pmcsr, 4);
10512
10513         /*
10514          * No more memory access after this point until device is brought back
10515          * to D0 state.
10516          */
10517         break;
10518
10519     default:
10520         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10521             state, pmcsr);
10522         return (-1);
10523     }
10524
10525     return (0);
10526 }
10527
10528
10529 /* return true if succeeded to acquire the lock */
10530 static uint8_t
10531 bxe_trylock_hw_lock(struct bxe_softc *sc,
10532                     uint32_t         resource)
10533 {
10534     uint32_t lock_status;
10535     uint32_t resource_bit = (1 << resource);
10536     int func = SC_FUNC(sc);
10537     uint32_t hw_lock_control_reg;
10538
10539     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10540
10541     /* Validating that the resource is within range */
10542     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10543         BLOGD(sc, DBG_LOAD,
10544               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10545               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10546         return (FALSE);
10547     }
10548
10549     if (func <= 5) {
10550         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10551     } else {
10552         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10553     }
10554
10555     /* try to acquire the lock */
10556     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10557     lock_status = REG_RD(sc, hw_lock_control_reg);
10558     if (lock_status & resource_bit) {
10559         return (TRUE);
10560     }
10561
10562     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10563         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10564         lock_status, resource_bit);
10565
10566     return (FALSE);
10567 }
10568
10569 /*
10570  * Get the recovery leader resource id according to the engine this function
10571  * belongs to. Currently only only 2 engines is supported.
10572  */
10573 static int
10574 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10575 {
10576     if (SC_PATH(sc)) {
10577         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10578     } else {
10579         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10580     }
10581 }
10582
10583 /* try to acquire a leader lock for current engine */
10584 static uint8_t
10585 bxe_trylock_leader_lock(struct bxe_softc *sc)
10586 {
10587     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10588 }
10589
10590 static int
10591 bxe_release_leader_lock(struct bxe_softc *sc)
10592 {
10593     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10594 }
10595
10596 /* close gates #2, #3 and #4 */
10597 static void
10598 bxe_set_234_gates(struct bxe_softc *sc,
10599                   uint8_t          close)
10600 {
10601     uint32_t val;
10602
10603     /* gates #2 and #4a are closed/opened for "not E1" only */
10604     if (!CHIP_IS_E1(sc)) {
10605         /* #4 */
10606         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10607         /* #2 */
10608         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10609     }
10610
10611     /* #3 */
10612     if (CHIP_IS_E1x(sc)) {
10613         /* prevent interrupts from HC on both ports */
10614         val = REG_RD(sc, HC_REG_CONFIG_1);
10615         REG_WR(sc, HC_REG_CONFIG_1,
10616                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10617                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10618
10619         val = REG_RD(sc, HC_REG_CONFIG_0);
10620         REG_WR(sc, HC_REG_CONFIG_0,
10621                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10622                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10623     } else {
10624         /* Prevent incoming interrupts in IGU */
10625         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10626
10627         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10628                (!close) ?
10629                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10630                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10631     }
10632
10633     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10634           close ? "closing" : "opening");
10635
10636     wmb();
10637 }
10638
10639 /* poll for pending writes bit, it should get cleared in no more than 1s */
10640 static int
10641 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10642 {
10643     uint32_t cnt = 1000;
10644     uint32_t pend_bits = 0;
10645
10646     do {
10647         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10648
10649         if (pend_bits == 0) {
10650             break;
10651         }
10652
10653         DELAY(1000);
10654     } while (--cnt > 0);
10655
10656     if (cnt == 0) {
10657         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10658         return (-1);
10659     }
10660
10661     return (0);
10662 }
10663
10664 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10665
10666 static void
10667 bxe_clp_reset_prep(struct bxe_softc *sc,
10668                    uint32_t         *magic_val)
10669 {
10670     /* Do some magic... */
10671     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10672     *magic_val = val & SHARED_MF_CLP_MAGIC;
10673     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10674 }
10675
10676 /* restore the value of the 'magic' bit */
10677 static void
10678 bxe_clp_reset_done(struct bxe_softc *sc,
10679                    uint32_t         magic_val)
10680 {
10681     /* Restore the 'magic' bit value... */
10682     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10683     MFCFG_WR(sc, shared_mf_config.clp_mb,
10684               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10685 }
10686
10687 /* prepare for MCP reset, takes care of CLP configurations */
10688 static void
10689 bxe_reset_mcp_prep(struct bxe_softc *sc,
10690                    uint32_t         *magic_val)
10691 {
10692     uint32_t shmem;
10693     uint32_t validity_offset;
10694
10695     /* set `magic' bit in order to save MF config */
10696     if (!CHIP_IS_E1(sc)) {
10697         bxe_clp_reset_prep(sc, magic_val);
10698     }
10699
10700     /* get shmem offset */
10701     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10702     validity_offset =
10703         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10704
10705     /* Clear validity map flags */
10706     if (shmem > 0) {
10707         REG_WR(sc, shmem + validity_offset, 0);
10708     }
10709 }
10710
10711 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10712 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10713
10714 static void
10715 bxe_mcp_wait_one(struct bxe_softc *sc)
10716 {
10717     /* special handling for emulation and FPGA (10 times longer) */
10718     if (CHIP_REV_IS_SLOW(sc)) {
10719         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10720     } else {
10721         DELAY((MCP_ONE_TIMEOUT) * 1000);
10722     }
10723 }
10724
10725 /* initialize shmem_base and waits for validity signature to appear */
10726 static int
10727 bxe_init_shmem(struct bxe_softc *sc)
10728 {
10729     int cnt = 0;
10730     uint32_t val = 0;
10731
10732     do {
10733         sc->devinfo.shmem_base     =
10734         sc->link_params.shmem_base =
10735             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10736
10737         if (sc->devinfo.shmem_base) {
10738             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10739             if (val & SHR_MEM_VALIDITY_MB)
10740                 return (0);
10741         }
10742
10743         bxe_mcp_wait_one(sc);
10744
10745     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10746
10747     BLOGE(sc, "BAD MCP validity signature\n");
10748
10749     return (-1);
10750 }
10751
10752 static int
10753 bxe_reset_mcp_comp(struct bxe_softc *sc,
10754                    uint32_t         magic_val)
10755 {
10756     int rc = bxe_init_shmem(sc);
10757
10758     /* Restore the `magic' bit value */
10759     if (!CHIP_IS_E1(sc)) {
10760         bxe_clp_reset_done(sc, magic_val);
10761     }
10762
10763     return (rc);
10764 }
10765
10766 static void
10767 bxe_pxp_prep(struct bxe_softc *sc)
10768 {
10769     if (!CHIP_IS_E1(sc)) {
10770         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10771         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10772         wmb();
10773     }
10774 }
10775
10776 /*
10777  * Reset the whole chip except for:
10778  *      - PCIE core
10779  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10780  *      - IGU
10781  *      - MISC (including AEU)
10782  *      - GRC
10783  *      - RBCN, RBCP
10784  */
10785 static void
10786 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10787                             uint8_t          global)
10788 {
10789     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10790     uint32_t global_bits2, stay_reset2;
10791
10792     /*
10793      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10794      * (per chip) blocks.
10795      */
10796     global_bits2 =
10797         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10798         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10799
10800     /*
10801      * Don't reset the following blocks.
10802      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10803      *            reset, as in 4 port device they might still be owned
10804      *            by the MCP (there is only one leader per path).
10805      */
10806     not_reset_mask1 =
10807         MISC_REGISTERS_RESET_REG_1_RST_HC |
10808         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10809         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10810
10811     not_reset_mask2 =
10812         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10813         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10814         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10815         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10816         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10817         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10818         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10819         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10820         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10821         MISC_REGISTERS_RESET_REG_2_PGLC |
10822         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10823         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10824         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10825         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10826         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10827         MISC_REGISTERS_RESET_REG_2_UMAC1;
10828
10829     /*
10830      * Keep the following blocks in reset:
10831      *  - all xxMACs are handled by the elink code.
10832      */
10833     stay_reset2 =
10834         MISC_REGISTERS_RESET_REG_2_XMAC |
10835         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10836
10837     /* Full reset masks according to the chip */
10838     reset_mask1 = 0xffffffff;
10839
10840     if (CHIP_IS_E1(sc))
10841         reset_mask2 = 0xffff;
10842     else if (CHIP_IS_E1H(sc))
10843         reset_mask2 = 0x1ffff;
10844     else if (CHIP_IS_E2(sc))
10845         reset_mask2 = 0xfffff;
10846     else /* CHIP_IS_E3 */
10847         reset_mask2 = 0x3ffffff;
10848
10849     /* Don't reset global blocks unless we need to */
10850     if (!global)
10851         reset_mask2 &= ~global_bits2;
10852
10853     /*
10854      * In case of attention in the QM, we need to reset PXP
10855      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10856      * because otherwise QM reset would release 'close the gates' shortly
10857      * before resetting the PXP, then the PSWRQ would send a write
10858      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10859      * read the payload data from PSWWR, but PSWWR would not
10860      * respond. The write queue in PGLUE would stuck, dmae commands
10861      * would not return. Therefore it's important to reset the second
10862      * reset register (containing the
10863      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10864      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10865      * bit).
10866      */
10867     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10868            reset_mask2 & (~not_reset_mask2));
10869
10870     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10871            reset_mask1 & (~not_reset_mask1));
10872
10873     mb();
10874     wmb();
10875
10876     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10877            reset_mask2 & (~stay_reset2));
10878
10879     mb();
10880     wmb();
10881
10882     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10883     wmb();
10884 }
10885
10886 static int
10887 bxe_process_kill(struct bxe_softc *sc,
10888                  uint8_t          global)
10889 {
10890     int cnt = 1000;
10891     uint32_t val = 0;
10892     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10893     uint32_t tags_63_32 = 0;
10894
10895     /* Empty the Tetris buffer, wait for 1s */
10896     do {
10897         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10898         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10899         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10900         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10901         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10902         if (CHIP_IS_E3(sc)) {
10903             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10904         }
10905
10906         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
10907             ((port_is_idle_0 & 0x1) == 0x1) &&
10908             ((port_is_idle_1 & 0x1) == 0x1) &&
10909             (pgl_exp_rom2 == 0xffffffff) &&
10910             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
10911             break;
10912         DELAY(1000);
10913     } while (cnt-- > 0);
10914
10915     if (cnt <= 0) {
10916         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
10917                   "are still outstanding read requests after 1s! "
10918                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
10919                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
10920               sr_cnt, blk_cnt, port_is_idle_0,
10921               port_is_idle_1, pgl_exp_rom2);
10922         return (-1);
10923     }
10924
10925     mb();
10926
10927     /* Close gates #2, #3 and #4 */
10928     bxe_set_234_gates(sc, TRUE);
10929
10930     /* Poll for IGU VQs for 57712 and newer chips */
10931     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
10932         return (-1);
10933     }
10934
10935     /* XXX indicate that "process kill" is in progress to MCP */
10936
10937     /* clear "unprepared" bit */
10938     REG_WR(sc, MISC_REG_UNPREPARED, 0);
10939     mb();
10940
10941     /* Make sure all is written to the chip before the reset */
10942     wmb();
10943
10944     /*
10945      * Wait for 1ms to empty GLUE and PCI-E core queues,
10946      * PSWHST, GRC and PSWRD Tetris buffer.
10947      */
10948     DELAY(1000);
10949
10950     /* Prepare to chip reset: */
10951     /* MCP */
10952     if (global) {
10953         bxe_reset_mcp_prep(sc, &val);
10954     }
10955
10956     /* PXP */
10957     bxe_pxp_prep(sc);
10958     mb();
10959
10960     /* reset the chip */
10961     bxe_process_kill_chip_reset(sc, global);
10962     mb();
10963
10964     /* clear errors in PGB */
10965     if (!CHIP_IS_E1(sc))
10966         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
10967
10968     /* Recover after reset: */
10969     /* MCP */
10970     if (global && bxe_reset_mcp_comp(sc, val)) {
10971         return (-1);
10972     }
10973
10974     /* XXX add resetting the NO_MCP mode DB here */
10975
10976     /* Open the gates #2, #3 and #4 */
10977     bxe_set_234_gates(sc, FALSE);
10978
10979     /* XXX
10980      * IGU/AEU preparation bring back the AEU/IGU to a reset state
10981      * re-enable attentions
10982      */
10983
10984     return (0);
10985 }
10986
10987 static int
10988 bxe_leader_reset(struct bxe_softc *sc)
10989 {
10990     int rc = 0;
10991     uint8_t global = bxe_reset_is_global(sc);
10992     uint32_t load_code;
10993
10994     /*
10995      * If not going to reset MCP, load "fake" driver to reset HW while
10996      * driver is owner of the HW.
10997      */
10998     if (!global && !BXE_NOMCP(sc)) {
10999         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11000                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11001         if (!load_code) {
11002             BLOGE(sc, "MCP response failure, aborting\n");
11003             rc = -1;
11004             goto exit_leader_reset;
11005         }
11006
11007         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11008             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11009             BLOGE(sc, "MCP unexpected response, aborting\n");
11010             rc = -1;
11011             goto exit_leader_reset2;
11012         }
11013
11014         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11015         if (!load_code) {
11016             BLOGE(sc, "MCP response failure, aborting\n");
11017             rc = -1;
11018             goto exit_leader_reset2;
11019         }
11020     }
11021
11022     /* try to recover after the failure */
11023     if (bxe_process_kill(sc, global)) {
11024         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11025         rc = -1;
11026         goto exit_leader_reset2;
11027     }
11028
11029     /*
11030      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11031      * state.
11032      */
11033     bxe_set_reset_done(sc);
11034     if (global) {
11035         bxe_clear_reset_global(sc);
11036     }
11037
11038 exit_leader_reset2:
11039
11040     /* unload "fake driver" if it was loaded */
11041     if (!global && !BXE_NOMCP(sc)) {
11042         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11043         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11044     }
11045
11046 exit_leader_reset:
11047
11048     sc->is_leader = 0;
11049     bxe_release_leader_lock(sc);
11050
11051     mb();
11052     return (rc);
11053 }
11054
11055 /*
11056  * prepare INIT transition, parameters configured:
11057  *   - HC configuration
11058  *   - Queue's CDU context
11059  */
11060 static void
11061 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11062                    struct bxe_fastpath            *fp,
11063                    struct ecore_queue_init_params *init_params)
11064 {
11065     uint8_t cos;
11066     int cxt_index, cxt_offset;
11067
11068     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11069     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11070
11071     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11072     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11073
11074     /* HC rate */
11075     init_params->rx.hc_rate =
11076         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11077     init_params->tx.hc_rate =
11078         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11079
11080     /* FW SB ID */
11081     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11082
11083     /* CQ index among the SB indices */
11084     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11085     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11086
11087     /* set maximum number of COSs supported by this queue */
11088     init_params->max_cos = sc->max_cos;
11089
11090     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11091           fp->index, init_params->max_cos);
11092
11093     /* set the context pointers queue object */
11094     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11095         /* XXX change index/cid here if ever support multiple tx CoS */
11096         /* fp->txdata[cos]->cid */
11097         cxt_index = fp->index / ILT_PAGE_CIDS;
11098         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11099         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11100     }
11101 }
11102
11103 /* set flags that are common for the Tx-only and not normal connections */
11104 static unsigned long
11105 bxe_get_common_flags(struct bxe_softc    *sc,
11106                      struct bxe_fastpath *fp,
11107                      uint8_t             zero_stats)
11108 {
11109     unsigned long flags = 0;
11110
11111     /* PF driver will always initialize the Queue to an ACTIVE state */
11112     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11113
11114     /*
11115      * tx only connections collect statistics (on the same index as the
11116      * parent connection). The statistics are zeroed when the parent
11117      * connection is initialized.
11118      */
11119
11120     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11121     if (zero_stats) {
11122         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11123     }
11124
11125     /*
11126      * tx only connections can support tx-switching, though their
11127      * CoS-ness doesn't survive the loopback
11128      */
11129     if (sc->flags & BXE_TX_SWITCHING) {
11130         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11131     }
11132
11133     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11134
11135     return (flags);
11136 }
11137
11138 static unsigned long
11139 bxe_get_q_flags(struct bxe_softc    *sc,
11140                 struct bxe_fastpath *fp,
11141                 uint8_t             leading)
11142 {
11143     unsigned long flags = 0;
11144
11145     if (IS_MF_SD(sc)) {
11146         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11147     }
11148
11149     if (if_getcapenable(sc->ifp) & IFCAP_LRO) {
11150         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11151         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11152     }
11153
11154     if (leading) {
11155         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11156         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11157     }
11158
11159     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11160
11161     /* merge with common flags */
11162     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11163 }
11164
11165 static void
11166 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11167                       struct bxe_fastpath               *fp,
11168                       struct ecore_general_setup_params *gen_init,
11169                       uint8_t                           cos)
11170 {
11171     gen_init->stat_id = bxe_stats_id(fp);
11172     gen_init->spcl_id = fp->cl_id;
11173     gen_init->mtu = sc->mtu;
11174     gen_init->cos = cos;
11175 }
11176
11177 static void
11178 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11179                  struct bxe_fastpath           *fp,
11180                  struct rxq_pause_params       *pause,
11181                  struct ecore_rxq_setup_params *rxq_init)
11182 {
11183     uint8_t max_sge = 0;
11184     uint16_t sge_sz = 0;
11185     uint16_t tpa_agg_size = 0;
11186
11187     pause->sge_th_lo = SGE_TH_LO(sc);
11188     pause->sge_th_hi = SGE_TH_HI(sc);
11189
11190     /* validate SGE ring has enough to cross high threshold */
11191     if (sc->dropless_fc &&
11192             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11193             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11194         BLOGW(sc, "sge ring threshold limit\n");
11195     }
11196
11197     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11198     tpa_agg_size = (2 * sc->mtu);
11199     if (tpa_agg_size < sc->max_aggregation_size) {
11200         tpa_agg_size = sc->max_aggregation_size;
11201     }
11202
11203     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11204     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11205                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11206     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11207
11208     /* pause - not for e1 */
11209     if (!CHIP_IS_E1(sc)) {
11210         pause->bd_th_lo = BD_TH_LO(sc);
11211         pause->bd_th_hi = BD_TH_HI(sc);
11212
11213         pause->rcq_th_lo = RCQ_TH_LO(sc);
11214         pause->rcq_th_hi = RCQ_TH_HI(sc);
11215
11216         /* validate rings have enough entries to cross high thresholds */
11217         if (sc->dropless_fc &&
11218             pause->bd_th_hi + FW_PREFETCH_CNT >
11219             sc->rx_ring_size) {
11220             BLOGW(sc, "rx bd ring threshold limit\n");
11221         }
11222
11223         if (sc->dropless_fc &&
11224             pause->rcq_th_hi + FW_PREFETCH_CNT >
11225             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11226             BLOGW(sc, "rcq ring threshold limit\n");
11227         }
11228
11229         pause->pri_map = 1;
11230     }
11231
11232     /* rxq setup */
11233     rxq_init->dscr_map   = fp->rx_dma.paddr;
11234     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11235     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11236     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11237
11238     /*
11239      * This should be a maximum number of data bytes that may be
11240      * placed on the BD (not including paddings).
11241      */
11242     rxq_init->buf_sz = (fp->rx_buf_size -
11243                         IP_HEADER_ALIGNMENT_PADDING);
11244
11245     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11246     rxq_init->tpa_agg_sz      = tpa_agg_size;
11247     rxq_init->sge_buf_sz      = sge_sz;
11248     rxq_init->max_sges_pkt    = max_sge;
11249     rxq_init->rss_engine_id   = SC_FUNC(sc);
11250     rxq_init->mcast_engine_id = SC_FUNC(sc);
11251
11252     /*
11253      * Maximum number or simultaneous TPA aggregation for this Queue.
11254      * For PF Clients it should be the maximum available number.
11255      * VF driver(s) may want to define it to a smaller value.
11256      */
11257     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11258
11259     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11260     rxq_init->fw_sb_id = fp->fw_sb_id;
11261
11262     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11263
11264     /*
11265      * configure silent vlan removal
11266      * if multi function mode is afex, then mask default vlan
11267      */
11268     if (IS_MF_AFEX(sc)) {
11269         rxq_init->silent_removal_value =
11270             sc->devinfo.mf_info.afex_def_vlan_tag;
11271         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11272     }
11273 }
11274
11275 static void
11276 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11277                  struct bxe_fastpath           *fp,
11278                  struct ecore_txq_setup_params *txq_init,
11279                  uint8_t                       cos)
11280 {
11281     /*
11282      * XXX If multiple CoS is ever supported then each fastpath structure
11283      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11284      * fp->txdata[cos]->tx_dma.paddr;
11285      */
11286     txq_init->dscr_map     = fp->tx_dma.paddr;
11287     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11288     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11289     txq_init->fw_sb_id     = fp->fw_sb_id;
11290
11291     /*
11292      * set the TSS leading client id for TX classfication to the
11293      * leading RSS client id
11294      */
11295     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11296 }
11297
11298 /*
11299  * This function performs 2 steps in a queue state machine:
11300  *   1) RESET->INIT
11301  *   2) INIT->SETUP
11302  */
11303 static int
11304 bxe_setup_queue(struct bxe_softc    *sc,
11305                 struct bxe_fastpath *fp,
11306                 uint8_t             leading)
11307 {
11308     struct ecore_queue_state_params q_params = { NULL };
11309     struct ecore_queue_setup_params *setup_params =
11310                         &q_params.params.setup;
11311     int rc;
11312
11313     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11314
11315     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11316
11317     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11318
11319     /* we want to wait for completion in this context */
11320     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11321
11322     /* prepare the INIT parameters */
11323     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11324
11325     /* Set the command */
11326     q_params.cmd = ECORE_Q_CMD_INIT;
11327
11328     /* Change the state to INIT */
11329     rc = ecore_queue_state_change(sc, &q_params);
11330     if (rc) {
11331         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11332         return (rc);
11333     }
11334
11335     BLOGD(sc, DBG_LOAD, "init complete\n");
11336
11337     /* now move the Queue to the SETUP state */
11338     memset(setup_params, 0, sizeof(*setup_params));
11339
11340     /* set Queue flags */
11341     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11342
11343     /* set general SETUP parameters */
11344     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11345                           FIRST_TX_COS_INDEX);
11346
11347     bxe_pf_rx_q_prep(sc, fp,
11348                      &setup_params->pause_params,
11349                      &setup_params->rxq_params);
11350
11351     bxe_pf_tx_q_prep(sc, fp,
11352                      &setup_params->txq_params,
11353                      FIRST_TX_COS_INDEX);
11354
11355     /* Set the command */
11356     q_params.cmd = ECORE_Q_CMD_SETUP;
11357
11358     /* change the state to SETUP */
11359     rc = ecore_queue_state_change(sc, &q_params);
11360     if (rc) {
11361         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11362         return (rc);
11363     }
11364
11365     return (rc);
11366 }
11367
11368 static int
11369 bxe_setup_leading(struct bxe_softc *sc)
11370 {
11371     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11372 }
11373
11374 static int
11375 bxe_config_rss_pf(struct bxe_softc            *sc,
11376                   struct ecore_rss_config_obj *rss_obj,
11377                   uint8_t                     config_hash)
11378 {
11379     struct ecore_config_rss_params params = { NULL };
11380     int i;
11381
11382     /*
11383      * Although RSS is meaningless when there is a single HW queue we
11384      * still need it enabled in order to have HW Rx hash generated.
11385      */
11386
11387     params.rss_obj = rss_obj;
11388
11389     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11390
11391     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11392
11393     /* RSS configuration */
11394     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11395     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11396     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11397     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11398     if (rss_obj->udp_rss_v4) {
11399         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11400     }
11401     if (rss_obj->udp_rss_v6) {
11402         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11403     }
11404
11405     /* Hash bits */
11406     params.rss_result_mask = MULTI_MASK;
11407
11408     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11409
11410     if (config_hash) {
11411         /* RSS keys */
11412         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11413             params.rss_key[i] = arc4random();
11414         }
11415
11416         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11417     }
11418
11419     return (ecore_config_rss(sc, &params));
11420 }
11421
11422 static int
11423 bxe_config_rss_eth(struct bxe_softc *sc,
11424                    uint8_t          config_hash)
11425 {
11426     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11427 }
11428
11429 static int
11430 bxe_init_rss_pf(struct bxe_softc *sc)
11431 {
11432     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11433     int i;
11434
11435     /*
11436      * Prepare the initial contents of the indirection table if
11437      * RSS is enabled
11438      */
11439     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11440         sc->rss_conf_obj.ind_table[i] =
11441             (sc->fp->cl_id + (i % num_eth_queues));
11442     }
11443
11444     if (sc->udp_rss) {
11445         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11446     }
11447
11448     /*
11449      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11450      * per-port, so if explicit configuration is needed, do it only
11451      * for a PMF.
11452      *
11453      * For 57712 and newer it's a per-function configuration.
11454      */
11455     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11456 }
11457
11458 static int
11459 bxe_set_mac_one(struct bxe_softc          *sc,
11460                 uint8_t                   *mac,
11461                 struct ecore_vlan_mac_obj *obj,
11462                 uint8_t                   set,
11463                 int                       mac_type,
11464                 unsigned long             *ramrod_flags)
11465 {
11466     struct ecore_vlan_mac_ramrod_params ramrod_param;
11467     int rc;
11468
11469     memset(&ramrod_param, 0, sizeof(ramrod_param));
11470
11471     /* fill in general parameters */
11472     ramrod_param.vlan_mac_obj = obj;
11473     ramrod_param.ramrod_flags = *ramrod_flags;
11474
11475     /* fill a user request section if needed */
11476     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11477         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11478
11479         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11480
11481         /* Set the command: ADD or DEL */
11482         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11483                                             ECORE_VLAN_MAC_DEL;
11484     }
11485
11486     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11487
11488     if (rc == ECORE_EXISTS) {
11489         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11490         /* do not treat adding same MAC as error */
11491         rc = 0;
11492     } else if (rc < 0) {
11493         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11494     }
11495
11496     return (rc);
11497 }
11498
11499 static int
11500 bxe_set_eth_mac(struct bxe_softc *sc,
11501                 uint8_t          set)
11502 {
11503     unsigned long ramrod_flags = 0;
11504
11505     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11506
11507     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11508
11509     /* Eth MAC is set on RSS leading client (fp[0]) */
11510     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11511                             &sc->sp_objs->mac_obj,
11512                             set, ECORE_ETH_MAC, &ramrod_flags));
11513 }
11514
11515 static int
11516 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11517 {
11518     uint32_t sel_phy_idx = 0;
11519
11520     if (sc->link_params.num_phys <= 1) {
11521         return (ELINK_INT_PHY);
11522     }
11523
11524     if (sc->link_vars.link_up) {
11525         sel_phy_idx = ELINK_EXT_PHY1;
11526         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11527         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11528             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11529              ELINK_SUPPORTED_FIBRE))
11530             sel_phy_idx = ELINK_EXT_PHY2;
11531     } else {
11532         switch (elink_phy_selection(&sc->link_params)) {
11533         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11534         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11535         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11536                sel_phy_idx = ELINK_EXT_PHY1;
11537                break;
11538         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11539         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11540                sel_phy_idx = ELINK_EXT_PHY2;
11541                break;
11542         }
11543     }
11544
11545     return (sel_phy_idx);
11546 }
11547
11548 static int
11549 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11550 {
11551     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11552
11553     /*
11554      * The selected activated PHY is always after swapping (in case PHY
11555      * swapping is enabled). So when swapping is enabled, we need to reverse
11556      * the configuration
11557      */
11558
11559     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11560         if (sel_phy_idx == ELINK_EXT_PHY1)
11561             sel_phy_idx = ELINK_EXT_PHY2;
11562         else if (sel_phy_idx == ELINK_EXT_PHY2)
11563             sel_phy_idx = ELINK_EXT_PHY1;
11564     }
11565
11566     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11567 }
11568
11569 static void
11570 bxe_set_requested_fc(struct bxe_softc *sc)
11571 {
11572     /*
11573      * Initialize link parameters structure variables
11574      * It is recommended to turn off RX FC for jumbo frames
11575      * for better performance
11576      */
11577     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11578         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11579     } else {
11580         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11581     }
11582 }
11583
11584 static void
11585 bxe_calc_fc_adv(struct bxe_softc *sc)
11586 {
11587     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11588     switch (sc->link_vars.ieee_fc &
11589             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11590     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11591     default:
11592         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11593                                            ADVERTISED_Pause);
11594         break;
11595
11596     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11597         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11598                                           ADVERTISED_Pause);
11599         break;
11600
11601     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11602         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11603         break;
11604     }
11605 }
11606
11607 static uint16_t
11608 bxe_get_mf_speed(struct bxe_softc *sc)
11609 {
11610     uint16_t line_speed = sc->link_vars.line_speed;
11611     if (IS_MF(sc)) {
11612         uint16_t maxCfg =
11613             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11614
11615         /* calculate the current MAX line speed limit for the MF devices */
11616         if (IS_MF_SI(sc)) {
11617             line_speed = (line_speed * maxCfg) / 100;
11618         } else { /* SD mode */
11619             uint16_t vn_max_rate = maxCfg * 100;
11620
11621             if (vn_max_rate < line_speed) {
11622                 line_speed = vn_max_rate;
11623             }
11624         }
11625     }
11626
11627     return (line_speed);
11628 }
11629
11630 static void
11631 bxe_fill_report_data(struct bxe_softc            *sc,
11632                      struct bxe_link_report_data *data)
11633 {
11634     uint16_t line_speed = bxe_get_mf_speed(sc);
11635
11636     memset(data, 0, sizeof(*data));
11637
11638     /* fill the report data with the effective line speed */
11639     data->line_speed = line_speed;
11640
11641     /* Link is down */
11642     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11643         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11644     }
11645
11646     /* Full DUPLEX */
11647     if (sc->link_vars.duplex == DUPLEX_FULL) {
11648         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11649     }
11650
11651     /* Rx Flow Control is ON */
11652     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11653         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11654     }
11655
11656     /* Tx Flow Control is ON */
11657     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11658         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11659     }
11660 }
11661
11662 /* report link status to OS, should be called under phy_lock */
11663 static void
11664 bxe_link_report_locked(struct bxe_softc *sc)
11665 {
11666     struct bxe_link_report_data cur_data;
11667
11668     /* reread mf_cfg */
11669     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11670         bxe_read_mf_cfg(sc);
11671     }
11672
11673     /* Read the current link report info */
11674     bxe_fill_report_data(sc, &cur_data);
11675
11676     /* Don't report link down or exactly the same link status twice */
11677     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11678         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11679                       &sc->last_reported_link.link_report_flags) &&
11680          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11681                       &cur_data.link_report_flags))) {
11682         return;
11683     }
11684
11685     sc->link_cnt++;
11686
11687     /* report new link params and remember the state for the next time */
11688     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11689
11690     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11691                      &cur_data.link_report_flags)) {
11692         if_link_state_change(sc->ifp, LINK_STATE_DOWN);
11693         BLOGI(sc, "NIC Link is Down\n");
11694     } else {
11695         const char *duplex;
11696         const char *flow;
11697
11698         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11699                                    &cur_data.link_report_flags)) {
11700             duplex = "full";
11701         } else {
11702             duplex = "half";
11703         }
11704
11705         /*
11706          * Handle the FC at the end so that only these flags would be
11707          * possibly set. This way we may easily check if there is no FC
11708          * enabled.
11709          */
11710         if (cur_data.link_report_flags) {
11711             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11712                              &cur_data.link_report_flags) &&
11713                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11714                              &cur_data.link_report_flags)) {
11715                 flow = "ON - receive & transmit";
11716             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11717                                     &cur_data.link_report_flags) &&
11718                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11719                                      &cur_data.link_report_flags)) {
11720                 flow = "ON - receive";
11721             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11722                                      &cur_data.link_report_flags) &&
11723                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11724                                     &cur_data.link_report_flags)) {
11725                 flow = "ON - transmit";
11726             } else {
11727                 flow = "none"; /* possible? */
11728             }
11729         } else {
11730             flow = "none";
11731         }
11732
11733         if_link_state_change(sc->ifp, LINK_STATE_UP);
11734         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11735               cur_data.line_speed, duplex, flow);
11736     }
11737 }
11738
11739 static void
11740 bxe_link_report(struct bxe_softc *sc)
11741 {
11742     bxe_acquire_phy_lock(sc);
11743     bxe_link_report_locked(sc);
11744     bxe_release_phy_lock(sc);
11745 }
11746
11747 static void
11748 bxe_link_status_update(struct bxe_softc *sc)
11749 {
11750     if (sc->state != BXE_STATE_OPEN) {
11751         return;
11752     }
11753
11754     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11755         elink_link_status_update(&sc->link_params, &sc->link_vars);
11756     } else {
11757         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11758                                   ELINK_SUPPORTED_10baseT_Full |
11759                                   ELINK_SUPPORTED_100baseT_Half |
11760                                   ELINK_SUPPORTED_100baseT_Full |
11761                                   ELINK_SUPPORTED_1000baseT_Full |
11762                                   ELINK_SUPPORTED_2500baseX_Full |
11763                                   ELINK_SUPPORTED_10000baseT_Full |
11764                                   ELINK_SUPPORTED_TP |
11765                                   ELINK_SUPPORTED_FIBRE |
11766                                   ELINK_SUPPORTED_Autoneg |
11767                                   ELINK_SUPPORTED_Pause |
11768                                   ELINK_SUPPORTED_Asym_Pause);
11769         sc->port.advertising[0] = sc->port.supported[0];
11770
11771         sc->link_params.sc                = sc;
11772         sc->link_params.port              = SC_PORT(sc);
11773         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11774         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11775         sc->link_params.req_line_speed[0] = SPEED_10000;
11776         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11777         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11778
11779         if (CHIP_REV_IS_FPGA(sc)) {
11780             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11781             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11782             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11783                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11784         } else {
11785             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11786             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11787             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11788                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11789         }
11790
11791         sc->link_vars.link_up = 1;
11792
11793         sc->link_vars.duplex    = DUPLEX_FULL;
11794         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11795
11796         if (IS_PF(sc)) {
11797             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11798             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11799             bxe_link_report(sc);
11800         }
11801     }
11802
11803     if (IS_PF(sc)) {
11804         if (sc->link_vars.link_up) {
11805             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11806         } else {
11807             bxe_stats_handle(sc, STATS_EVENT_STOP);
11808         }
11809         bxe_link_report(sc);
11810     } else {
11811         bxe_link_report(sc);
11812         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11813     }
11814 }
11815
11816 static int
11817 bxe_initial_phy_init(struct bxe_softc *sc,
11818                      int              load_mode)
11819 {
11820     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11821     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11822     struct elink_params *lp = &sc->link_params;
11823
11824     bxe_set_requested_fc(sc);
11825
11826     if (CHIP_REV_IS_SLOW(sc)) {
11827         uint32_t bond = CHIP_BOND_ID(sc);
11828         uint32_t feat = 0;
11829
11830         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11831             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11832         } else if (bond & 0x4) {
11833             if (CHIP_IS_E3(sc)) {
11834                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11835             } else {
11836                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11837             }
11838         } else if (bond & 0x8) {
11839             if (CHIP_IS_E3(sc)) {
11840                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11841             } else {
11842                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11843             }
11844         }
11845
11846         /* disable EMAC for E3 and above */
11847         if (bond & 0x2) {
11848             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11849         }
11850
11851         sc->link_params.feature_config_flags |= feat;
11852     }
11853
11854     bxe_acquire_phy_lock(sc);
11855
11856     if (load_mode == LOAD_DIAG) {
11857         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11858         /* Prefer doing PHY loopback at 10G speed, if possible */
11859         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11860             if (lp->speed_cap_mask[cfg_idx] &
11861                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11862                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11863             } else {
11864                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11865             }
11866         }
11867     }
11868
11869     if (load_mode == LOAD_LOOPBACK_EXT) {
11870         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11871     }
11872
11873     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11874
11875     bxe_release_phy_lock(sc);
11876
11877     bxe_calc_fc_adv(sc);
11878
11879     if (sc->link_vars.link_up) {
11880         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11881         bxe_link_report(sc);
11882     }
11883
11884     if (!CHIP_REV_IS_SLOW(sc)) {
11885         bxe_periodic_start(sc);
11886     }
11887
11888     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11889     return (rc);
11890 }
11891
11892 /* must be called under IF_ADDR_LOCK */
11893
11894 static int
11895 bxe_set_mc_list(struct bxe_softc *sc)
11896 {
11897     struct ecore_mcast_ramrod_params rparam = { NULL };
11898     int rc = 0;
11899     int mc_count = 0;
11900     int mcnt, i;
11901     struct ecore_mcast_list_elem *mc_mac, *mc_mac_start;
11902     unsigned char *mta;
11903     if_t ifp = sc->ifp;
11904
11905     mc_count = if_multiaddr_count(ifp, -1);/* XXX they don't have a limit */
11906     if (!mc_count)
11907         return (0);
11908
11909     mta = malloc(sizeof(unsigned char) * ETHER_ADDR_LEN *
11910             mc_count, M_DEVBUF, M_NOWAIT);
11911
11912     if(mta == NULL) {
11913         BLOGE(sc, "Failed to allocate temp mcast list\n");
11914         return (-1);
11915     }
11916     bzero(mta, (sizeof(unsigned char) * ETHER_ADDR_LEN * mc_count));
11917     
11918     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF, (M_NOWAIT | M_ZERO));
11919     mc_mac_start = mc_mac;
11920
11921     if (!mc_mac) {
11922         free(mta, M_DEVBUF);
11923         BLOGE(sc, "Failed to allocate temp mcast list\n");
11924         return (-1);
11925     }
11926     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
11927
11928     /* mta and mcnt not expected to be  different */
11929     if_multiaddr_array(ifp, mta, &mcnt, mc_count);
11930
11931
11932     rparam.mcast_obj = &sc->mcast_obj;
11933     ECORE_LIST_INIT(&rparam.mcast_list);
11934
11935     for(i=0; i< mcnt; i++) {
11936
11937         mc_mac->mac = (uint8_t *)(mta + (i * ETHER_ADDR_LEN));
11938         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &rparam.mcast_list);
11939
11940         BLOGD(sc, DBG_LOAD,
11941               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
11942               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
11943               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
11944
11945         mc_mac++;
11946     }
11947     rparam.mcast_list_len = mc_count;
11948
11949     BXE_MCAST_LOCK(sc);
11950
11951     /* first, clear all configured multicast MACs */
11952     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
11953     if (rc < 0) {
11954         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
11955         BXE_MCAST_UNLOCK(sc);
11956         free(mc_mac_start, M_DEVBUF);
11957         free(mta, M_DEVBUF);
11958         return (rc);
11959     }
11960
11961     /* Now add the new MACs */
11962     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
11963     if (rc < 0) {
11964         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
11965     }
11966
11967     BXE_MCAST_UNLOCK(sc);
11968
11969     free(mc_mac_start, M_DEVBUF);
11970     free(mta, M_DEVBUF);
11971
11972     return (rc);
11973 }
11974
11975 static int
11976 bxe_set_uc_list(struct bxe_softc *sc)
11977 {
11978     if_t ifp = sc->ifp;
11979     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
11980     struct ifaddr *ifa;
11981     unsigned long ramrod_flags = 0;
11982     int rc;
11983
11984 #if __FreeBSD_version < 800000
11985     IF_ADDR_LOCK(ifp);
11986 #else
11987     if_addr_rlock(ifp);
11988 #endif
11989
11990     /* first schedule a cleanup up of old configuration */
11991     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
11992     if (rc < 0) {
11993         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
11994 #if __FreeBSD_version < 800000
11995         IF_ADDR_UNLOCK(ifp);
11996 #else
11997         if_addr_runlock(ifp);
11998 #endif
11999         return (rc);
12000     }
12001
12002     ifa = if_getifaddr(ifp); /* XXX Is this structure */
12003     while (ifa) {
12004         if (ifa->ifa_addr->sa_family != AF_LINK) {
12005             ifa = TAILQ_NEXT(ifa, ifa_link);
12006             continue;
12007         }
12008
12009         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12010                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12011         if (rc == -EEXIST) {
12012             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12013             /* do not treat adding same MAC as an error */
12014             rc = 0;
12015         } else if (rc < 0) {
12016             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12017 #if __FreeBSD_version < 800000
12018             IF_ADDR_UNLOCK(ifp);
12019 #else
12020             if_addr_runlock(ifp);
12021 #endif
12022             return (rc);
12023         }
12024
12025         ifa = TAILQ_NEXT(ifa, ifa_link);
12026     }
12027
12028 #if __FreeBSD_version < 800000
12029     IF_ADDR_UNLOCK(ifp);
12030 #else
12031     if_addr_runlock(ifp);
12032 #endif
12033
12034     /* Execute the pending commands */
12035     bit_set(&ramrod_flags, RAMROD_CONT);
12036     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12037                             ECORE_UC_LIST_MAC, &ramrod_flags));
12038 }
12039
12040 static void
12041 bxe_set_rx_mode(struct bxe_softc *sc)
12042 {
12043     if_t ifp = sc->ifp;
12044     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12045
12046     if (sc->state != BXE_STATE_OPEN) {
12047         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12048         return;
12049     }
12050
12051     BLOGD(sc, DBG_SP, "if_flags(ifp)=0x%x\n", if_getflags(sc->ifp));
12052
12053     if (if_getflags(ifp) & IFF_PROMISC) {
12054         rx_mode = BXE_RX_MODE_PROMISC;
12055     } else if ((if_getflags(ifp) & IFF_ALLMULTI) ||
12056                ((if_getamcount(ifp) > BXE_MAX_MULTICAST) &&
12057                 CHIP_IS_E1(sc))) {
12058         rx_mode = BXE_RX_MODE_ALLMULTI;
12059     } else {
12060         if (IS_PF(sc)) {
12061             /* some multicasts */
12062             if (bxe_set_mc_list(sc) < 0) {
12063                 rx_mode = BXE_RX_MODE_ALLMULTI;
12064             }
12065             if (bxe_set_uc_list(sc) < 0) {
12066                 rx_mode = BXE_RX_MODE_PROMISC;
12067             }
12068         }
12069     }
12070
12071     sc->rx_mode = rx_mode;
12072
12073     /* schedule the rx_mode command */
12074     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12075         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12076         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12077         return;
12078     }
12079
12080     if (IS_PF(sc)) {
12081         bxe_set_storm_rx_mode(sc);
12082     }
12083 }
12084
12085
12086 /* update flags in shmem */
12087 static void
12088 bxe_update_drv_flags(struct bxe_softc *sc,
12089                      uint32_t         flags,
12090                      uint32_t         set)
12091 {
12092     uint32_t drv_flags;
12093
12094     if (SHMEM2_HAS(sc, drv_flags)) {
12095         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12096         drv_flags = SHMEM2_RD(sc, drv_flags);
12097
12098         if (set) {
12099             SET_FLAGS(drv_flags, flags);
12100         } else {
12101             RESET_FLAGS(drv_flags, flags);
12102         }
12103
12104         SHMEM2_WR(sc, drv_flags, drv_flags);
12105         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12106
12107         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12108     }
12109 }
12110
12111 /* periodic timer callout routine, only runs when the interface is up */
12112
12113 static void
12114 bxe_periodic_callout_func(void *xsc)
12115 {
12116     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12117     struct bxe_fastpath *fp;
12118     uint16_t tx_bd_avail;
12119     int i;
12120
12121     if (!BXE_CORE_TRYLOCK(sc)) {
12122         /* just bail and try again next time */
12123
12124         if ((sc->state == BXE_STATE_OPEN) &&
12125             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12126             /* schedule the next periodic callout */
12127             callout_reset(&sc->periodic_callout, hz,
12128                           bxe_periodic_callout_func, sc);
12129         }
12130
12131         return;
12132     }
12133
12134     if ((sc->state != BXE_STATE_OPEN) ||
12135         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12136         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12137         BXE_CORE_UNLOCK(sc);
12138         return;
12139     }
12140
12141 #if __FreeBSD_version >= 800000
12142
12143     FOR_EACH_QUEUE(sc, i) {
12144         fp = &sc->fp[i];
12145
12146         if (BXE_FP_TX_TRYLOCK(fp)) {
12147             if_t ifp = sc->ifp;
12148             /*
12149              * If interface was stopped due to unavailable
12150              * bds, try to process some tx completions
12151              */
12152             (void) bxe_txeof(sc, fp);
12153            
12154             tx_bd_avail = bxe_tx_avail(sc, fp);
12155             if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12156                 bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
12157             }
12158             BXE_FP_TX_UNLOCK(fp);
12159         }
12160     }
12161
12162 #else
12163
12164     fp = &sc->fp[0];
12165     if (BXE_FP_TX_TRYLOCK(fp)) {
12166         struct ifnet *ifp = sc->ifnet;
12167         /*
12168          * If interface was stopped due to unavailable
12169          * bds, try to process some tx completions
12170          */
12171         (void) bxe_txeof(sc, fp);
12172            
12173         tx_bd_avail = bxe_tx_avail(sc, fp);
12174         if (tx_bd_avail >= BXE_TX_CLEANUP_THRESHOLD) {
12175             bxe_tx_start_locked(sc, ifp, fp);
12176         }
12177  
12178         BXE_FP_TX_UNLOCK(fp);
12179     }
12180
12181 #endif /* #if __FreeBSD_version >= 800000 */
12182
12183     /* Check for TX timeouts on any fastpath. */
12184     FOR_EACH_QUEUE(sc, i) {
12185         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12186             /* Ruh-Roh, chip was reset! */
12187             break;
12188         }
12189     }
12190
12191     if (!CHIP_REV_IS_SLOW(sc)) {
12192         /*
12193          * This barrier is needed to ensure the ordering between the writing
12194          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12195          * the reading here.
12196          */
12197         mb();
12198         if (sc->port.pmf) {
12199             bxe_acquire_phy_lock(sc);
12200             elink_period_func(&sc->link_params, &sc->link_vars);
12201             bxe_release_phy_lock(sc);
12202         }
12203     }
12204
12205     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12206         int mb_idx = SC_FW_MB_IDX(sc);
12207         uint32_t drv_pulse;
12208         uint32_t mcp_pulse;
12209
12210         ++sc->fw_drv_pulse_wr_seq;
12211         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12212
12213         drv_pulse = sc->fw_drv_pulse_wr_seq;
12214         bxe_drv_pulse(sc);
12215
12216         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12217                      MCP_PULSE_SEQ_MASK);
12218
12219         /*
12220          * The delta between driver pulse and mcp response should
12221          * be 1 (before mcp response) or 0 (after mcp response).
12222          */
12223         if ((drv_pulse != mcp_pulse) &&
12224             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12225             /* someone lost a heartbeat... */
12226             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12227                   drv_pulse, mcp_pulse);
12228         }
12229     }
12230
12231     /* state is BXE_STATE_OPEN */
12232     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12233
12234     BXE_CORE_UNLOCK(sc);
12235
12236     if ((sc->state == BXE_STATE_OPEN) &&
12237         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12238         /* schedule the next periodic callout */
12239         callout_reset(&sc->periodic_callout, hz,
12240                       bxe_periodic_callout_func, sc);
12241     }
12242 }
12243
12244 static void
12245 bxe_periodic_start(struct bxe_softc *sc)
12246 {
12247     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12248     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12249 }
12250
12251 static void
12252 bxe_periodic_stop(struct bxe_softc *sc)
12253 {
12254     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12255     callout_drain(&sc->periodic_callout);
12256 }
12257
12258 /* start the controller */
12259 static __noinline int
12260 bxe_nic_load(struct bxe_softc *sc,
12261              int              load_mode)
12262 {
12263     uint32_t val;
12264     int load_code = 0;
12265     int i, rc = 0;
12266
12267     BXE_CORE_LOCK_ASSERT(sc);
12268
12269     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12270
12271     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12272
12273     if (IS_PF(sc)) {
12274         /* must be called before memory allocation and HW init */
12275         bxe_ilt_set_info(sc);
12276     }
12277
12278     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12279
12280     bxe_set_fp_rx_buf_size(sc);
12281
12282     if (bxe_alloc_fp_buffers(sc) != 0) {
12283         BLOGE(sc, "Failed to allocate fastpath memory\n");
12284         sc->state = BXE_STATE_CLOSED;
12285         rc = ENOMEM;
12286         goto bxe_nic_load_error0;
12287     }
12288
12289     if (bxe_alloc_mem(sc) != 0) {
12290         sc->state = BXE_STATE_CLOSED;
12291         rc = ENOMEM;
12292         goto bxe_nic_load_error0;
12293     }
12294
12295     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12296         sc->state = BXE_STATE_CLOSED;
12297         rc = ENOMEM;
12298         goto bxe_nic_load_error0;
12299     }
12300
12301     if (IS_PF(sc)) {
12302         /* set pf load just before approaching the MCP */
12303         bxe_set_pf_load(sc);
12304
12305         /* if MCP exists send load request and analyze response */
12306         if (!BXE_NOMCP(sc)) {
12307             /* attempt to load pf */
12308             if (bxe_nic_load_request(sc, &load_code) != 0) {
12309                 sc->state = BXE_STATE_CLOSED;
12310                 rc = ENXIO;
12311                 goto bxe_nic_load_error1;
12312             }
12313
12314             /* what did the MCP say? */
12315             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12316                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12317                 sc->state = BXE_STATE_CLOSED;
12318                 rc = ENXIO;
12319                 goto bxe_nic_load_error2;
12320             }
12321         } else {
12322             BLOGI(sc, "Device has no MCP!\n");
12323             load_code = bxe_nic_load_no_mcp(sc);
12324         }
12325
12326         /* mark PMF if applicable */
12327         bxe_nic_load_pmf(sc, load_code);
12328
12329         /* Init Function state controlling object */
12330         bxe_init_func_obj(sc);
12331
12332         /* Initialize HW */
12333         if (bxe_init_hw(sc, load_code) != 0) {
12334             BLOGE(sc, "HW init failed\n");
12335             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12336             sc->state = BXE_STATE_CLOSED;
12337             rc = ENXIO;
12338             goto bxe_nic_load_error2;
12339         }
12340     }
12341
12342     /* set ALWAYS_ALIVE bit in shmem */
12343     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12344     bxe_drv_pulse(sc);
12345     sc->flags |= BXE_NO_PULSE;
12346
12347     /* attach interrupts */
12348     if (bxe_interrupt_attach(sc) != 0) {
12349         sc->state = BXE_STATE_CLOSED;
12350         rc = ENXIO;
12351         goto bxe_nic_load_error2;
12352     }
12353
12354     bxe_nic_init(sc, load_code);
12355
12356     /* Init per-function objects */
12357     if (IS_PF(sc)) {
12358         bxe_init_objs(sc);
12359         // XXX bxe_iov_nic_init(sc);
12360
12361         /* set AFEX default VLAN tag to an invalid value */
12362         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12363         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12364
12365         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12366         rc = bxe_func_start(sc);
12367         if (rc) {
12368             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12369             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12370             sc->state = BXE_STATE_ERROR;
12371             goto bxe_nic_load_error3;
12372         }
12373
12374         /* send LOAD_DONE command to MCP */
12375         if (!BXE_NOMCP(sc)) {
12376             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12377             if (!load_code) {
12378                 BLOGE(sc, "MCP response failure, aborting\n");
12379                 sc->state = BXE_STATE_ERROR;
12380                 rc = ENXIO;
12381                 goto bxe_nic_load_error3;
12382             }
12383         }
12384
12385         rc = bxe_setup_leading(sc);
12386         if (rc) {
12387             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12388             sc->state = BXE_STATE_ERROR;
12389             goto bxe_nic_load_error3;
12390         }
12391
12392         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12393             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12394             if (rc) {
12395                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12396                 sc->state = BXE_STATE_ERROR;
12397                 goto bxe_nic_load_error3;
12398             }
12399         }
12400
12401         rc = bxe_init_rss_pf(sc);
12402         if (rc) {
12403             BLOGE(sc, "PF RSS init failed\n");
12404             sc->state = BXE_STATE_ERROR;
12405             goto bxe_nic_load_error3;
12406         }
12407     }
12408     /* XXX VF */
12409
12410     /* now when Clients are configured we are ready to work */
12411     sc->state = BXE_STATE_OPEN;
12412
12413     /* Configure a ucast MAC */
12414     if (IS_PF(sc)) {
12415         rc = bxe_set_eth_mac(sc, TRUE);
12416     }
12417     if (rc) {
12418         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12419         sc->state = BXE_STATE_ERROR;
12420         goto bxe_nic_load_error3;
12421     }
12422
12423     if (sc->port.pmf) {
12424         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12425         if (rc) {
12426             sc->state = BXE_STATE_ERROR;
12427             goto bxe_nic_load_error3;
12428         }
12429     }
12430
12431     sc->link_params.feature_config_flags &=
12432         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12433
12434     /* start fast path */
12435
12436     /* Initialize Rx filter */
12437     bxe_set_rx_mode(sc);
12438
12439     /* start the Tx */
12440     switch (/* XXX load_mode */LOAD_OPEN) {
12441     case LOAD_NORMAL:
12442     case LOAD_OPEN:
12443         break;
12444
12445     case LOAD_DIAG:
12446     case LOAD_LOOPBACK_EXT:
12447         sc->state = BXE_STATE_DIAG;
12448         break;
12449
12450     default:
12451         break;
12452     }
12453
12454     if (sc->port.pmf) {
12455         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12456     } else {
12457         bxe_link_status_update(sc);
12458     }
12459
12460     /* start the periodic timer callout */
12461     bxe_periodic_start(sc);
12462
12463     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12464         /* mark driver is loaded in shmem2 */
12465         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12466         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12467                   (val |
12468                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12469                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12470     }
12471
12472     /* wait for all pending SP commands to complete */
12473     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12474         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12475         bxe_periodic_stop(sc);
12476         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12477         return (ENXIO);
12478     }
12479
12480     /* Tell the stack the driver is running! */
12481     if_setdrvflags(sc->ifp, IFF_DRV_RUNNING);
12482
12483     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12484
12485     return (0);
12486
12487 bxe_nic_load_error3:
12488
12489     if (IS_PF(sc)) {
12490         bxe_int_disable_sync(sc, 1);
12491
12492         /* clean out queued objects */
12493         bxe_squeeze_objects(sc);
12494     }
12495
12496     bxe_interrupt_detach(sc);
12497
12498 bxe_nic_load_error2:
12499
12500     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12501         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12502         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12503     }
12504
12505     sc->port.pmf = 0;
12506
12507 bxe_nic_load_error1:
12508
12509     /* clear pf_load status, as it was already set */
12510     if (IS_PF(sc)) {
12511         bxe_clear_pf_load(sc);
12512     }
12513
12514 bxe_nic_load_error0:
12515
12516     bxe_free_fw_stats_mem(sc);
12517     bxe_free_fp_buffers(sc);
12518     bxe_free_mem(sc);
12519
12520     return (rc);
12521 }
12522
12523 static int
12524 bxe_init_locked(struct bxe_softc *sc)
12525 {
12526     int other_engine = SC_PATH(sc) ? 0 : 1;
12527     uint8_t other_load_status, load_status;
12528     uint8_t global = FALSE;
12529     int rc;
12530
12531     BXE_CORE_LOCK_ASSERT(sc);
12532
12533     /* check if the driver is already running */
12534     if (if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) {
12535         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12536         return (0);
12537     }
12538
12539     bxe_set_power_state(sc, PCI_PM_D0);
12540
12541     /*
12542      * If parity occurred during the unload, then attentions and/or
12543      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12544      * loaded on the current engine to complete the recovery. Parity recovery
12545      * is only relevant for PF driver.
12546      */
12547     if (IS_PF(sc)) {
12548         other_load_status = bxe_get_load_status(sc, other_engine);
12549         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12550
12551         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12552             bxe_chk_parity_attn(sc, &global, TRUE)) {
12553             do {
12554                 /*
12555                  * If there are attentions and they are in global blocks, set
12556                  * the GLOBAL_RESET bit regardless whether it will be this
12557                  * function that will complete the recovery or not.
12558                  */
12559                 if (global) {
12560                     bxe_set_reset_global(sc);
12561                 }
12562
12563                 /*
12564                  * Only the first function on the current engine should try
12565                  * to recover in open. In case of attentions in global blocks
12566                  * only the first in the chip should try to recover.
12567                  */
12568                 if ((!load_status && (!global || !other_load_status)) &&
12569                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12570                     BLOGI(sc, "Recovered during init\n");
12571                     break;
12572                 }
12573
12574                 /* recovery has failed... */
12575                 bxe_set_power_state(sc, PCI_PM_D3hot);
12576                 sc->recovery_state = BXE_RECOVERY_FAILED;
12577
12578                 BLOGE(sc, "Recovery flow hasn't properly "
12579                           "completed yet, try again later. "
12580                           "If you still see this message after a "
12581                           "few retries then power cycle is required.\n");
12582
12583                 rc = ENXIO;
12584                 goto bxe_init_locked_done;
12585             } while (0);
12586         }
12587     }
12588
12589     sc->recovery_state = BXE_RECOVERY_DONE;
12590
12591     rc = bxe_nic_load(sc, LOAD_OPEN);
12592
12593 bxe_init_locked_done:
12594
12595     if (rc) {
12596         /* Tell the stack the driver is NOT running! */
12597         BLOGE(sc, "Initialization failed, "
12598                   "stack notified driver is NOT running!\n");
12599         if_setdrvflagbits(sc->ifp, 0, IFF_DRV_RUNNING);
12600     }
12601
12602     return (rc);
12603 }
12604
12605 static int
12606 bxe_stop_locked(struct bxe_softc *sc)
12607 {
12608     BXE_CORE_LOCK_ASSERT(sc);
12609     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12610 }
12611
12612 /*
12613  * Handles controller initialization when called from an unlocked routine.
12614  * ifconfig calls this function.
12615  *
12616  * Returns:
12617  *   void
12618  */
12619 static void
12620 bxe_init(void *xsc)
12621 {
12622     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12623
12624     BXE_CORE_LOCK(sc);
12625     bxe_init_locked(sc);
12626     BXE_CORE_UNLOCK(sc);
12627 }
12628
12629 static int
12630 bxe_init_ifnet(struct bxe_softc *sc)
12631 {
12632     if_t ifp;
12633     int capabilities;
12634
12635     /* ifconfig entrypoint for media type/status reporting */
12636     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12637                  bxe_ifmedia_update,
12638                  bxe_ifmedia_status);
12639
12640     /* set the default interface values */
12641     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12642     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12643     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12644
12645     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12646
12647     /* allocate the ifnet structure */
12648     if ((ifp = if_gethandle(IFT_ETHER)) == NULL) {
12649         BLOGE(sc, "Interface allocation failed!\n");
12650         return (ENXIO);
12651     }
12652
12653     if_setsoftc(ifp, sc);
12654     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12655     if_setflags(ifp, (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST));
12656     if_setioctlfn(ifp, bxe_ioctl);
12657     if_setstartfn(ifp, bxe_tx_start);
12658     if_setgetcounterfn(ifp, bxe_get_counter);
12659 #if __FreeBSD_version >= 800000
12660     if_settransmitfn(ifp, bxe_tx_mq_start);
12661     if_setqflushfn(ifp, bxe_mq_flush);
12662 #endif
12663 #ifdef FreeBSD8_0
12664     if_settimer(ifp, 0);
12665 #endif
12666     if_setinitfn(ifp, bxe_init);
12667     if_setmtu(ifp, sc->mtu);
12668     if_sethwassist(ifp, (CSUM_IP      |
12669                         CSUM_TCP      |
12670                         CSUM_UDP      |
12671                         CSUM_TSO      |
12672                         CSUM_TCP_IPV6 |
12673                         CSUM_UDP_IPV6));
12674
12675     capabilities =
12676 #if __FreeBSD_version < 700000
12677         (IFCAP_VLAN_MTU       |
12678          IFCAP_VLAN_HWTAGGING |
12679          IFCAP_HWCSUM         |
12680          IFCAP_JUMBO_MTU      |
12681          IFCAP_LRO);
12682 #else
12683         (IFCAP_VLAN_MTU       |
12684          IFCAP_VLAN_HWTAGGING |
12685          IFCAP_VLAN_HWTSO     |
12686          IFCAP_VLAN_HWFILTER  |
12687          IFCAP_VLAN_HWCSUM    |
12688          IFCAP_HWCSUM         |
12689          IFCAP_JUMBO_MTU      |
12690          IFCAP_LRO            |
12691          IFCAP_TSO4           |
12692          IFCAP_TSO6           |
12693          IFCAP_WOL_MAGIC);
12694 #endif
12695     if_setcapabilitiesbit(ifp, capabilities, 0); /* XXX */
12696     if_setbaudrate(ifp, IF_Gbps(10));
12697 /* XXX */
12698     if_setsendqlen(ifp, sc->tx_ring_size);
12699     if_setsendqready(ifp);
12700 /* XXX */
12701
12702     sc->ifp = ifp;
12703
12704     /* attach to the Ethernet interface list */
12705     ether_ifattach(ifp, sc->link_params.mac_addr);
12706
12707     return (0);
12708 }
12709
12710 static void
12711 bxe_deallocate_bars(struct bxe_softc *sc)
12712 {
12713     int i;
12714
12715     for (i = 0; i < MAX_BARS; i++) {
12716         if (sc->bar[i].resource != NULL) {
12717             bus_release_resource(sc->dev,
12718                                  SYS_RES_MEMORY,
12719                                  sc->bar[i].rid,
12720                                  sc->bar[i].resource);
12721             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12722                   i, PCIR_BAR(i));
12723         }
12724     }
12725 }
12726
12727 static int
12728 bxe_allocate_bars(struct bxe_softc *sc)
12729 {
12730     u_int flags;
12731     int i;
12732
12733     memset(sc->bar, 0, sizeof(sc->bar));
12734
12735     for (i = 0; i < MAX_BARS; i++) {
12736
12737         /* memory resources reside at BARs 0, 2, 4 */
12738         /* Run `pciconf -lb` to see mappings */
12739         if ((i != 0) && (i != 2) && (i != 4)) {
12740             continue;
12741         }
12742
12743         sc->bar[i].rid = PCIR_BAR(i);
12744
12745         flags = RF_ACTIVE;
12746         if (i == 0) {
12747             flags |= RF_SHAREABLE;
12748         }
12749
12750         if ((sc->bar[i].resource =
12751              bus_alloc_resource_any(sc->dev,
12752                                     SYS_RES_MEMORY,
12753                                     &sc->bar[i].rid,
12754                                     flags)) == NULL) {
12755             return (0);
12756         }
12757
12758         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12759         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12760         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12761
12762         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%jd) -> %p\n",
12763               i, PCIR_BAR(i),
12764               (void *)rman_get_start(sc->bar[i].resource),
12765               (void *)rman_get_end(sc->bar[i].resource),
12766               rman_get_size(sc->bar[i].resource),
12767               (void *)sc->bar[i].kva);
12768     }
12769
12770     return (0);
12771 }
12772
12773 static void
12774 bxe_get_function_num(struct bxe_softc *sc)
12775 {
12776     uint32_t val = 0;
12777
12778     /*
12779      * Read the ME register to get the function number. The ME register
12780      * holds the relative-function number and absolute-function number. The
12781      * absolute-function number appears only in E2 and above. Before that
12782      * these bits always contained zero, therefore we cannot blindly use them.
12783      */
12784
12785     val = REG_RD(sc, BAR_ME_REGISTER);
12786
12787     sc->pfunc_rel =
12788         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12789     sc->path_id =
12790         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12791
12792     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12793         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12794     } else {
12795         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12796     }
12797
12798     BLOGD(sc, DBG_LOAD,
12799           "Relative function %d, Absolute function %d, Path %d\n",
12800           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12801 }
12802
12803 static uint32_t
12804 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12805 {
12806     uint32_t shmem2_size;
12807     uint32_t offset;
12808     uint32_t mf_cfg_offset_value;
12809
12810     /* Non 57712 */
12811     offset = (SHMEM_RD(sc, func_mb) +
12812               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12813
12814     /* 57712 plus */
12815     if (sc->devinfo.shmem2_base != 0) {
12816         shmem2_size = SHMEM2_RD(sc, size);
12817         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12818             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12819             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12820                 offset = mf_cfg_offset_value;
12821             }
12822         }
12823     }
12824
12825     return (offset);
12826 }
12827
12828 static uint32_t
12829 bxe_pcie_capability_read(struct bxe_softc *sc,
12830                          int    reg,
12831                          int    width)
12832 {
12833     int pcie_reg;
12834
12835     /* ensure PCIe capability is enabled */
12836     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12837         if (pcie_reg != 0) {
12838             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12839             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12840         }
12841     }
12842
12843     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12844
12845     return (0);
12846 }
12847
12848 static uint8_t
12849 bxe_is_pcie_pending(struct bxe_softc *sc)
12850 {
12851     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12852             PCIM_EXP_STA_TRANSACTION_PND);
12853 }
12854
12855 /*
12856  * Walk the PCI capabiites list for the device to find what features are
12857  * supported. These capabilites may be enabled/disabled by firmware so it's
12858  * best to walk the list rather than make assumptions.
12859  */
12860 static void
12861 bxe_probe_pci_caps(struct bxe_softc *sc)
12862 {
12863     uint16_t link_status;
12864     int reg;
12865
12866     /* check if PCI Power Management is enabled */
12867     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12868         if (reg != 0) {
12869             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12870
12871             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12872             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12873         }
12874     }
12875
12876     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12877
12878     /* handle PCIe 2.0 workarounds for 57710 */
12879     if (CHIP_IS_E1(sc)) {
12880         /* workaround for 57710 errata E4_57710_27462 */
12881         sc->devinfo.pcie_link_speed =
12882             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12883
12884         /* workaround for 57710 errata E4_57710_27488 */
12885         sc->devinfo.pcie_link_width =
12886             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12887         if (sc->devinfo.pcie_link_speed > 1) {
12888             sc->devinfo.pcie_link_width =
12889                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12890         }
12891     } else {
12892         sc->devinfo.pcie_link_speed =
12893             (link_status & PCIM_LINK_STA_SPEED);
12894         sc->devinfo.pcie_link_width =
12895             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12896     }
12897
12898     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12899           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12900
12901     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12902     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12903
12904     /* check if MSI capability is enabled */
12905     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12906         if (reg != 0) {
12907             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
12908
12909             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
12910             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
12911         }
12912     }
12913
12914     /* check if MSI-X capability is enabled */
12915     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
12916         if (reg != 0) {
12917             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
12918
12919             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
12920             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
12921         }
12922     }
12923 }
12924
12925 static int
12926 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
12927 {
12928     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12929     uint32_t val;
12930
12931     /* get the outer vlan if we're in switch-dependent mode */
12932
12933     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
12934     mf_info->ext_id = (uint16_t)val;
12935
12936     mf_info->multi_vnics_mode = 1;
12937
12938     if (!VALID_OVLAN(mf_info->ext_id)) {
12939         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
12940         return (1);
12941     }
12942
12943     /* get the capabilities */
12944     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12945         FUNC_MF_CFG_PROTOCOL_ISCSI) {
12946         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
12947     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12948                FUNC_MF_CFG_PROTOCOL_FCOE) {
12949         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
12950     } else {
12951         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
12952     }
12953
12954     mf_info->vnics_per_port =
12955         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
12956
12957     return (0);
12958 }
12959
12960 static uint32_t
12961 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
12962 {
12963     uint32_t retval = 0;
12964     uint32_t val;
12965
12966     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
12967
12968     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
12969         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
12970             retval |= MF_PROTO_SUPPORT_ETHERNET;
12971         }
12972         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
12973             retval |= MF_PROTO_SUPPORT_ISCSI;
12974         }
12975         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
12976             retval |= MF_PROTO_SUPPORT_FCOE;
12977         }
12978     }
12979
12980     return (retval);
12981 }
12982
12983 static int
12984 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
12985 {
12986     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12987     uint32_t val;
12988
12989     /*
12990      * There is no outer vlan if we're in switch-independent mode.
12991      * If the mac is valid then assume multi-function.
12992      */
12993
12994     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
12995
12996     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
12997
12998     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
12999
13000     mf_info->vnics_per_port =
13001         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13002
13003     return (0);
13004 }
13005
13006 static int
13007 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13008 {
13009     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13010     uint32_t e1hov_tag;
13011     uint32_t func_config;
13012     uint32_t niv_config;
13013
13014     mf_info->multi_vnics_mode = 1;
13015
13016     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13017     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13018     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13019
13020     mf_info->ext_id =
13021         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13022                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13023
13024     mf_info->default_vlan =
13025         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13026                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13027
13028     mf_info->niv_allowed_priorities =
13029         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13030                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13031
13032     mf_info->niv_default_cos =
13033         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13034                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13035
13036     mf_info->afex_vlan_mode =
13037         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13038          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13039
13040     mf_info->niv_mba_enabled =
13041         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13042          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13043
13044     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13045
13046     mf_info->vnics_per_port =
13047         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13048
13049     return (0);
13050 }
13051
13052 static int
13053 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13054 {
13055     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13056     uint32_t mf_cfg1;
13057     uint32_t mf_cfg2;
13058     uint32_t ovlan1;
13059     uint32_t ovlan2;
13060     uint8_t i, j;
13061
13062     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13063           SC_PORT(sc));
13064     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13065           mf_info->mf_config[SC_VN(sc)]);
13066     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13067           mf_info->multi_vnics_mode);
13068     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13069           mf_info->vnics_per_port);
13070     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13071           mf_info->ext_id);
13072     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13073           mf_info->min_bw[0], mf_info->min_bw[1],
13074           mf_info->min_bw[2], mf_info->min_bw[3]);
13075     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13076           mf_info->max_bw[0], mf_info->max_bw[1],
13077           mf_info->max_bw[2], mf_info->max_bw[3]);
13078     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13079           sc->mac_addr_str);
13080
13081     /* various MF mode sanity checks... */
13082
13083     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13084         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13085               SC_PORT(sc));
13086         return (1);
13087     }
13088
13089     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13090         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13091               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13092         return (1);
13093     }
13094
13095     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13096         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13097         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13098             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13099                   SC_VN(sc), OVLAN(sc));
13100             return (1);
13101         }
13102
13103         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13104             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13105                   mf_info->multi_vnics_mode, OVLAN(sc));
13106             return (1);
13107         }
13108
13109         /*
13110          * Verify all functions are either MF or SF mode. If MF, make sure
13111          * sure that all non-hidden functions have a valid ovlan. If SF,
13112          * make sure that all non-hidden functions have an invalid ovlan.
13113          */
13114         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13115             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13116             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13117             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13118                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13119                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13120                 BLOGE(sc, "mf_mode=SD function %d MF config "
13121                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13122                       i, mf_info->multi_vnics_mode, ovlan1);
13123                 return (1);
13124             }
13125         }
13126
13127         /* Verify all funcs on the same port each have a different ovlan. */
13128         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13129             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13130             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13131             /* iterate from the next function on the port to the max func */
13132             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13133                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13134                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13135                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13136                     VALID_OVLAN(ovlan1) &&
13137                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13138                     VALID_OVLAN(ovlan2) &&
13139                     (ovlan1 == ovlan2)) {
13140                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13141                               "have the same ovlan (%d)\n",
13142                           i, j, ovlan1);
13143                     return (1);
13144                 }
13145             }
13146         }
13147     } /* MULTI_FUNCTION_SD */
13148
13149     return (0);
13150 }
13151
13152 static int
13153 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13154 {
13155     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13156     uint32_t val, mac_upper;
13157     uint8_t i, vnic;
13158
13159     /* initialize mf_info defaults */
13160     mf_info->vnics_per_port   = 1;
13161     mf_info->multi_vnics_mode = FALSE;
13162     mf_info->path_has_ovlan   = FALSE;
13163     mf_info->mf_mode          = SINGLE_FUNCTION;
13164
13165     if (!CHIP_IS_MF_CAP(sc)) {
13166         return (0);
13167     }
13168
13169     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13170         BLOGE(sc, "Invalid mf_cfg_base!\n");
13171         return (1);
13172     }
13173
13174     /* get the MF mode (switch dependent / independent / single-function) */
13175
13176     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13177
13178     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13179     {
13180     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13181
13182         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13183
13184         /* check for legal upper mac bytes */
13185         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13186             mf_info->mf_mode = MULTI_FUNCTION_SI;
13187         } else {
13188             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13189         }
13190
13191         break;
13192
13193     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13194     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13195
13196         /* get outer vlan configuration */
13197         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13198
13199         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13200             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13201             mf_info->mf_mode = MULTI_FUNCTION_SD;
13202         } else {
13203             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13204         }
13205
13206         break;
13207
13208     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13209
13210         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13211         return (0);
13212
13213     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13214
13215         /*
13216          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13217          * and the MAC address is valid.
13218          */
13219         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13220
13221         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13222             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13223             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13224         } else {
13225             BLOGE(sc, "Invalid config for AFEX mode\n");
13226         }
13227
13228         break;
13229
13230     default:
13231
13232         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13233               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13234
13235         return (1);
13236     }
13237
13238     /* set path mf_mode (which could be different than function mf_mode) */
13239     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13240         mf_info->path_has_ovlan = TRUE;
13241     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13242         /*
13243          * Decide on path multi vnics mode. If we're not in MF mode and in
13244          * 4-port mode, this is good enough to check vnic-0 of the other port
13245          * on the same path
13246          */
13247         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13248             uint8_t other_port = !(PORT_ID(sc) & 1);
13249             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13250
13251             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13252
13253             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13254         }
13255     }
13256
13257     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13258         /* invalid MF config */
13259         if (SC_VN(sc) >= 1) {
13260             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13261             return (1);
13262         }
13263
13264         return (0);
13265     }
13266
13267     /* get the MF configuration */
13268     mf_info->mf_config[SC_VN(sc)] =
13269         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13270
13271     switch(mf_info->mf_mode)
13272     {
13273     case MULTI_FUNCTION_SD:
13274
13275         bxe_get_shmem_mf_cfg_info_sd(sc);
13276         break;
13277
13278     case MULTI_FUNCTION_SI:
13279
13280         bxe_get_shmem_mf_cfg_info_si(sc);
13281         break;
13282
13283     case MULTI_FUNCTION_AFEX:
13284
13285         bxe_get_shmem_mf_cfg_info_niv(sc);
13286         break;
13287
13288     default:
13289
13290         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13291               mf_info->mf_mode);
13292         return (1);
13293     }
13294
13295     /* get the congestion management parameters */
13296
13297     vnic = 0;
13298     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13299         /* get min/max bw */
13300         val = MFCFG_RD(sc, func_mf_config[i].config);
13301         mf_info->min_bw[vnic] =
13302             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13303         mf_info->max_bw[vnic] =
13304             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13305         vnic++;
13306     }
13307
13308     return (bxe_check_valid_mf_cfg(sc));
13309 }
13310
13311 static int
13312 bxe_get_shmem_info(struct bxe_softc *sc)
13313 {
13314     int port;
13315     uint32_t mac_hi, mac_lo, val;
13316
13317     port = SC_PORT(sc);
13318     mac_hi = mac_lo = 0;
13319
13320     sc->link_params.sc   = sc;
13321     sc->link_params.port = port;
13322
13323     /* get the hardware config info */
13324     sc->devinfo.hw_config =
13325         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13326     sc->devinfo.hw_config2 =
13327         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13328
13329     sc->link_params.hw_led_mode =
13330         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13331          SHARED_HW_CFG_LED_MODE_SHIFT);
13332
13333     /* get the port feature config */
13334     sc->port.config =
13335         SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13336
13337     /* get the link params */
13338     sc->link_params.speed_cap_mask[0] =
13339         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13340     sc->link_params.speed_cap_mask[1] =
13341         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13342
13343     /* get the lane config */
13344     sc->link_params.lane_config =
13345         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13346
13347     /* get the link config */
13348     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13349     sc->port.link_config[ELINK_INT_PHY] = val;
13350     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13351     sc->port.link_config[ELINK_EXT_PHY1] =
13352         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13353
13354     /* get the override preemphasis flag and enable it or turn it off */
13355     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13356     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13357         sc->link_params.feature_config_flags |=
13358             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13359     } else {
13360         sc->link_params.feature_config_flags &=
13361             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13362     }
13363
13364     /* get the initial value of the link params */
13365     sc->link_params.multi_phy_config =
13366         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13367
13368     /* get external phy info */
13369     sc->port.ext_phy_config =
13370         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13371
13372     /* get the multifunction configuration */
13373     bxe_get_mf_cfg_info(sc);
13374
13375     /* get the mac address */
13376     if (IS_MF(sc)) {
13377         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13378         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13379     } else {
13380         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13381         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13382     }
13383
13384     if ((mac_lo == 0) && (mac_hi == 0)) {
13385         *sc->mac_addr_str = 0;
13386         BLOGE(sc, "No Ethernet address programmed!\n");
13387     } else {
13388         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13389         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13390         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13391         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13392         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13393         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13394         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13395                  "%02x:%02x:%02x:%02x:%02x:%02x",
13396                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13397                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13398                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13399         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13400     }
13401
13402     return (0);
13403 }
13404
13405 static void
13406 bxe_get_tunable_params(struct bxe_softc *sc)
13407 {
13408     /* sanity checks */
13409
13410     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13411         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13412         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13413         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13414         bxe_interrupt_mode = INTR_MODE_MSIX;
13415     }
13416
13417     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13418         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13419         bxe_queue_count = 0;
13420     }
13421
13422     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13423         if (bxe_max_rx_bufs == 0) {
13424             bxe_max_rx_bufs = RX_BD_USABLE;
13425         } else {
13426             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13427             bxe_max_rx_bufs = 2048;
13428         }
13429     }
13430
13431     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13432         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13433         bxe_hc_rx_ticks = 25;
13434     }
13435
13436     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13437         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13438         bxe_hc_tx_ticks = 50;
13439     }
13440
13441     if (bxe_max_aggregation_size == 0) {
13442         bxe_max_aggregation_size = TPA_AGG_SIZE;
13443     }
13444
13445     if (bxe_max_aggregation_size > 0xffff) {
13446         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13447               bxe_max_aggregation_size);
13448         bxe_max_aggregation_size = TPA_AGG_SIZE;
13449     }
13450
13451     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13452         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13453         bxe_mrrs = -1;
13454     }
13455
13456     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13457         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13458         bxe_autogreeen = 0;
13459     }
13460
13461     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13462         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13463         bxe_udp_rss = 0;
13464     }
13465
13466     /* pull in user settings */
13467
13468     sc->interrupt_mode       = bxe_interrupt_mode;
13469     sc->max_rx_bufs          = bxe_max_rx_bufs;
13470     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13471     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13472     sc->max_aggregation_size = bxe_max_aggregation_size;
13473     sc->mrrs                 = bxe_mrrs;
13474     sc->autogreeen           = bxe_autogreeen;
13475     sc->udp_rss              = bxe_udp_rss;
13476
13477     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13478         sc->num_queues = 1;
13479     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13480         sc->num_queues =
13481             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13482                 MAX_RSS_CHAINS);
13483         if (sc->num_queues > mp_ncpus) {
13484             sc->num_queues = mp_ncpus;
13485         }
13486     }
13487
13488     BLOGD(sc, DBG_LOAD,
13489           "User Config: "
13490           "debug=0x%lx "
13491           "interrupt_mode=%d "
13492           "queue_count=%d "
13493           "hc_rx_ticks=%d "
13494           "hc_tx_ticks=%d "
13495           "rx_budget=%d "
13496           "max_aggregation_size=%d "
13497           "mrrs=%d "
13498           "autogreeen=%d "
13499           "udp_rss=%d\n",
13500           bxe_debug,
13501           sc->interrupt_mode,
13502           sc->num_queues,
13503           sc->hc_rx_ticks,
13504           sc->hc_tx_ticks,
13505           bxe_rx_budget,
13506           sc->max_aggregation_size,
13507           sc->mrrs,
13508           sc->autogreeen,
13509           sc->udp_rss);
13510 }
13511
13512 static int
13513 bxe_media_detect(struct bxe_softc *sc)
13514 {
13515     int port_type;
13516     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13517
13518     switch (sc->link_params.phy[phy_idx].media_type) {
13519     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13520     case ELINK_ETH_PHY_XFP_FIBER:
13521         BLOGI(sc, "Found 10Gb Fiber media.\n");
13522         sc->media = IFM_10G_SR;
13523         port_type = PORT_FIBRE;
13524         break;
13525     case ELINK_ETH_PHY_SFP_1G_FIBER:
13526         BLOGI(sc, "Found 1Gb Fiber media.\n");
13527         sc->media = IFM_1000_SX;
13528         port_type = PORT_FIBRE;
13529         break;
13530     case ELINK_ETH_PHY_KR:
13531     case ELINK_ETH_PHY_CX4:
13532         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13533         sc->media = IFM_10G_CX4;
13534         port_type = PORT_FIBRE;
13535         break;
13536     case ELINK_ETH_PHY_DA_TWINAX:
13537         BLOGI(sc, "Found 10Gb Twinax media.\n");
13538         sc->media = IFM_10G_TWINAX;
13539         port_type = PORT_DA;
13540         break;
13541     case ELINK_ETH_PHY_BASE_T:
13542         if (sc->link_params.speed_cap_mask[0] &
13543             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13544             BLOGI(sc, "Found 10GBase-T media.\n");
13545             sc->media = IFM_10G_T;
13546             port_type = PORT_TP;
13547         } else {
13548             BLOGI(sc, "Found 1000Base-T media.\n");
13549             sc->media = IFM_1000_T;
13550             port_type = PORT_TP;
13551         }
13552         break;
13553     case ELINK_ETH_PHY_NOT_PRESENT:
13554         BLOGI(sc, "Media not present.\n");
13555         sc->media = 0;
13556         port_type = PORT_OTHER;
13557         break;
13558     case ELINK_ETH_PHY_UNSPECIFIED:
13559     default:
13560         BLOGI(sc, "Unknown media!\n");
13561         sc->media = 0;
13562         port_type = PORT_OTHER;
13563         break;
13564     }
13565     return port_type;
13566 }
13567
13568 #define GET_FIELD(value, fname)                     \
13569     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13570 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13571 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13572
13573 static int
13574 bxe_get_igu_cam_info(struct bxe_softc *sc)
13575 {
13576     int pfid = SC_FUNC(sc);
13577     int igu_sb_id;
13578     uint32_t val;
13579     uint8_t fid, igu_sb_cnt = 0;
13580
13581     sc->igu_base_sb = 0xff;
13582
13583     if (CHIP_INT_MODE_IS_BC(sc)) {
13584         int vn = SC_VN(sc);
13585         igu_sb_cnt = sc->igu_sb_cnt;
13586         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13587                            FP_SB_MAX_E1x);
13588         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13589                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13590         return (0);
13591     }
13592
13593     /* IGU in normal mode - read CAM */
13594     for (igu_sb_id = 0;
13595          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13596          igu_sb_id++) {
13597         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13598         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13599             continue;
13600         }
13601         fid = IGU_FID(val);
13602         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13603             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13604                 continue;
13605             }
13606             if (IGU_VEC(val) == 0) {
13607                 /* default status block */
13608                 sc->igu_dsb_id = igu_sb_id;
13609             } else {
13610                 if (sc->igu_base_sb == 0xff) {
13611                     sc->igu_base_sb = igu_sb_id;
13612                 }
13613                 igu_sb_cnt++;
13614             }
13615         }
13616     }
13617
13618     /*
13619      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13620      * that number of CAM entries will not be equal to the value advertised in
13621      * PCI. Driver should use the minimal value of both as the actual status
13622      * block count
13623      */
13624     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13625
13626     if (igu_sb_cnt == 0) {
13627         BLOGE(sc, "CAM configuration error\n");
13628         return (-1);
13629     }
13630
13631     return (0);
13632 }
13633
13634 /*
13635  * Gather various information from the device config space, the device itself,
13636  * shmem, and the user input.
13637  */
13638 static int
13639 bxe_get_device_info(struct bxe_softc *sc)
13640 {
13641     uint32_t val;
13642     int rc;
13643
13644     /* Get the data for the device */
13645     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13646     sc->devinfo.device_id    = pci_get_device(sc->dev);
13647     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13648     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13649
13650     /* get the chip revision (chip metal comes from pci config space) */
13651     sc->devinfo.chip_id     =
13652     sc->link_params.chip_id =
13653         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13654          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13655          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13656          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13657
13658     /* force 57811 according to MISC register */
13659     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13660         if (CHIP_IS_57810(sc)) {
13661             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13662                                    (sc->devinfo.chip_id & 0x0000ffff));
13663         } else if (CHIP_IS_57810_MF(sc)) {
13664             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13665                                    (sc->devinfo.chip_id & 0x0000ffff));
13666         }
13667         sc->devinfo.chip_id |= 0x1;
13668     }
13669
13670     BLOGD(sc, DBG_LOAD,
13671           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13672           sc->devinfo.chip_id,
13673           ((sc->devinfo.chip_id >> 16) & 0xffff),
13674           ((sc->devinfo.chip_id >> 12) & 0xf),
13675           ((sc->devinfo.chip_id >>  4) & 0xff),
13676           ((sc->devinfo.chip_id >>  0) & 0xf));
13677
13678     val = (REG_RD(sc, 0x2874) & 0x55);
13679     if ((sc->devinfo.chip_id & 0x1) ||
13680         (CHIP_IS_E1(sc) && val) ||
13681         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13682         sc->flags |= BXE_ONE_PORT_FLAG;
13683         BLOGD(sc, DBG_LOAD, "single port device\n");
13684     }
13685
13686     /* set the doorbell size */
13687     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13688
13689     /* determine whether the device is in 2 port or 4 port mode */
13690     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13691     if (CHIP_IS_E2E3(sc)) {
13692         /*
13693          * Read port4mode_en_ovwr[0]:
13694          *   If 1, four port mode is in port4mode_en_ovwr[1].
13695          *   If 0, four port mode is in port4mode_en[0].
13696          */
13697         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13698         if (val & 1) {
13699             val = ((val >> 1) & 1);
13700         } else {
13701             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13702         }
13703
13704         sc->devinfo.chip_port_mode =
13705             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13706
13707         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13708     }
13709
13710     /* get the function and path info for the device */
13711     bxe_get_function_num(sc);
13712
13713     /* get the shared memory base address */
13714     sc->devinfo.shmem_base     =
13715     sc->link_params.shmem_base =
13716         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13717     sc->devinfo.shmem2_base =
13718         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13719                                   MISC_REG_GENERIC_CR_0));
13720
13721     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13722           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13723
13724     if (!sc->devinfo.shmem_base) {
13725         /* this should ONLY prevent upcoming shmem reads */
13726         BLOGI(sc, "MCP not active\n");
13727         sc->flags |= BXE_NO_MCP_FLAG;
13728         return (0);
13729     }
13730
13731     /* make sure the shared memory contents are valid */
13732     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13733     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13734         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13735         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13736         return (0);
13737     }
13738     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13739
13740     /* get the bootcode version */
13741     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13742     snprintf(sc->devinfo.bc_ver_str,
13743              sizeof(sc->devinfo.bc_ver_str),
13744              "%d.%d.%d",
13745              ((sc->devinfo.bc_ver >> 24) & 0xff),
13746              ((sc->devinfo.bc_ver >> 16) & 0xff),
13747              ((sc->devinfo.bc_ver >>  8) & 0xff));
13748     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13749
13750     /* get the bootcode shmem address */
13751     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13752     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13753
13754     /* clean indirect addresses as they're not used */
13755     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13756     if (IS_PF(sc)) {
13757         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13758         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13759         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13760         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13761         if (CHIP_IS_E1x(sc)) {
13762             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13763             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13764             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13765             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13766         }
13767
13768         /*
13769          * Enable internal target-read (in case we are probed after PF
13770          * FLR). Must be done prior to any BAR read access. Only for
13771          * 57712 and up
13772          */
13773         if (!CHIP_IS_E1x(sc)) {
13774             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13775         }
13776     }
13777
13778     /* get the nvram size */
13779     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13780     sc->devinfo.flash_size =
13781         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13782     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13783
13784     /* get PCI capabilites */
13785     bxe_probe_pci_caps(sc);
13786
13787     bxe_set_power_state(sc, PCI_PM_D0);
13788
13789     /* get various configuration parameters from shmem */
13790     bxe_get_shmem_info(sc);
13791
13792     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13793         val = pci_read_config(sc->dev,
13794                               (sc->devinfo.pcie_msix_cap_reg +
13795                                PCIR_MSIX_CTRL),
13796                               2);
13797         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13798     } else {
13799         sc->igu_sb_cnt = 1;
13800     }
13801
13802     sc->igu_base_addr = BAR_IGU_INTMEM;
13803
13804     /* initialize IGU parameters */
13805     if (CHIP_IS_E1x(sc)) {
13806         sc->devinfo.int_block = INT_BLOCK_HC;
13807         sc->igu_dsb_id = DEF_SB_IGU_ID;
13808         sc->igu_base_sb = 0;
13809     } else {
13810         sc->devinfo.int_block = INT_BLOCK_IGU;
13811
13812         /* do not allow device reset during IGU info preocessing */
13813         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13814
13815         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13816
13817         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13818             int tout = 5000;
13819
13820             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13821
13822             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13823             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13824             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13825
13826             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13827                 tout--;
13828                 DELAY(1000);
13829             }
13830
13831             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13832                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13833                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13834                 return (-1);
13835             }
13836         }
13837
13838         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13839             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13840             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13841         } else {
13842             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13843         }
13844
13845         rc = bxe_get_igu_cam_info(sc);
13846
13847         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13848
13849         if (rc) {
13850             return (rc);
13851         }
13852     }
13853
13854     /*
13855      * Get base FW non-default (fast path) status block ID. This value is
13856      * used to initialize the fw_sb_id saved on the fp/queue structure to
13857      * determine the id used by the FW.
13858      */
13859     if (CHIP_IS_E1x(sc)) {
13860         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13861     } else {
13862         /*
13863          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13864          * the same queue are indicated on the same IGU SB). So we prefer
13865          * FW and IGU SBs to be the same value.
13866          */
13867         sc->base_fw_ndsb = sc->igu_base_sb;
13868     }
13869
13870     BLOGD(sc, DBG_LOAD,
13871           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13872           sc->igu_dsb_id, sc->igu_base_sb,
13873           sc->igu_sb_cnt, sc->base_fw_ndsb);
13874
13875     elink_phy_probe(&sc->link_params);
13876
13877     return (0);
13878 }
13879
13880 static void
13881 bxe_link_settings_supported(struct bxe_softc *sc,
13882                             uint32_t         switch_cfg)
13883 {
13884     uint32_t cfg_size = 0;
13885     uint32_t idx;
13886     uint8_t port = SC_PORT(sc);
13887
13888     /* aggregation of supported attributes of all external phys */
13889     sc->port.supported[0] = 0;
13890     sc->port.supported[1] = 0;
13891
13892     switch (sc->link_params.num_phys) {
13893     case 1:
13894         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13895         cfg_size = 1;
13896         break;
13897     case 2:
13898         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13899         cfg_size = 1;
13900         break;
13901     case 3:
13902         if (sc->link_params.multi_phy_config &
13903             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13904             sc->port.supported[1] =
13905                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13906             sc->port.supported[0] =
13907                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13908         } else {
13909             sc->port.supported[0] =
13910                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13911             sc->port.supported[1] =
13912                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13913         }
13914         cfg_size = 2;
13915         break;
13916     }
13917
13918     if (!(sc->port.supported[0] || sc->port.supported[1])) {
13919         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
13920               SHMEM_RD(sc,
13921                        dev_info.port_hw_config[port].external_phy_config),
13922               SHMEM_RD(sc,
13923                        dev_info.port_hw_config[port].external_phy_config2));
13924         return;
13925     }
13926
13927     if (CHIP_IS_E3(sc))
13928         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
13929     else {
13930         switch (switch_cfg) {
13931         case ELINK_SWITCH_CFG_1G:
13932             sc->port.phy_addr =
13933                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
13934             break;
13935         case ELINK_SWITCH_CFG_10G:
13936             sc->port.phy_addr =
13937                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
13938             break;
13939         default:
13940             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
13941                   sc->port.link_config[0]);
13942             return;
13943         }
13944     }
13945
13946     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
13947
13948     /* mask what we support according to speed_cap_mask per configuration */
13949     for (idx = 0; idx < cfg_size; idx++) {
13950         if (!(sc->link_params.speed_cap_mask[idx] &
13951               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
13952             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
13953         }
13954
13955         if (!(sc->link_params.speed_cap_mask[idx] &
13956               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
13957             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
13958         }
13959
13960         if (!(sc->link_params.speed_cap_mask[idx] &
13961               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
13962             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
13963         }
13964
13965         if (!(sc->link_params.speed_cap_mask[idx] &
13966               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
13967             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
13968         }
13969
13970         if (!(sc->link_params.speed_cap_mask[idx] &
13971               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
13972             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
13973         }
13974
13975         if (!(sc->link_params.speed_cap_mask[idx] &
13976               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
13977             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
13978         }
13979
13980         if (!(sc->link_params.speed_cap_mask[idx] &
13981               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
13982             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
13983         }
13984
13985         if (!(sc->link_params.speed_cap_mask[idx] &
13986               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
13987             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
13988         }
13989     }
13990
13991     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
13992           sc->port.supported[0], sc->port.supported[1]);
13993 }
13994
13995 static void
13996 bxe_link_settings_requested(struct bxe_softc *sc)
13997 {
13998     uint32_t link_config;
13999     uint32_t idx;
14000     uint32_t cfg_size = 0;
14001
14002     sc->port.advertising[0] = 0;
14003     sc->port.advertising[1] = 0;
14004
14005     switch (sc->link_params.num_phys) {
14006     case 1:
14007     case 2:
14008         cfg_size = 1;
14009         break;
14010     case 3:
14011         cfg_size = 2;
14012         break;
14013     }
14014
14015     for (idx = 0; idx < cfg_size; idx++) {
14016         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14017         link_config = sc->port.link_config[idx];
14018
14019         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14020         case PORT_FEATURE_LINK_SPEED_AUTO:
14021             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14022                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14023                 sc->port.advertising[idx] |= sc->port.supported[idx];
14024                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14025                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14026                     sc->port.advertising[idx] |=
14027                         (ELINK_SUPPORTED_100baseT_Half |
14028                          ELINK_SUPPORTED_100baseT_Full);
14029             } else {
14030                 /* force 10G, no AN */
14031                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14032                 sc->port.advertising[idx] |=
14033                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14034                 continue;
14035             }
14036             break;
14037
14038         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14039             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14040                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14041                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14042                                               ADVERTISED_TP);
14043             } else {
14044                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14045                           "speed_cap_mask=0x%08x\n",
14046                       link_config, sc->link_params.speed_cap_mask[idx]);
14047                 return;
14048             }
14049             break;
14050
14051         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14052             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14053                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14054                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14055                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14056                                               ADVERTISED_TP);
14057             } else {
14058                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14059                           "speed_cap_mask=0x%08x\n",
14060                       link_config, sc->link_params.speed_cap_mask[idx]);
14061                 return;
14062             }
14063             break;
14064
14065         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14066             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14067                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14068                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14069                                               ADVERTISED_TP);
14070             } else {
14071                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14072                           "speed_cap_mask=0x%08x\n",
14073                       link_config, sc->link_params.speed_cap_mask[idx]);
14074                 return;
14075             }
14076             break;
14077
14078         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14079             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14080                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14081                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14082                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14083                                               ADVERTISED_TP);
14084             } else {
14085                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14086                           "speed_cap_mask=0x%08x\n",
14087                       link_config, sc->link_params.speed_cap_mask[idx]);
14088                 return;
14089             }
14090             break;
14091
14092         case PORT_FEATURE_LINK_SPEED_1G:
14093             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14094                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14095                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14096                                               ADVERTISED_TP);
14097             } else {
14098                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14099                           "speed_cap_mask=0x%08x\n",
14100                       link_config, sc->link_params.speed_cap_mask[idx]);
14101                 return;
14102             }
14103             break;
14104
14105         case PORT_FEATURE_LINK_SPEED_2_5G:
14106             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14107                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14108                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14109                                               ADVERTISED_TP);
14110             } else {
14111                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14112                           "speed_cap_mask=0x%08x\n",
14113                       link_config, sc->link_params.speed_cap_mask[idx]);
14114                 return;
14115             }
14116             break;
14117
14118         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14119             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14120                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14121                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14122                                               ADVERTISED_FIBRE);
14123             } else {
14124                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14125                           "speed_cap_mask=0x%08x\n",
14126                       link_config, sc->link_params.speed_cap_mask[idx]);
14127                 return;
14128             }
14129             break;
14130
14131         case PORT_FEATURE_LINK_SPEED_20G:
14132             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14133             break;
14134
14135         default:
14136             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14137                       "speed_cap_mask=0x%08x\n",
14138                   link_config, sc->link_params.speed_cap_mask[idx]);
14139             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14140             sc->port.advertising[idx] = sc->port.supported[idx];
14141             break;
14142         }
14143
14144         sc->link_params.req_flow_ctrl[idx] =
14145             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14146
14147         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14148             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14149                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14150             } else {
14151                 bxe_set_requested_fc(sc);
14152             }
14153         }
14154
14155         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14156                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14157               sc->link_params.req_line_speed[idx],
14158               sc->link_params.req_duplex[idx],
14159               sc->link_params.req_flow_ctrl[idx],
14160               sc->port.advertising[idx]);
14161     }
14162 }
14163
14164 static void
14165 bxe_get_phy_info(struct bxe_softc *sc)
14166 {
14167     uint8_t port = SC_PORT(sc);
14168     uint32_t config = sc->port.config;
14169     uint32_t eee_mode;
14170
14171     /* shmem data already read in bxe_get_shmem_info() */
14172
14173     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14174                         "link_config0=0x%08x\n",
14175                sc->link_params.lane_config,
14176                sc->link_params.speed_cap_mask[0],
14177                sc->port.link_config[0]);
14178
14179     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14180     bxe_link_settings_requested(sc);
14181
14182     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14183         sc->link_params.feature_config_flags |=
14184             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14185     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14186         sc->link_params.feature_config_flags &=
14187             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14188     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14189         sc->link_params.feature_config_flags |=
14190             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14191     }
14192
14193     /* configure link feature according to nvram value */
14194     eee_mode =
14195         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14196           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14197          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14198     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14199         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14200                                     ELINK_EEE_MODE_ENABLE_LPI |
14201                                     ELINK_EEE_MODE_OUTPUT_TIME);
14202     } else {
14203         sc->link_params.eee_mode = 0;
14204     }
14205
14206     /* get the media type */
14207     bxe_media_detect(sc);
14208 }
14209
14210 static void
14211 bxe_get_params(struct bxe_softc *sc)
14212 {
14213     /* get user tunable params */
14214     bxe_get_tunable_params(sc);
14215
14216     /* select the RX and TX ring sizes */
14217     sc->tx_ring_size = TX_BD_USABLE;
14218     sc->rx_ring_size = RX_BD_USABLE;
14219
14220     /* XXX disable WoL */
14221     sc->wol = 0;
14222 }
14223
14224 static void
14225 bxe_set_modes_bitmap(struct bxe_softc *sc)
14226 {
14227     uint32_t flags = 0;
14228
14229     if (CHIP_REV_IS_FPGA(sc)) {
14230         SET_FLAGS(flags, MODE_FPGA);
14231     } else if (CHIP_REV_IS_EMUL(sc)) {
14232         SET_FLAGS(flags, MODE_EMUL);
14233     } else {
14234         SET_FLAGS(flags, MODE_ASIC);
14235     }
14236
14237     if (CHIP_IS_MODE_4_PORT(sc)) {
14238         SET_FLAGS(flags, MODE_PORT4);
14239     } else {
14240         SET_FLAGS(flags, MODE_PORT2);
14241     }
14242
14243     if (CHIP_IS_E2(sc)) {
14244         SET_FLAGS(flags, MODE_E2);
14245     } else if (CHIP_IS_E3(sc)) {
14246         SET_FLAGS(flags, MODE_E3);
14247         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14248             SET_FLAGS(flags, MODE_E3_A0);
14249         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14250             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14251         }
14252     }
14253
14254     if (IS_MF(sc)) {
14255         SET_FLAGS(flags, MODE_MF);
14256         switch (sc->devinfo.mf_info.mf_mode) {
14257         case MULTI_FUNCTION_SD:
14258             SET_FLAGS(flags, MODE_MF_SD);
14259             break;
14260         case MULTI_FUNCTION_SI:
14261             SET_FLAGS(flags, MODE_MF_SI);
14262             break;
14263         case MULTI_FUNCTION_AFEX:
14264             SET_FLAGS(flags, MODE_MF_AFEX);
14265             break;
14266         }
14267     } else {
14268         SET_FLAGS(flags, MODE_SF);
14269     }
14270
14271 #if defined(__LITTLE_ENDIAN)
14272     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14273 #else /* __BIG_ENDIAN */
14274     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14275 #endif
14276
14277     INIT_MODE_FLAGS(sc) = flags;
14278 }
14279
14280 static int
14281 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14282 {
14283     struct bxe_fastpath *fp;
14284     bus_addr_t busaddr;
14285     int max_agg_queues;
14286     int max_segments;
14287     bus_size_t max_size;
14288     bus_size_t max_seg_size;
14289     char buf[32];
14290     int rc;
14291     int i, j;
14292
14293     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14294
14295     /* allocate the parent bus DMA tag */
14296     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14297                             1,                        /* alignment */
14298                             0,                        /* boundary limit */
14299                             BUS_SPACE_MAXADDR,        /* restricted low */
14300                             BUS_SPACE_MAXADDR,        /* restricted hi */
14301                             NULL,                     /* addr filter() */
14302                             NULL,                     /* addr filter() arg */
14303                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14304                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14305                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14306                             0,                        /* flags */
14307                             NULL,                     /* lock() */
14308                             NULL,                     /* lock() arg */
14309                             &sc->parent_dma_tag);     /* returned dma tag */
14310     if (rc != 0) {
14311         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14312         return (1);
14313     }
14314
14315     /************************/
14316     /* DEFAULT STATUS BLOCK */
14317     /************************/
14318
14319     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14320                       &sc->def_sb_dma, "default status block") != 0) {
14321         /* XXX */
14322         bus_dma_tag_destroy(sc->parent_dma_tag);
14323         return (1);
14324     }
14325
14326     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14327
14328     /***************/
14329     /* EVENT QUEUE */
14330     /***************/
14331
14332     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14333                       &sc->eq_dma, "event queue") != 0) {
14334         /* XXX */
14335         bxe_dma_free(sc, &sc->def_sb_dma);
14336         sc->def_sb = NULL;
14337         bus_dma_tag_destroy(sc->parent_dma_tag);
14338         return (1);
14339     }
14340
14341     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14342
14343     /*************/
14344     /* SLOW PATH */
14345     /*************/
14346
14347     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14348                       &sc->sp_dma, "slow path") != 0) {
14349         /* XXX */
14350         bxe_dma_free(sc, &sc->eq_dma);
14351         sc->eq = NULL;
14352         bxe_dma_free(sc, &sc->def_sb_dma);
14353         sc->def_sb = NULL;
14354         bus_dma_tag_destroy(sc->parent_dma_tag);
14355         return (1);
14356     }
14357
14358     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14359
14360     /*******************/
14361     /* SLOW PATH QUEUE */
14362     /*******************/
14363
14364     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14365                       &sc->spq_dma, "slow path queue") != 0) {
14366         /* XXX */
14367         bxe_dma_free(sc, &sc->sp_dma);
14368         sc->sp = NULL;
14369         bxe_dma_free(sc, &sc->eq_dma);
14370         sc->eq = NULL;
14371         bxe_dma_free(sc, &sc->def_sb_dma);
14372         sc->def_sb = NULL;
14373         bus_dma_tag_destroy(sc->parent_dma_tag);
14374         return (1);
14375     }
14376
14377     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14378
14379     /***************************/
14380     /* FW DECOMPRESSION BUFFER */
14381     /***************************/
14382
14383     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14384                       "fw decompression buffer") != 0) {
14385         /* XXX */
14386         bxe_dma_free(sc, &sc->spq_dma);
14387         sc->spq = NULL;
14388         bxe_dma_free(sc, &sc->sp_dma);
14389         sc->sp = NULL;
14390         bxe_dma_free(sc, &sc->eq_dma);
14391         sc->eq = NULL;
14392         bxe_dma_free(sc, &sc->def_sb_dma);
14393         sc->def_sb = NULL;
14394         bus_dma_tag_destroy(sc->parent_dma_tag);
14395         return (1);
14396     }
14397
14398     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14399
14400     if ((sc->gz_strm =
14401          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14402         /* XXX */
14403         bxe_dma_free(sc, &sc->gz_buf_dma);
14404         sc->gz_buf = NULL;
14405         bxe_dma_free(sc, &sc->spq_dma);
14406         sc->spq = NULL;
14407         bxe_dma_free(sc, &sc->sp_dma);
14408         sc->sp = NULL;
14409         bxe_dma_free(sc, &sc->eq_dma);
14410         sc->eq = NULL;
14411         bxe_dma_free(sc, &sc->def_sb_dma);
14412         sc->def_sb = NULL;
14413         bus_dma_tag_destroy(sc->parent_dma_tag);
14414         return (1);
14415     }
14416
14417     /*************/
14418     /* FASTPATHS */
14419     /*************/
14420
14421     /* allocate DMA memory for each fastpath structure */
14422     for (i = 0; i < sc->num_queues; i++) {
14423         fp = &sc->fp[i];
14424         fp->sc    = sc;
14425         fp->index = i;
14426
14427         /*******************/
14428         /* FP STATUS BLOCK */
14429         /*******************/
14430
14431         snprintf(buf, sizeof(buf), "fp %d status block", i);
14432         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14433                           &fp->sb_dma, buf) != 0) {
14434             /* XXX unwind and free previous fastpath allocations */
14435             BLOGE(sc, "Failed to alloc %s\n", buf);
14436             return (1);
14437         } else {
14438             if (CHIP_IS_E2E3(sc)) {
14439                 fp->status_block.e2_sb =
14440                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14441             } else {
14442                 fp->status_block.e1x_sb =
14443                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14444             }
14445         }
14446
14447         /******************/
14448         /* FP TX BD CHAIN */
14449         /******************/
14450
14451         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14452         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14453                           &fp->tx_dma, buf) != 0) {
14454             /* XXX unwind and free previous fastpath allocations */
14455             BLOGE(sc, "Failed to alloc %s\n", buf);
14456             return (1);
14457         } else {
14458             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14459         }
14460
14461         /* link together the tx bd chain pages */
14462         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14463             /* index into the tx bd chain array to last entry per page */
14464             struct eth_tx_next_bd *tx_next_bd =
14465                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14466             /* point to the next page and wrap from last page */
14467             busaddr = (fp->tx_dma.paddr +
14468                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14469             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14470             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14471         }
14472
14473         /******************/
14474         /* FP RX BD CHAIN */
14475         /******************/
14476
14477         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14478         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14479                           &fp->rx_dma, buf) != 0) {
14480             /* XXX unwind and free previous fastpath allocations */
14481             BLOGE(sc, "Failed to alloc %s\n", buf);
14482             return (1);
14483         } else {
14484             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14485         }
14486
14487         /* link together the rx bd chain pages */
14488         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14489             /* index into the rx bd chain array to last entry per page */
14490             struct eth_rx_bd *rx_bd =
14491                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14492             /* point to the next page and wrap from last page */
14493             busaddr = (fp->rx_dma.paddr +
14494                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14495             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14496             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14497         }
14498
14499         /*******************/
14500         /* FP RX RCQ CHAIN */
14501         /*******************/
14502
14503         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14504         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14505                           &fp->rcq_dma, buf) != 0) {
14506             /* XXX unwind and free previous fastpath allocations */
14507             BLOGE(sc, "Failed to alloc %s\n", buf);
14508             return (1);
14509         } else {
14510             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14511         }
14512
14513         /* link together the rcq chain pages */
14514         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14515             /* index into the rcq chain array to last entry per page */
14516             struct eth_rx_cqe_next_page *rx_cqe_next =
14517                 (struct eth_rx_cqe_next_page *)
14518                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14519             /* point to the next page and wrap from last page */
14520             busaddr = (fp->rcq_dma.paddr +
14521                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14522             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14523             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14524         }
14525
14526         /*******************/
14527         /* FP RX SGE CHAIN */
14528         /*******************/
14529
14530         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14531         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14532                           &fp->rx_sge_dma, buf) != 0) {
14533             /* XXX unwind and free previous fastpath allocations */
14534             BLOGE(sc, "Failed to alloc %s\n", buf);
14535             return (1);
14536         } else {
14537             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14538         }
14539
14540         /* link together the sge chain pages */
14541         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14542             /* index into the rcq chain array to last entry per page */
14543             struct eth_rx_sge *rx_sge =
14544                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14545             /* point to the next page and wrap from last page */
14546             busaddr = (fp->rx_sge_dma.paddr +
14547                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14548             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14549             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14550         }
14551
14552         /***********************/
14553         /* FP TX MBUF DMA MAPS */
14554         /***********************/
14555
14556         /* set required sizes before mapping to conserve resources */
14557         if (if_getcapenable(sc->ifp) & (IFCAP_TSO4 | IFCAP_TSO6)) {
14558             max_size     = BXE_TSO_MAX_SIZE;
14559             max_segments = BXE_TSO_MAX_SEGMENTS;
14560             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14561         } else {
14562             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14563             max_segments = BXE_MAX_SEGMENTS;
14564             max_seg_size = MCLBYTES;
14565         }
14566
14567         /* create a dma tag for the tx mbufs */
14568         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14569                                 1,                  /* alignment */
14570                                 0,                  /* boundary limit */
14571                                 BUS_SPACE_MAXADDR,  /* restricted low */
14572                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14573                                 NULL,               /* addr filter() */
14574                                 NULL,               /* addr filter() arg */
14575                                 max_size,           /* max map size */
14576                                 max_segments,       /* num discontinuous */
14577                                 max_seg_size,       /* max seg size */
14578                                 0,                  /* flags */
14579                                 NULL,               /* lock() */
14580                                 NULL,               /* lock() arg */
14581                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14582         if (rc != 0) {
14583             /* XXX unwind and free previous fastpath allocations */
14584             BLOGE(sc, "Failed to create dma tag for "
14585                       "'fp %d tx mbufs' (%d)\n", i, rc);
14586             return (1);
14587         }
14588
14589         /* create dma maps for each of the tx mbuf clusters */
14590         for (j = 0; j < TX_BD_TOTAL; j++) {
14591             if (bus_dmamap_create(fp->tx_mbuf_tag,
14592                                   BUS_DMA_NOWAIT,
14593                                   &fp->tx_mbuf_chain[j].m_map)) {
14594                 /* XXX unwind and free previous fastpath allocations */
14595                 BLOGE(sc, "Failed to create dma map for "
14596                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14597                 return (1);
14598             }
14599         }
14600
14601         /***********************/
14602         /* FP RX MBUF DMA MAPS */
14603         /***********************/
14604
14605         /* create a dma tag for the rx mbufs */
14606         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14607                                 1,                  /* alignment */
14608                                 0,                  /* boundary limit */
14609                                 BUS_SPACE_MAXADDR,  /* restricted low */
14610                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14611                                 NULL,               /* addr filter() */
14612                                 NULL,               /* addr filter() arg */
14613                                 MJUM9BYTES,         /* max map size */
14614                                 1,                  /* num discontinuous */
14615                                 MJUM9BYTES,         /* max seg size */
14616                                 0,                  /* flags */
14617                                 NULL,               /* lock() */
14618                                 NULL,               /* lock() arg */
14619                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14620         if (rc != 0) {
14621             /* XXX unwind and free previous fastpath allocations */
14622             BLOGE(sc, "Failed to create dma tag for "
14623                       "'fp %d rx mbufs' (%d)\n", i, rc);
14624             return (1);
14625         }
14626
14627         /* create dma maps for each of the rx mbuf clusters */
14628         for (j = 0; j < RX_BD_TOTAL; j++) {
14629             if (bus_dmamap_create(fp->rx_mbuf_tag,
14630                                   BUS_DMA_NOWAIT,
14631                                   &fp->rx_mbuf_chain[j].m_map)) {
14632                 /* XXX unwind and free previous fastpath allocations */
14633                 BLOGE(sc, "Failed to create dma map for "
14634                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14635                 return (1);
14636             }
14637         }
14638
14639         /* create dma map for the spare rx mbuf cluster */
14640         if (bus_dmamap_create(fp->rx_mbuf_tag,
14641                               BUS_DMA_NOWAIT,
14642                               &fp->rx_mbuf_spare_map)) {
14643             /* XXX unwind and free previous fastpath allocations */
14644             BLOGE(sc, "Failed to create dma map for "
14645                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14646             return (1);
14647         }
14648
14649         /***************************/
14650         /* FP RX SGE MBUF DMA MAPS */
14651         /***************************/
14652
14653         /* create a dma tag for the rx sge mbufs */
14654         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14655                                 1,                  /* alignment */
14656                                 0,                  /* boundary limit */
14657                                 BUS_SPACE_MAXADDR,  /* restricted low */
14658                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14659                                 NULL,               /* addr filter() */
14660                                 NULL,               /* addr filter() arg */
14661                                 BCM_PAGE_SIZE,      /* max map size */
14662                                 1,                  /* num discontinuous */
14663                                 BCM_PAGE_SIZE,      /* max seg size */
14664                                 0,                  /* flags */
14665                                 NULL,               /* lock() */
14666                                 NULL,               /* lock() arg */
14667                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14668         if (rc != 0) {
14669             /* XXX unwind and free previous fastpath allocations */
14670             BLOGE(sc, "Failed to create dma tag for "
14671                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14672             return (1);
14673         }
14674
14675         /* create dma maps for the rx sge mbuf clusters */
14676         for (j = 0; j < RX_SGE_TOTAL; j++) {
14677             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14678                                   BUS_DMA_NOWAIT,
14679                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14680                 /* XXX unwind and free previous fastpath allocations */
14681                 BLOGE(sc, "Failed to create dma map for "
14682                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14683                 return (1);
14684             }
14685         }
14686
14687         /* create dma map for the spare rx sge mbuf cluster */
14688         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14689                               BUS_DMA_NOWAIT,
14690                               &fp->rx_sge_mbuf_spare_map)) {
14691             /* XXX unwind and free previous fastpath allocations */
14692             BLOGE(sc, "Failed to create dma map for "
14693                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14694             return (1);
14695         }
14696
14697         /***************************/
14698         /* FP RX TPA MBUF DMA MAPS */
14699         /***************************/
14700
14701         /* create dma maps for the rx tpa mbuf clusters */
14702         max_agg_queues = MAX_AGG_QS(sc);
14703
14704         for (j = 0; j < max_agg_queues; j++) {
14705             if (bus_dmamap_create(fp->rx_mbuf_tag,
14706                                   BUS_DMA_NOWAIT,
14707                                   &fp->rx_tpa_info[j].bd.m_map)) {
14708                 /* XXX unwind and free previous fastpath allocations */
14709                 BLOGE(sc, "Failed to create dma map for "
14710                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14711                 return (1);
14712             }
14713         }
14714
14715         /* create dma map for the spare rx tpa mbuf cluster */
14716         if (bus_dmamap_create(fp->rx_mbuf_tag,
14717                               BUS_DMA_NOWAIT,
14718                               &fp->rx_tpa_info_mbuf_spare_map)) {
14719             /* XXX unwind and free previous fastpath allocations */
14720             BLOGE(sc, "Failed to create dma map for "
14721                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14722             return (1);
14723         }
14724
14725         bxe_init_sge_ring_bit_mask(fp);
14726     }
14727
14728     return (0);
14729 }
14730
14731 static void
14732 bxe_free_hsi_mem(struct bxe_softc *sc)
14733 {
14734     struct bxe_fastpath *fp;
14735     int max_agg_queues;
14736     int i, j;
14737
14738     if (sc->parent_dma_tag == NULL) {
14739         return; /* assume nothing was allocated */
14740     }
14741
14742     for (i = 0; i < sc->num_queues; i++) {
14743         fp = &sc->fp[i];
14744
14745         /*******************/
14746         /* FP STATUS BLOCK */
14747         /*******************/
14748
14749         bxe_dma_free(sc, &fp->sb_dma);
14750         memset(&fp->status_block, 0, sizeof(fp->status_block));
14751
14752         /******************/
14753         /* FP TX BD CHAIN */
14754         /******************/
14755
14756         bxe_dma_free(sc, &fp->tx_dma);
14757         fp->tx_chain = NULL;
14758
14759         /******************/
14760         /* FP RX BD CHAIN */
14761         /******************/
14762
14763         bxe_dma_free(sc, &fp->rx_dma);
14764         fp->rx_chain = NULL;
14765
14766         /*******************/
14767         /* FP RX RCQ CHAIN */
14768         /*******************/
14769
14770         bxe_dma_free(sc, &fp->rcq_dma);
14771         fp->rcq_chain = NULL;
14772
14773         /*******************/
14774         /* FP RX SGE CHAIN */
14775         /*******************/
14776
14777         bxe_dma_free(sc, &fp->rx_sge_dma);
14778         fp->rx_sge_chain = NULL;
14779
14780         /***********************/
14781         /* FP TX MBUF DMA MAPS */
14782         /***********************/
14783
14784         if (fp->tx_mbuf_tag != NULL) {
14785             for (j = 0; j < TX_BD_TOTAL; j++) {
14786                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14787                     bus_dmamap_unload(fp->tx_mbuf_tag,
14788                                       fp->tx_mbuf_chain[j].m_map);
14789                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14790                                        fp->tx_mbuf_chain[j].m_map);
14791                 }
14792             }
14793
14794             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14795             fp->tx_mbuf_tag = NULL;
14796         }
14797
14798         /***********************/
14799         /* FP RX MBUF DMA MAPS */
14800         /***********************/
14801
14802         if (fp->rx_mbuf_tag != NULL) {
14803             for (j = 0; j < RX_BD_TOTAL; j++) {
14804                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14805                     bus_dmamap_unload(fp->rx_mbuf_tag,
14806                                       fp->rx_mbuf_chain[j].m_map);
14807                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14808                                        fp->rx_mbuf_chain[j].m_map);
14809                 }
14810             }
14811
14812             if (fp->rx_mbuf_spare_map != NULL) {
14813                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14814                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14815             }
14816
14817             /***************************/
14818             /* FP RX TPA MBUF DMA MAPS */
14819             /***************************/
14820
14821             max_agg_queues = MAX_AGG_QS(sc);
14822
14823             for (j = 0; j < max_agg_queues; j++) {
14824                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14825                     bus_dmamap_unload(fp->rx_mbuf_tag,
14826                                       fp->rx_tpa_info[j].bd.m_map);
14827                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14828                                        fp->rx_tpa_info[j].bd.m_map);
14829                 }
14830             }
14831
14832             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14833                 bus_dmamap_unload(fp->rx_mbuf_tag,
14834                                   fp->rx_tpa_info_mbuf_spare_map);
14835                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14836                                    fp->rx_tpa_info_mbuf_spare_map);
14837             }
14838
14839             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14840             fp->rx_mbuf_tag = NULL;
14841         }
14842
14843         /***************************/
14844         /* FP RX SGE MBUF DMA MAPS */
14845         /***************************/
14846
14847         if (fp->rx_sge_mbuf_tag != NULL) {
14848             for (j = 0; j < RX_SGE_TOTAL; j++) {
14849                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14850                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14851                                       fp->rx_sge_mbuf_chain[j].m_map);
14852                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14853                                        fp->rx_sge_mbuf_chain[j].m_map);
14854                 }
14855             }
14856
14857             if (fp->rx_sge_mbuf_spare_map != NULL) {
14858                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14859                                   fp->rx_sge_mbuf_spare_map);
14860                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14861                                    fp->rx_sge_mbuf_spare_map);
14862             }
14863
14864             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14865             fp->rx_sge_mbuf_tag = NULL;
14866         }
14867     }
14868
14869     /***************************/
14870     /* FW DECOMPRESSION BUFFER */
14871     /***************************/
14872
14873     bxe_dma_free(sc, &sc->gz_buf_dma);
14874     sc->gz_buf = NULL;
14875     free(sc->gz_strm, M_DEVBUF);
14876     sc->gz_strm = NULL;
14877
14878     /*******************/
14879     /* SLOW PATH QUEUE */
14880     /*******************/
14881
14882     bxe_dma_free(sc, &sc->spq_dma);
14883     sc->spq = NULL;
14884
14885     /*************/
14886     /* SLOW PATH */
14887     /*************/
14888
14889     bxe_dma_free(sc, &sc->sp_dma);
14890     sc->sp = NULL;
14891
14892     /***************/
14893     /* EVENT QUEUE */
14894     /***************/
14895
14896     bxe_dma_free(sc, &sc->eq_dma);
14897     sc->eq = NULL;
14898
14899     /************************/
14900     /* DEFAULT STATUS BLOCK */
14901     /************************/
14902
14903     bxe_dma_free(sc, &sc->def_sb_dma);
14904     sc->def_sb = NULL;
14905
14906     bus_dma_tag_destroy(sc->parent_dma_tag);
14907     sc->parent_dma_tag = NULL;
14908 }
14909
14910 /*
14911  * Previous driver DMAE transaction may have occurred when pre-boot stage
14912  * ended and boot began. This would invalidate the addresses of the
14913  * transaction, resulting in was-error bit set in the PCI causing all
14914  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
14915  * the interrupt which detected this from the pglueb and the was-done bit
14916  */
14917 static void
14918 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
14919 {
14920     uint32_t val;
14921
14922     if (!CHIP_IS_E1x(sc)) {
14923         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
14924         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
14925             BLOGD(sc, DBG_LOAD,
14926                   "Clearing 'was-error' bit that was set in pglueb");
14927             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
14928         }
14929     }
14930 }
14931
14932 static int
14933 bxe_prev_mcp_done(struct bxe_softc *sc)
14934 {
14935     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
14936                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
14937     if (!rc) {
14938         BLOGE(sc, "MCP response failure, aborting\n");
14939         return (-1);
14940     }
14941
14942     return (0);
14943 }
14944
14945 static struct bxe_prev_list_node *
14946 bxe_prev_path_get_entry(struct bxe_softc *sc)
14947 {
14948     struct bxe_prev_list_node *tmp;
14949
14950     LIST_FOREACH(tmp, &bxe_prev_list, node) {
14951         if ((sc->pcie_bus == tmp->bus) &&
14952             (sc->pcie_device == tmp->slot) &&
14953             (SC_PATH(sc) == tmp->path)) {
14954             return (tmp);
14955         }
14956     }
14957
14958     return (NULL);
14959 }
14960
14961 static uint8_t
14962 bxe_prev_is_path_marked(struct bxe_softc *sc)
14963 {
14964     struct bxe_prev_list_node *tmp;
14965     int rc = FALSE;
14966
14967     mtx_lock(&bxe_prev_mtx);
14968
14969     tmp = bxe_prev_path_get_entry(sc);
14970     if (tmp) {
14971         if (tmp->aer) {
14972             BLOGD(sc, DBG_LOAD,
14973                   "Path %d/%d/%d was marked by AER\n",
14974                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
14975         } else {
14976             rc = TRUE;
14977             BLOGD(sc, DBG_LOAD,
14978                   "Path %d/%d/%d was already cleaned from previous drivers\n",
14979                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
14980         }
14981     }
14982
14983     mtx_unlock(&bxe_prev_mtx);
14984
14985     return (rc);
14986 }
14987
14988 static int
14989 bxe_prev_mark_path(struct bxe_softc *sc,
14990                    uint8_t          after_undi)
14991 {
14992     struct bxe_prev_list_node *tmp;
14993
14994     mtx_lock(&bxe_prev_mtx);
14995
14996     /* Check whether the entry for this path already exists */
14997     tmp = bxe_prev_path_get_entry(sc);
14998     if (tmp) {
14999         if (!tmp->aer) {
15000             BLOGD(sc, DBG_LOAD,
15001                   "Re-marking AER in path %d/%d/%d\n",
15002                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15003         } else {
15004             BLOGD(sc, DBG_LOAD,
15005                   "Removing AER indication from path %d/%d/%d\n",
15006                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15007             tmp->aer = 0;
15008         }
15009
15010         mtx_unlock(&bxe_prev_mtx);
15011         return (0);
15012     }
15013
15014     mtx_unlock(&bxe_prev_mtx);
15015
15016     /* Create an entry for this path and add it */
15017     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15018                  (M_NOWAIT | M_ZERO));
15019     if (!tmp) {
15020         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15021         return (-1);
15022     }
15023
15024     tmp->bus  = sc->pcie_bus;
15025     tmp->slot = sc->pcie_device;
15026     tmp->path = SC_PATH(sc);
15027     tmp->aer  = 0;
15028     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15029
15030     mtx_lock(&bxe_prev_mtx);
15031
15032     BLOGD(sc, DBG_LOAD,
15033           "Marked path %d/%d/%d - finished previous unload\n",
15034           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15035     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15036
15037     mtx_unlock(&bxe_prev_mtx);
15038
15039     return (0);
15040 }
15041
15042 static int
15043 bxe_do_flr(struct bxe_softc *sc)
15044 {
15045     int i;
15046
15047     /* only E2 and onwards support FLR */
15048     if (CHIP_IS_E1x(sc)) {
15049         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15050         return (-1);
15051     }
15052
15053     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15054     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15055         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15056               sc->devinfo.bc_ver);
15057         return (-1);
15058     }
15059
15060     /* Wait for Transaction Pending bit clean */
15061     for (i = 0; i < 4; i++) {
15062         if (i) {
15063             DELAY(((1 << (i - 1)) * 100) * 1000);
15064         }
15065
15066         if (!bxe_is_pcie_pending(sc)) {
15067             goto clear;
15068         }
15069     }
15070
15071     BLOGE(sc, "PCIE transaction is not cleared, "
15072               "proceeding with reset anyway\n");
15073
15074 clear:
15075
15076     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15077     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15078
15079     return (0);
15080 }
15081
15082 struct bxe_mac_vals {
15083     uint32_t xmac_addr;
15084     uint32_t xmac_val;
15085     uint32_t emac_addr;
15086     uint32_t emac_val;
15087     uint32_t umac_addr;
15088     uint32_t umac_val;
15089     uint32_t bmac_addr;
15090     uint32_t bmac_val[2];
15091 };
15092
15093 static void
15094 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15095                           struct bxe_mac_vals *vals)
15096 {
15097     uint32_t val, base_addr, offset, mask, reset_reg;
15098     uint8_t mac_stopped = FALSE;
15099     uint8_t port = SC_PORT(sc);
15100     uint32_t wb_data[2];
15101
15102     /* reset addresses as they also mark which values were changed */
15103     vals->bmac_addr = 0;
15104     vals->umac_addr = 0;
15105     vals->xmac_addr = 0;
15106     vals->emac_addr = 0;
15107
15108     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15109
15110     if (!CHIP_IS_E3(sc)) {
15111         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15112         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15113         if ((mask & reset_reg) && val) {
15114             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15115             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15116                                     : NIG_REG_INGRESS_BMAC0_MEM;
15117             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15118                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15119
15120             /*
15121              * use rd/wr since we cannot use dmae. This is safe
15122              * since MCP won't access the bus due to the request
15123              * to unload, and no function on the path can be
15124              * loaded at this time.
15125              */
15126             wb_data[0] = REG_RD(sc, base_addr + offset);
15127             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15128             vals->bmac_addr = base_addr + offset;
15129             vals->bmac_val[0] = wb_data[0];
15130             vals->bmac_val[1] = wb_data[1];
15131             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15132             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15133             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15134         }
15135
15136         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15137         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15138         vals->emac_val = REG_RD(sc, vals->emac_addr);
15139         REG_WR(sc, vals->emac_addr, 0);
15140         mac_stopped = TRUE;
15141     } else {
15142         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15143             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15144             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15145             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15146             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15147             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15148             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15149             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15150             REG_WR(sc, vals->xmac_addr, 0);
15151             mac_stopped = TRUE;
15152         }
15153
15154         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15155         if (mask & reset_reg) {
15156             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15157             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15158             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15159             vals->umac_val = REG_RD(sc, vals->umac_addr);
15160             REG_WR(sc, vals->umac_addr, 0);
15161             mac_stopped = TRUE;
15162         }
15163     }
15164
15165     if (mac_stopped) {
15166         DELAY(20000);
15167     }
15168 }
15169
15170 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15171 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15172 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15173 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15174
15175 static void
15176 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15177                          uint8_t          port,
15178                          uint8_t          inc)
15179 {
15180     uint16_t rcq, bd;
15181     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15182
15183     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15184     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15185
15186     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15187     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15188
15189     BLOGD(sc, DBG_LOAD,
15190           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15191           port, bd, rcq);
15192 }
15193
15194 static int
15195 bxe_prev_unload_common(struct bxe_softc *sc)
15196 {
15197     uint32_t reset_reg, tmp_reg = 0, rc;
15198     uint8_t prev_undi = FALSE;
15199     struct bxe_mac_vals mac_vals;
15200     uint32_t timer_count = 1000;
15201     uint32_t prev_brb;
15202
15203     /*
15204      * It is possible a previous function received 'common' answer,
15205      * but hasn't loaded yet, therefore creating a scenario of
15206      * multiple functions receiving 'common' on the same path.
15207      */
15208     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15209
15210     memset(&mac_vals, 0, sizeof(mac_vals));
15211
15212     if (bxe_prev_is_path_marked(sc)) {
15213         return (bxe_prev_mcp_done(sc));
15214     }
15215
15216     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15217
15218     /* Reset should be performed after BRB is emptied */
15219     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15220         /* Close the MAC Rx to prevent BRB from filling up */
15221         bxe_prev_unload_close_mac(sc, &mac_vals);
15222
15223         /* close LLH filters towards the BRB */
15224         elink_set_rx_filter(&sc->link_params, 0);
15225
15226         /*
15227          * Check if the UNDI driver was previously loaded.
15228          * UNDI driver initializes CID offset for normal bell to 0x7
15229          */
15230         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15231             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15232             if (tmp_reg == 0x7) {
15233                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15234                 prev_undi = TRUE;
15235                 /* clear the UNDI indication */
15236                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15237                 /* clear possible idle check errors */
15238                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15239             }
15240         }
15241
15242         /* wait until BRB is empty */
15243         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15244         while (timer_count) {
15245             prev_brb = tmp_reg;
15246
15247             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15248             if (!tmp_reg) {
15249                 break;
15250             }
15251
15252             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15253
15254             /* reset timer as long as BRB actually gets emptied */
15255             if (prev_brb > tmp_reg) {
15256                 timer_count = 1000;
15257             } else {
15258                 timer_count--;
15259             }
15260
15261             /* If UNDI resides in memory, manually increment it */
15262             if (prev_undi) {
15263                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15264             }
15265
15266             DELAY(10);
15267         }
15268
15269         if (!timer_count) {
15270             BLOGE(sc, "Failed to empty BRB\n");
15271         }
15272     }
15273
15274     /* No packets are in the pipeline, path is ready for reset */
15275     bxe_reset_common(sc);
15276
15277     if (mac_vals.xmac_addr) {
15278         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15279     }
15280     if (mac_vals.umac_addr) {
15281         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15282     }
15283     if (mac_vals.emac_addr) {
15284         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15285     }
15286     if (mac_vals.bmac_addr) {
15287         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15288         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15289     }
15290
15291     rc = bxe_prev_mark_path(sc, prev_undi);
15292     if (rc) {
15293         bxe_prev_mcp_done(sc);
15294         return (rc);
15295     }
15296
15297     return (bxe_prev_mcp_done(sc));
15298 }
15299
15300 static int
15301 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15302 {
15303     int rc;
15304
15305     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15306
15307     /* Test if previous unload process was already finished for this path */
15308     if (bxe_prev_is_path_marked(sc)) {
15309         return (bxe_prev_mcp_done(sc));
15310     }
15311
15312     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15313
15314     /*
15315      * If function has FLR capabilities, and existing FW version matches
15316      * the one required, then FLR will be sufficient to clean any residue
15317      * left by previous driver
15318      */
15319     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15320     if (!rc) {
15321         /* fw version is good */
15322         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15323         rc = bxe_do_flr(sc);
15324     }
15325
15326     if (!rc) {
15327         /* FLR was performed */
15328         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15329         return (0);
15330     }
15331
15332     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15333
15334     /* Close the MCP request, return failure*/
15335     rc = bxe_prev_mcp_done(sc);
15336     if (!rc) {
15337         rc = BXE_PREV_WAIT_NEEDED;
15338     }
15339
15340     return (rc);
15341 }
15342
15343 static int
15344 bxe_prev_unload(struct bxe_softc *sc)
15345 {
15346     int time_counter = 10;
15347     uint32_t fw, hw_lock_reg, hw_lock_val;
15348     uint32_t rc = 0;
15349
15350     /*
15351      * Clear HW from errors which may have resulted from an interrupted
15352      * DMAE transaction.
15353      */
15354     bxe_prev_interrupted_dmae(sc);
15355
15356     /* Release previously held locks */
15357     hw_lock_reg =
15358         (SC_FUNC(sc) <= 5) ?
15359             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15360             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15361
15362     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15363     if (hw_lock_val) {
15364         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15365             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15366             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15367                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15368         }
15369         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15370         REG_WR(sc, hw_lock_reg, 0xffffffff);
15371     } else {
15372         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15373     }
15374
15375     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15376         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15377         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15378     }
15379
15380     do {
15381         /* Lock MCP using an unload request */
15382         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15383         if (!fw) {
15384             BLOGE(sc, "MCP response failure, aborting\n");
15385             rc = -1;
15386             break;
15387         }
15388
15389         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15390             rc = bxe_prev_unload_common(sc);
15391             break;
15392         }
15393
15394         /* non-common reply from MCP night require looping */
15395         rc = bxe_prev_unload_uncommon(sc);
15396         if (rc != BXE_PREV_WAIT_NEEDED) {
15397             break;
15398         }
15399
15400         DELAY(20000);
15401     } while (--time_counter);
15402
15403     if (!time_counter || rc) {
15404         BLOGE(sc, "Failed to unload previous driver!"
15405             " time_counter %d rc %d\n", time_counter, rc);
15406         rc = -1;
15407     }
15408
15409     return (rc);
15410 }
15411
15412 void
15413 bxe_dcbx_set_state(struct bxe_softc *sc,
15414                    uint8_t          dcb_on,
15415                    uint32_t         dcbx_enabled)
15416 {
15417     if (!CHIP_IS_E1x(sc)) {
15418         sc->dcb_state = dcb_on;
15419         sc->dcbx_enabled = dcbx_enabled;
15420     } else {
15421         sc->dcb_state = FALSE;
15422         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15423     }
15424     BLOGD(sc, DBG_LOAD,
15425           "DCB state [%s:%s]\n",
15426           dcb_on ? "ON" : "OFF",
15427           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15428           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15429           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15430           "on-chip with negotiation" : "invalid");
15431 }
15432
15433 /* must be called after sriov-enable */
15434 static int
15435 bxe_set_qm_cid_count(struct bxe_softc *sc)
15436 {
15437     int cid_count = BXE_L2_MAX_CID(sc);
15438
15439     if (IS_SRIOV(sc)) {
15440         cid_count += BXE_VF_CIDS;
15441     }
15442
15443     if (CNIC_SUPPORT(sc)) {
15444         cid_count += CNIC_CID_MAX;
15445     }
15446
15447     return (roundup(cid_count, QM_CID_ROUND));
15448 }
15449
15450 static void
15451 bxe_init_multi_cos(struct bxe_softc *sc)
15452 {
15453     int pri, cos;
15454
15455     uint32_t pri_map = 0; /* XXX change to user config */
15456
15457     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15458         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15459         if (cos < sc->max_cos) {
15460             sc->prio_to_cos[pri] = cos;
15461         } else {
15462             BLOGW(sc, "Invalid COS %d for priority %d "
15463                       "(max COS is %d), setting to 0\n",
15464                   cos, pri, (sc->max_cos - 1));
15465             sc->prio_to_cos[pri] = 0;
15466         }
15467     }
15468 }
15469
15470 static int
15471 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15472 {
15473     struct bxe_softc *sc;
15474     int error, result;
15475
15476     result = 0;
15477     error = sysctl_handle_int(oidp, &result, 0, req);
15478
15479     if (error || !req->newptr) {
15480         return (error);
15481     }
15482
15483     if (result == 1) {
15484         uint32_t  temp;
15485         sc = (struct bxe_softc *)arg1;
15486
15487         BLOGI(sc, "... dumping driver state ...\n");
15488         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15489         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15490     }
15491
15492     return (error);
15493 }
15494
15495 static int
15496 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15497 {
15498     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15499     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15500     uint32_t *offset;
15501     uint64_t value = 0;
15502     int index = (int)arg2;
15503
15504     if (index >= BXE_NUM_ETH_STATS) {
15505         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15506         return (-1);
15507     }
15508
15509     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15510
15511     switch (bxe_eth_stats_arr[index].size) {
15512     case 4:
15513         value = (uint64_t)*offset;
15514         break;
15515     case 8:
15516         value = HILO_U64(*offset, *(offset + 1));
15517         break;
15518     default:
15519         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15520               index, bxe_eth_stats_arr[index].size);
15521         return (-1);
15522     }
15523
15524     return (sysctl_handle_64(oidp, &value, 0, req));
15525 }
15526
15527 static int
15528 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15529 {
15530     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15531     uint32_t *eth_stats;
15532     uint32_t *offset;
15533     uint64_t value = 0;
15534     uint32_t q_stat = (uint32_t)arg2;
15535     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15536     uint32_t index = (q_stat & 0xffff);
15537
15538     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15539
15540     if (index >= BXE_NUM_ETH_Q_STATS) {
15541         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15542         return (-1);
15543     }
15544
15545     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15546
15547     switch (bxe_eth_q_stats_arr[index].size) {
15548     case 4:
15549         value = (uint64_t)*offset;
15550         break;
15551     case 8:
15552         value = HILO_U64(*offset, *(offset + 1));
15553         break;
15554     default:
15555         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15556               index, bxe_eth_q_stats_arr[index].size);
15557         return (-1);
15558     }
15559
15560     return (sysctl_handle_64(oidp, &value, 0, req));
15561 }
15562
15563 static void
15564 bxe_add_sysctls(struct bxe_softc *sc)
15565 {
15566     struct sysctl_ctx_list *ctx;
15567     struct sysctl_oid_list *children;
15568     struct sysctl_oid *queue_top, *queue;
15569     struct sysctl_oid_list *queue_top_children, *queue_children;
15570     char queue_num_buf[32];
15571     uint32_t q_stat;
15572     int i, j;
15573
15574     ctx = device_get_sysctl_ctx(sc->dev);
15575     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15576
15577     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15578                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15579                       "version");
15580
15581     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15582              BCM_5710_FW_MAJOR_VERSION,
15583              BCM_5710_FW_MINOR_VERSION,
15584              BCM_5710_FW_REVISION_VERSION,
15585              BCM_5710_FW_ENGINEERING_VERSION);
15586
15587     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15588         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15589          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15590          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15591          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15592                                                                 "Unknown"));
15593     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15594                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15595                     "multifunction vnics per port");
15596
15597     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15598         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15599          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15600          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15601                                               "???GT/s"),
15602         sc->devinfo.pcie_link_width);
15603
15604     sc->debug = bxe_debug;
15605
15606 #if __FreeBSD_version >= 900000
15607     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15608                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15609                       "bootcode version");
15610     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15611                       CTLFLAG_RD, sc->fw_ver_str, 0,
15612                       "firmware version");
15613     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15614                       CTLFLAG_RD, sc->mf_mode_str, 0,
15615                       "multifunction mode");
15616     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15617                       CTLFLAG_RD, sc->mac_addr_str, 0,
15618                       "mac address");
15619     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15620                       CTLFLAG_RD, sc->pci_link_str, 0,
15621                       "pci link status");
15622     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15623                     CTLFLAG_RW, &sc->debug,
15624                     "debug logging mode");
15625 #else
15626     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15627                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15628                       "bootcode version");
15629     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15630                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15631                       "firmware version");
15632     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15633                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15634                       "multifunction mode");
15635     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15636                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15637                       "mac address");
15638     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15639                       CTLFLAG_RD, &sc->pci_link_str, 0,
15640                       "pci link status");
15641     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15642                     CTLFLAG_RW, &sc->debug, 0,
15643                     "debug logging mode");
15644 #endif /* #if __FreeBSD_version >= 900000 */
15645
15646     sc->trigger_grcdump = 0;
15647     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15648                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15649                    "trigger grcdump should be invoked"
15650                    "  before collecting grcdump");
15651
15652     sc->grcdump_started = 0;
15653     sc->grcdump_done = 0;
15654     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15655                    CTLFLAG_RD, &sc->grcdump_done, 0,
15656                    "set by driver when grcdump is done");
15657
15658     sc->rx_budget = bxe_rx_budget;
15659     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15660                     CTLFLAG_RW, &sc->rx_budget, 0,
15661                     "rx processing budget");
15662
15663     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15664                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15665                     bxe_sysctl_state, "IU", "dump driver state");
15666
15667     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15668         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15669                         bxe_eth_stats_arr[i].string,
15670                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15671                         bxe_sysctl_eth_stat, "LU",
15672                         bxe_eth_stats_arr[i].string);
15673     }
15674
15675     /* add a new parent node for all queues "dev.bxe.#.queue" */
15676     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15677                                 CTLFLAG_RD, NULL, "queue");
15678     queue_top_children = SYSCTL_CHILDREN(queue_top);
15679
15680     for (i = 0; i < sc->num_queues; i++) {
15681         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15682         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15683         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15684                                 queue_num_buf, CTLFLAG_RD, NULL,
15685                                 "single queue");
15686         queue_children = SYSCTL_CHILDREN(queue);
15687
15688         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15689             q_stat = ((i << 16) | j);
15690             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15691                             bxe_eth_q_stats_arr[j].string,
15692                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15693                             bxe_sysctl_eth_q_stat, "LU",
15694                             bxe_eth_q_stats_arr[j].string);
15695         }
15696     }
15697 }
15698
15699 static int
15700 bxe_alloc_buf_rings(struct bxe_softc *sc)
15701 {
15702 #if __FreeBSD_version >= 800000
15703
15704     int i;
15705     struct bxe_fastpath *fp;
15706
15707     for (i = 0; i < sc->num_queues; i++) {
15708
15709         fp = &sc->fp[i];
15710
15711         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15712                                    M_NOWAIT, &fp->tx_mtx);
15713         if (fp->tx_br == NULL)
15714             return (-1);
15715     }
15716 #endif
15717     return (0);
15718 }
15719
15720 static void
15721 bxe_free_buf_rings(struct bxe_softc *sc)
15722 {
15723 #if __FreeBSD_version >= 800000
15724
15725     int i;
15726     struct bxe_fastpath *fp;
15727
15728     for (i = 0; i < sc->num_queues; i++) {
15729
15730         fp = &sc->fp[i];
15731
15732         if (fp->tx_br) {
15733             buf_ring_free(fp->tx_br, M_DEVBUF);
15734             fp->tx_br = NULL;
15735         }
15736     }
15737
15738 #endif
15739 }
15740
15741 static void
15742 bxe_init_fp_mutexs(struct bxe_softc *sc)
15743 {
15744     int i;
15745     struct bxe_fastpath *fp;
15746
15747     for (i = 0; i < sc->num_queues; i++) {
15748
15749         fp = &sc->fp[i];
15750
15751         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15752             "bxe%d_fp%d_tx_lock", sc->unit, i);
15753         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15754
15755         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15756             "bxe%d_fp%d_rx_lock", sc->unit, i);
15757         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15758     }
15759 }
15760
15761 static void
15762 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15763 {
15764     int i;
15765     struct bxe_fastpath *fp;
15766
15767     for (i = 0; i < sc->num_queues; i++) {
15768
15769         fp = &sc->fp[i];
15770
15771         if (mtx_initialized(&fp->tx_mtx)) {
15772             mtx_destroy(&fp->tx_mtx);
15773         }
15774
15775         if (mtx_initialized(&fp->rx_mtx)) {
15776             mtx_destroy(&fp->rx_mtx);
15777         }
15778     }
15779 }
15780
15781
15782 /*
15783  * Device attach function.
15784  *
15785  * Allocates device resources, performs secondary chip identification, and
15786  * initializes driver instance variables. This function is called from driver
15787  * load after a successful probe.
15788  *
15789  * Returns:
15790  *   0 = Success, >0 = Failure
15791  */
15792 static int
15793 bxe_attach(device_t dev)
15794 {
15795     struct bxe_softc *sc;
15796
15797     sc = device_get_softc(dev);
15798
15799     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15800
15801     sc->state = BXE_STATE_CLOSED;
15802
15803     sc->dev  = dev;
15804     sc->unit = device_get_unit(dev);
15805
15806     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15807
15808     sc->pcie_bus    = pci_get_bus(dev);
15809     sc->pcie_device = pci_get_slot(dev);
15810     sc->pcie_func   = pci_get_function(dev);
15811
15812     /* enable bus master capability */
15813     pci_enable_busmaster(dev);
15814
15815     /* get the BARs */
15816     if (bxe_allocate_bars(sc) != 0) {
15817         return (ENXIO);
15818     }
15819
15820     /* initialize the mutexes */
15821     bxe_init_mutexes(sc);
15822
15823     /* prepare the periodic callout */
15824     callout_init(&sc->periodic_callout, 0);
15825
15826     /* prepare the chip taskqueue */
15827     sc->chip_tq_flags = CHIP_TQ_NONE;
15828     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15829              "bxe%d_chip_tq", sc->unit);
15830     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15831     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15832                                    taskqueue_thread_enqueue,
15833                                    &sc->chip_tq);
15834     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15835                             "%s", sc->chip_tq_name);
15836
15837     /* get device info and set params */
15838     if (bxe_get_device_info(sc) != 0) {
15839         BLOGE(sc, "getting device info\n");
15840         bxe_deallocate_bars(sc);
15841         pci_disable_busmaster(dev);
15842         return (ENXIO);
15843     }
15844
15845     /* get final misc params */
15846     bxe_get_params(sc);
15847
15848     /* set the default MTU (changed via ifconfig) */
15849     sc->mtu = ETHERMTU;
15850
15851     bxe_set_modes_bitmap(sc);
15852
15853     /* XXX
15854      * If in AFEX mode and the function is configured for FCoE
15855      * then bail... no L2 allowed.
15856      */
15857
15858     /* get phy settings from shmem and 'and' against admin settings */
15859     bxe_get_phy_info(sc);
15860
15861     /* initialize the FreeBSD ifnet interface */
15862     if (bxe_init_ifnet(sc) != 0) {
15863         bxe_release_mutexes(sc);
15864         bxe_deallocate_bars(sc);
15865         pci_disable_busmaster(dev);
15866         return (ENXIO);
15867     }
15868
15869     if (bxe_add_cdev(sc) != 0) {
15870         if (sc->ifp != NULL) {
15871             ether_ifdetach(sc->ifp);
15872         }
15873         ifmedia_removeall(&sc->ifmedia);
15874         bxe_release_mutexes(sc);
15875         bxe_deallocate_bars(sc);
15876         pci_disable_busmaster(dev);
15877         return (ENXIO);
15878     }
15879
15880     /* allocate device interrupts */
15881     if (bxe_interrupt_alloc(sc) != 0) {
15882         bxe_del_cdev(sc);
15883         if (sc->ifp != NULL) {
15884             ether_ifdetach(sc->ifp);
15885         }
15886         ifmedia_removeall(&sc->ifmedia);
15887         bxe_release_mutexes(sc);
15888         bxe_deallocate_bars(sc);
15889         pci_disable_busmaster(dev);
15890         return (ENXIO);
15891     }
15892
15893     bxe_init_fp_mutexs(sc);
15894
15895     if (bxe_alloc_buf_rings(sc) != 0) {
15896         bxe_free_buf_rings(sc);
15897         bxe_interrupt_free(sc);
15898         bxe_del_cdev(sc);
15899         if (sc->ifp != NULL) {
15900             ether_ifdetach(sc->ifp);
15901         }
15902         ifmedia_removeall(&sc->ifmedia);
15903         bxe_release_mutexes(sc);
15904         bxe_deallocate_bars(sc);
15905         pci_disable_busmaster(dev);
15906         return (ENXIO);
15907     }
15908
15909     /* allocate ilt */
15910     if (bxe_alloc_ilt_mem(sc) != 0) {
15911         bxe_free_buf_rings(sc);
15912         bxe_interrupt_free(sc);
15913         bxe_del_cdev(sc);
15914         if (sc->ifp != NULL) {
15915             ether_ifdetach(sc->ifp);
15916         }
15917         ifmedia_removeall(&sc->ifmedia);
15918         bxe_release_mutexes(sc);
15919         bxe_deallocate_bars(sc);
15920         pci_disable_busmaster(dev);
15921         return (ENXIO);
15922     }
15923
15924     /* allocate the host hardware/software hsi structures */
15925     if (bxe_alloc_hsi_mem(sc) != 0) {
15926         bxe_free_ilt_mem(sc);
15927         bxe_free_buf_rings(sc);
15928         bxe_interrupt_free(sc);
15929         bxe_del_cdev(sc);
15930         if (sc->ifp != NULL) {
15931             ether_ifdetach(sc->ifp);
15932         }
15933         ifmedia_removeall(&sc->ifmedia);
15934         bxe_release_mutexes(sc);
15935         bxe_deallocate_bars(sc);
15936         pci_disable_busmaster(dev);
15937         return (ENXIO);
15938     }
15939
15940     /* need to reset chip if UNDI was active */
15941     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
15942         /* init fw_seq */
15943         sc->fw_seq =
15944             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
15945              DRV_MSG_SEQ_NUMBER_MASK);
15946         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
15947         bxe_prev_unload(sc);
15948     }
15949
15950 #if 1
15951     /* XXX */
15952     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15953 #else
15954     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
15955         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
15956         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
15957         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
15958         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
15959         bxe_dcbx_init_params(sc);
15960     } else {
15961         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15962     }
15963 #endif
15964
15965     /* calculate qm_cid_count */
15966     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
15967     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
15968
15969     sc->max_cos = 1;
15970     bxe_init_multi_cos(sc);
15971
15972     bxe_add_sysctls(sc);
15973
15974     return (0);
15975 }
15976
15977 /*
15978  * Device detach function.
15979  *
15980  * Stops the controller, resets the controller, and releases resources.
15981  *
15982  * Returns:
15983  *   0 = Success, >0 = Failure
15984  */
15985 static int
15986 bxe_detach(device_t dev)
15987 {
15988     struct bxe_softc *sc;
15989     if_t ifp;
15990
15991     sc = device_get_softc(dev);
15992
15993     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
15994
15995     ifp = sc->ifp;
15996     if (ifp != NULL && if_vlantrunkinuse(ifp)) {
15997         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
15998         return(EBUSY);
15999     }
16000
16001     bxe_del_cdev(sc);
16002
16003     /* stop the periodic callout */
16004     bxe_periodic_stop(sc);
16005
16006     /* stop the chip taskqueue */
16007     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16008     if (sc->chip_tq) {
16009         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16010         taskqueue_free(sc->chip_tq);
16011         sc->chip_tq = NULL;
16012     }
16013
16014     /* stop and reset the controller if it was open */
16015     if (sc->state != BXE_STATE_CLOSED) {
16016         BXE_CORE_LOCK(sc);
16017         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16018         sc->state = BXE_STATE_DISABLED;
16019         BXE_CORE_UNLOCK(sc);
16020     }
16021
16022     /* release the network interface */
16023     if (ifp != NULL) {
16024         ether_ifdetach(ifp);
16025     }
16026     ifmedia_removeall(&sc->ifmedia);
16027
16028     /* XXX do the following based on driver state... */
16029
16030     /* free the host hardware/software hsi structures */
16031     bxe_free_hsi_mem(sc);
16032
16033     /* free ilt */
16034     bxe_free_ilt_mem(sc);
16035
16036     bxe_free_buf_rings(sc);
16037
16038     /* release the interrupts */
16039     bxe_interrupt_free(sc);
16040
16041     /* Release the mutexes*/
16042     bxe_destroy_fp_mutexs(sc);
16043     bxe_release_mutexes(sc);
16044
16045
16046     /* Release the PCIe BAR mapped memory */
16047     bxe_deallocate_bars(sc);
16048
16049     /* Release the FreeBSD interface. */
16050     if (sc->ifp != NULL) {
16051         if_free(sc->ifp);
16052     }
16053
16054     pci_disable_busmaster(dev);
16055
16056     return (0);
16057 }
16058
16059 /*
16060  * Device shutdown function.
16061  *
16062  * Stops and resets the controller.
16063  *
16064  * Returns:
16065  *   Nothing
16066  */
16067 static int
16068 bxe_shutdown(device_t dev)
16069 {
16070     struct bxe_softc *sc;
16071
16072     sc = device_get_softc(dev);
16073
16074     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16075
16076     /* stop the periodic callout */
16077     bxe_periodic_stop(sc);
16078
16079     BXE_CORE_LOCK(sc);
16080     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16081     BXE_CORE_UNLOCK(sc);
16082
16083     return (0);
16084 }
16085
16086 void
16087 bxe_igu_ack_sb(struct bxe_softc *sc,
16088                uint8_t          igu_sb_id,
16089                uint8_t          segment,
16090                uint16_t         index,
16091                uint8_t          op,
16092                uint8_t          update)
16093 {
16094     uint32_t igu_addr = sc->igu_base_addr;
16095     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16096     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16097 }
16098
16099 static void
16100 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16101                      uint8_t          func,
16102                      uint8_t          idu_sb_id,
16103                      uint8_t          is_pf)
16104 {
16105     uint32_t data, ctl, cnt = 100;
16106     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16107     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16108     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16109     uint32_t sb_bit =  1 << (idu_sb_id%32);
16110     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16111     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16112
16113     /* Not supported in BC mode */
16114     if (CHIP_INT_MODE_IS_BC(sc)) {
16115         return;
16116     }
16117
16118     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16119              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16120             IGU_REGULAR_CLEANUP_SET |
16121             IGU_REGULAR_BCLEANUP);
16122
16123     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16124            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16125            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16126
16127     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16128             data, igu_addr_data);
16129     REG_WR(sc, igu_addr_data, data);
16130
16131     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16132                       BUS_SPACE_BARRIER_WRITE);
16133     mb();
16134
16135     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16136             ctl, igu_addr_ctl);
16137     REG_WR(sc, igu_addr_ctl, ctl);
16138
16139     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16140                       BUS_SPACE_BARRIER_WRITE);
16141     mb();
16142
16143     /* wait for clean up to finish */
16144     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16145         DELAY(20000);
16146     }
16147
16148     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16149         BLOGD(sc, DBG_LOAD,
16150               "Unable to finish IGU cleanup: "
16151               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16152               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16153     }
16154 }
16155
16156 static void
16157 bxe_igu_clear_sb(struct bxe_softc *sc,
16158                  uint8_t          idu_sb_id)
16159 {
16160     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16161 }
16162
16163
16164
16165
16166
16167
16168
16169 /*******************/
16170 /* ECORE CALLBACKS */
16171 /*******************/
16172
16173 static void
16174 bxe_reset_common(struct bxe_softc *sc)
16175 {
16176     uint32_t val = 0x1400;
16177
16178     /* reset_common */
16179     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16180
16181     if (CHIP_IS_E3(sc)) {
16182         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16183         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16184     }
16185
16186     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16187 }
16188
16189 static void
16190 bxe_common_init_phy(struct bxe_softc *sc)
16191 {
16192     uint32_t shmem_base[2];
16193     uint32_t shmem2_base[2];
16194
16195     /* Avoid common init in case MFW supports LFA */
16196     if (SHMEM2_RD(sc, size) >
16197         (uint32_t)offsetof(struct shmem2_region,
16198                            lfa_host_addr[SC_PORT(sc)])) {
16199         return;
16200     }
16201
16202     shmem_base[0]  = sc->devinfo.shmem_base;
16203     shmem2_base[0] = sc->devinfo.shmem2_base;
16204
16205     if (!CHIP_IS_E1x(sc)) {
16206         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16207         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16208     }
16209
16210     bxe_acquire_phy_lock(sc);
16211     elink_common_init_phy(sc, shmem_base, shmem2_base,
16212                           sc->devinfo.chip_id, 0);
16213     bxe_release_phy_lock(sc);
16214 }
16215
16216 static void
16217 bxe_pf_disable(struct bxe_softc *sc)
16218 {
16219     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16220
16221     val &= ~IGU_PF_CONF_FUNC_EN;
16222
16223     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16224     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16225     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16226 }
16227
16228 static void
16229 bxe_init_pxp(struct bxe_softc *sc)
16230 {
16231     uint16_t devctl;
16232     int r_order, w_order;
16233
16234     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16235
16236     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16237
16238     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16239
16240     if (sc->mrrs == -1) {
16241         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16242     } else {
16243         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16244         r_order = sc->mrrs;
16245     }
16246
16247     ecore_init_pxp_arb(sc, r_order, w_order);
16248 }
16249
16250 static uint32_t
16251 bxe_get_pretend_reg(struct bxe_softc *sc)
16252 {
16253     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16254     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16255     return (base + (SC_ABS_FUNC(sc)) * stride);
16256 }
16257
16258 /*
16259  * Called only on E1H or E2.
16260  * When pretending to be PF, the pretend value is the function number 0..7.
16261  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16262  * combination.
16263  */
16264 static int
16265 bxe_pretend_func(struct bxe_softc *sc,
16266                  uint16_t         pretend_func_val)
16267 {
16268     uint32_t pretend_reg;
16269
16270     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16271         return (-1);
16272     }
16273
16274     /* get my own pretend register */
16275     pretend_reg = bxe_get_pretend_reg(sc);
16276     REG_WR(sc, pretend_reg, pretend_func_val);
16277     REG_RD(sc, pretend_reg);
16278     return (0);
16279 }
16280
16281 static void
16282 bxe_iov_init_dmae(struct bxe_softc *sc)
16283 {
16284     return;
16285 }
16286
16287 static void
16288 bxe_iov_init_dq(struct bxe_softc *sc)
16289 {
16290     return;
16291 }
16292
16293 /* send a NIG loopback debug packet */
16294 static void
16295 bxe_lb_pckt(struct bxe_softc *sc)
16296 {
16297     uint32_t wb_write[3];
16298
16299     /* Ethernet source and destination addresses */
16300     wb_write[0] = 0x55555555;
16301     wb_write[1] = 0x55555555;
16302     wb_write[2] = 0x20;     /* SOP */
16303     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16304
16305     /* NON-IP protocol */
16306     wb_write[0] = 0x09000000;
16307     wb_write[1] = 0x55555555;
16308     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16309     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16310 }
16311
16312 /*
16313  * Some of the internal memories are not directly readable from the driver.
16314  * To test them we send debug packets.
16315  */
16316 static int
16317 bxe_int_mem_test(struct bxe_softc *sc)
16318 {
16319     int factor;
16320     int count, i;
16321     uint32_t val = 0;
16322
16323     if (CHIP_REV_IS_FPGA(sc)) {
16324         factor = 120;
16325     } else if (CHIP_REV_IS_EMUL(sc)) {
16326         factor = 200;
16327     } else {
16328         factor = 1;
16329     }
16330
16331     /* disable inputs of parser neighbor blocks */
16332     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16333     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16334     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16335     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16336
16337     /*  write 0 to parser credits for CFC search request */
16338     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16339
16340     /* send Ethernet packet */
16341     bxe_lb_pckt(sc);
16342
16343     /* TODO do i reset NIG statistic? */
16344     /* Wait until NIG register shows 1 packet of size 0x10 */
16345     count = 1000 * factor;
16346     while (count) {
16347         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16348         val = *BXE_SP(sc, wb_data[0]);
16349         if (val == 0x10) {
16350             break;
16351         }
16352
16353         DELAY(10000);
16354         count--;
16355     }
16356
16357     if (val != 0x10) {
16358         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16359         return (-1);
16360     }
16361
16362     /* wait until PRS register shows 1 packet */
16363     count = (1000 * factor);
16364     while (count) {
16365         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16366         if (val == 1) {
16367             break;
16368         }
16369
16370         DELAY(10000);
16371         count--;
16372     }
16373
16374     if (val != 0x1) {
16375         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16376         return (-2);
16377     }
16378
16379     /* Reset and init BRB, PRS */
16380     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16381     DELAY(50000);
16382     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16383     DELAY(50000);
16384     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16385     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16386
16387     /* Disable inputs of parser neighbor blocks */
16388     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16389     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16390     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16391     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16392
16393     /* Write 0 to parser credits for CFC search request */
16394     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16395
16396     /* send 10 Ethernet packets */
16397     for (i = 0; i < 10; i++) {
16398         bxe_lb_pckt(sc);
16399     }
16400
16401     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16402     count = (1000 * factor);
16403     while (count) {
16404         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16405         val = *BXE_SP(sc, wb_data[0]);
16406         if (val == 0xb0) {
16407             break;
16408         }
16409
16410         DELAY(10000);
16411         count--;
16412     }
16413
16414     if (val != 0xb0) {
16415         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16416         return (-3);
16417     }
16418
16419     /* Wait until PRS register shows 2 packets */
16420     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16421     if (val != 2) {
16422         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16423     }
16424
16425     /* Write 1 to parser credits for CFC search request */
16426     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16427
16428     /* Wait until PRS register shows 3 packets */
16429     DELAY(10000 * factor);
16430
16431     /* Wait until NIG register shows 1 packet of size 0x10 */
16432     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16433     if (val != 3) {
16434         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16435     }
16436
16437     /* clear NIG EOP FIFO */
16438     for (i = 0; i < 11; i++) {
16439         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16440     }
16441
16442     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16443     if (val != 1) {
16444         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16445         return (-4);
16446     }
16447
16448     /* Reset and init BRB, PRS, NIG */
16449     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16450     DELAY(50000);
16451     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16452     DELAY(50000);
16453     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16454     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16455     if (!CNIC_SUPPORT(sc)) {
16456         /* set NIC mode */
16457         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16458     }
16459
16460     /* Enable inputs of parser neighbor blocks */
16461     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16462     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16463     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16464     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16465
16466     return (0);
16467 }
16468
16469 static void
16470 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16471 {
16472     int is_required;
16473     uint32_t val;
16474     int port;
16475
16476     is_required = 0;
16477     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16478            SHARED_HW_CFG_FAN_FAILURE_MASK);
16479
16480     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16481         is_required = 1;
16482     }
16483     /*
16484      * The fan failure mechanism is usually related to the PHY type since
16485      * the power consumption of the board is affected by the PHY. Currently,
16486      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16487      */
16488     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16489         for (port = PORT_0; port < PORT_MAX; port++) {
16490             is_required |= elink_fan_failure_det_req(sc,
16491                                                      sc->devinfo.shmem_base,
16492                                                      sc->devinfo.shmem2_base,
16493                                                      port);
16494         }
16495     }
16496
16497     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16498
16499     if (is_required == 0) {
16500         return;
16501     }
16502
16503     /* Fan failure is indicated by SPIO 5 */
16504     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16505
16506     /* set to active low mode */
16507     val = REG_RD(sc, MISC_REG_SPIO_INT);
16508     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16509     REG_WR(sc, MISC_REG_SPIO_INT, val);
16510
16511     /* enable interrupt to signal the IGU */
16512     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16513     val |= MISC_SPIO_SPIO5;
16514     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16515 }
16516
16517 static void
16518 bxe_enable_blocks_attention(struct bxe_softc *sc)
16519 {
16520     uint32_t val;
16521
16522     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16523     if (!CHIP_IS_E1x(sc)) {
16524         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16525     } else {
16526         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16527     }
16528     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16529     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16530     /*
16531      * mask read length error interrupts in brb for parser
16532      * (parsing unit and 'checksum and crc' unit)
16533      * these errors are legal (PU reads fixed length and CAC can cause
16534      * read length error on truncated packets)
16535      */
16536     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16537     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16538     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16539     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16540     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16541     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16542 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16543 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16544     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16545     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16546     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16547 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16548 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16549     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16550     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16551     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16552     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16553 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16554 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16555
16556     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16557            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16558            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16559     if (!CHIP_IS_E1x(sc)) {
16560         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16561                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16562     }
16563     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16564
16565     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16566     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16567     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16568 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16569
16570     if (!CHIP_IS_E1x(sc)) {
16571         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16572         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16573     }
16574
16575     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16576     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16577 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16578     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16579 }
16580
16581 /**
16582  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16583  *
16584  * @sc:     driver handle
16585  */
16586 static int
16587 bxe_init_hw_common(struct bxe_softc *sc)
16588 {
16589     uint8_t abs_func_id;
16590     uint32_t val;
16591
16592     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16593           SC_ABS_FUNC(sc));
16594
16595     /*
16596      * take the RESET lock to protect undi_unload flow from accessing
16597      * registers while we are resetting the chip
16598      */
16599     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16600
16601     bxe_reset_common(sc);
16602
16603     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16604
16605     val = 0xfffc;
16606     if (CHIP_IS_E3(sc)) {
16607         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16608         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16609     }
16610
16611     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16612
16613     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16614
16615     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16616     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16617
16618     if (!CHIP_IS_E1x(sc)) {
16619         /*
16620          * 4-port mode or 2-port mode we need to turn off master-enable for
16621          * everyone. After that we turn it back on for self. So, we disregard
16622          * multi-function, and always disable all functions on the given path,
16623          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16624          */
16625         for (abs_func_id = SC_PATH(sc);
16626              abs_func_id < (E2_FUNC_MAX * 2);
16627              abs_func_id += 2) {
16628             if (abs_func_id == SC_ABS_FUNC(sc)) {
16629                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16630                 continue;
16631             }
16632
16633             bxe_pretend_func(sc, abs_func_id);
16634
16635             /* clear pf enable */
16636             bxe_pf_disable(sc);
16637
16638             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16639         }
16640     }
16641
16642     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16643
16644     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16645
16646     if (CHIP_IS_E1(sc)) {
16647         /*
16648          * enable HW interrupt from PXP on USDM overflow
16649          * bit 16 on INT_MASK_0
16650          */
16651         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16652     }
16653
16654     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16655     bxe_init_pxp(sc);
16656
16657 #ifdef __BIG_ENDIAN
16658     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16659     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16660     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16661     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16662     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16663     /* make sure this value is 0 */
16664     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16665
16666     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16667     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16668     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16669     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16670     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16671 #endif
16672
16673     ecore_ilt_init_page_size(sc, INITOP_SET);
16674
16675     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16676         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16677     }
16678
16679     /* let the HW do it's magic... */
16680     DELAY(100000);
16681
16682     /* finish PXP init */
16683     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16684     if (val != 1) {
16685         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16686             val);
16687         return (-1);
16688     }
16689     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16690     if (val != 1) {
16691         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16692         return (-1);
16693     }
16694
16695     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16696
16697     /*
16698      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16699      * entries with value "0" and valid bit on. This needs to be done by the
16700      * first PF that is loaded in a path (i.e. common phase)
16701      */
16702     if (!CHIP_IS_E1x(sc)) {
16703 /*
16704  * In E2 there is a bug in the timers block that can cause function 6 / 7
16705  * (i.e. vnic3) to start even if it is marked as "scan-off".
16706  * This occurs when a different function (func2,3) is being marked
16707  * as "scan-off". Real-life scenario for example: if a driver is being
16708  * load-unloaded while func6,7 are down. This will cause the timer to access
16709  * the ilt, translate to a logical address and send a request to read/write.
16710  * Since the ilt for the function that is down is not valid, this will cause
16711  * a translation error which is unrecoverable.
16712  * The Workaround is intended to make sure that when this happens nothing
16713  * fatal will occur. The workaround:
16714  *  1.  First PF driver which loads on a path will:
16715  *      a.  After taking the chip out of reset, by using pretend,
16716  *          it will write "0" to the following registers of
16717  *          the other vnics.
16718  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16719  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16720  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16721  *          And for itself it will write '1' to
16722  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16723  *          dmae-operations (writing to pram for example.)
16724  *          note: can be done for only function 6,7 but cleaner this
16725  *            way.
16726  *      b.  Write zero+valid to the entire ILT.
16727  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16728  *          VNIC3 (of that port). The range allocated will be the
16729  *          entire ILT. This is needed to prevent  ILT range error.
16730  *  2.  Any PF driver load flow:
16731  *      a.  ILT update with the physical addresses of the allocated
16732  *          logical pages.
16733  *      b.  Wait 20msec. - note that this timeout is needed to make
16734  *          sure there are no requests in one of the PXP internal
16735  *          queues with "old" ILT addresses.
16736  *      c.  PF enable in the PGLC.
16737  *      d.  Clear the was_error of the PF in the PGLC. (could have
16738  *          occurred while driver was down)
16739  *      e.  PF enable in the CFC (WEAK + STRONG)
16740  *      f.  Timers scan enable
16741  *  3.  PF driver unload flow:
16742  *      a.  Clear the Timers scan_en.
16743  *      b.  Polling for scan_on=0 for that PF.
16744  *      c.  Clear the PF enable bit in the PXP.
16745  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16746  *      e.  Write zero+valid to all ILT entries (The valid bit must
16747  *          stay set)
16748  *      f.  If this is VNIC 3 of a port then also init
16749  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16750  *          to the last enrty in the ILT.
16751  *
16752  *      Notes:
16753  *      Currently the PF error in the PGLC is non recoverable.
16754  *      In the future the there will be a recovery routine for this error.
16755  *      Currently attention is masked.
16756  *      Having an MCP lock on the load/unload process does not guarantee that
16757  *      there is no Timer disable during Func6/7 enable. This is because the
16758  *      Timers scan is currently being cleared by the MCP on FLR.
16759  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16760  *      there is error before clearing it. But the flow above is simpler and
16761  *      more general.
16762  *      All ILT entries are written by zero+valid and not just PF6/7
16763  *      ILT entries since in the future the ILT entries allocation for
16764  *      PF-s might be dynamic.
16765  */
16766         struct ilt_client_info ilt_cli;
16767         struct ecore_ilt ilt;
16768
16769         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16770         memset(&ilt, 0, sizeof(struct ecore_ilt));
16771
16772         /* initialize dummy TM client */
16773         ilt_cli.start      = 0;
16774         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16775         ilt_cli.client_num = ILT_CLIENT_TM;
16776
16777         /*
16778          * Step 1: set zeroes to all ilt page entries with valid bit on
16779          * Step 2: set the timers first/last ilt entry to point
16780          * to the entire range to prevent ILT range error for 3rd/4th
16781          * vnic (this code assumes existence of the vnic)
16782          *
16783          * both steps performed by call to ecore_ilt_client_init_op()
16784          * with dummy TM client
16785          *
16786          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16787          * and his brother are split registers
16788          */
16789
16790         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16791         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16792         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16793
16794         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16795         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16796         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16797     }
16798
16799     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16800     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16801
16802     if (!CHIP_IS_E1x(sc)) {
16803         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16804                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16805
16806         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16807         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16808
16809         /* let the HW do it's magic... */
16810         do {
16811             DELAY(200000);
16812             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16813         } while (factor-- && (val != 1));
16814
16815         if (val != 1) {
16816             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16817             return (-1);
16818         }
16819     }
16820
16821     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16822
16823     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16824
16825     bxe_iov_init_dmae(sc);
16826
16827     /* clean the DMAE memory */
16828     sc->dmae_ready = 1;
16829     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16830
16831     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16832
16833     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16834
16835     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16836
16837     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16838
16839     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16840     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
16841     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
16842     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
16843
16844     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
16845
16846     /* QM queues pointers table */
16847     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
16848
16849     /* soft reset pulse */
16850     REG_WR(sc, QM_REG_SOFT_RESET, 1);
16851     REG_WR(sc, QM_REG_SOFT_RESET, 0);
16852
16853     if (CNIC_SUPPORT(sc))
16854         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
16855
16856     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
16857     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
16858     if (!CHIP_REV_IS_SLOW(sc)) {
16859         /* enable hw interrupt from doorbell Q */
16860         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16861     }
16862
16863     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16864
16865     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16866     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
16867
16868     if (!CHIP_IS_E1(sc)) {
16869         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
16870     }
16871
16872     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
16873         if (IS_MF_AFEX(sc)) {
16874             /*
16875              * configure that AFEX and VLAN headers must be
16876              * received in AFEX mode
16877              */
16878             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
16879             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
16880             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
16881             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
16882             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
16883         } else {
16884             /*
16885              * Bit-map indicating which L2 hdrs may appear
16886              * after the basic Ethernet header
16887              */
16888             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
16889                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16890         }
16891     }
16892
16893     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
16894     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
16895     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
16896     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
16897
16898     if (!CHIP_IS_E1x(sc)) {
16899         /* reset VFC memories */
16900         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16901                VFC_MEMORIES_RST_REG_CAM_RST |
16902                VFC_MEMORIES_RST_REG_RAM_RST);
16903         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16904                VFC_MEMORIES_RST_REG_CAM_RST |
16905                VFC_MEMORIES_RST_REG_RAM_RST);
16906
16907         DELAY(20000);
16908     }
16909
16910     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
16911     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
16912     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
16913     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
16914
16915     /* sync semi rtc */
16916     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
16917            0x80000000);
16918     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
16919            0x80000000);
16920
16921     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
16922     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
16923     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
16924
16925     if (!CHIP_IS_E1x(sc)) {
16926         if (IS_MF_AFEX(sc)) {
16927             /*
16928              * configure that AFEX and VLAN headers must be
16929              * sent in AFEX mode
16930              */
16931             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
16932             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
16933             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
16934             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
16935             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
16936         } else {
16937             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
16938                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16939         }
16940     }
16941
16942     REG_WR(sc, SRC_REG_SOFT_RST, 1);
16943
16944     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
16945
16946     if (CNIC_SUPPORT(sc)) {
16947         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
16948         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
16949         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
16950         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
16951         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
16952         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
16953         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
16954         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
16955         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
16956         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
16957     }
16958     REG_WR(sc, SRC_REG_SOFT_RST, 0);
16959
16960     if (sizeof(union cdu_context) != 1024) {
16961         /* we currently assume that a context is 1024 bytes */
16962         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
16963               (long)sizeof(union cdu_context));
16964     }
16965
16966     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
16967     val = (4 << 24) + (0 << 12) + 1024;
16968     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
16969
16970     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
16971
16972     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
16973     /* enable context validation interrupt from CFC */
16974     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16975
16976     /* set the thresholds to prevent CFC/CDU race */
16977     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
16978     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
16979
16980     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
16981         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
16982     }
16983
16984     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
16985     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
16986
16987     /* Reset PCIE errors for debug */
16988     REG_WR(sc, 0x2814, 0xffffffff);
16989     REG_WR(sc, 0x3820, 0xffffffff);
16990
16991     if (!CHIP_IS_E1x(sc)) {
16992         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
16993                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
16994                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
16995         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
16996                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
16997                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
16998                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
16999         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17000                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17001                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17002                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17003     }
17004
17005     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17006
17007     if (!CHIP_IS_E1(sc)) {
17008         /* in E3 this done in per-port section */
17009         if (!CHIP_IS_E3(sc))
17010             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17011     }
17012
17013     if (CHIP_IS_E1H(sc)) {
17014         /* not applicable for E2 (and above ...) */
17015         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17016     }
17017
17018     if (CHIP_REV_IS_SLOW(sc)) {
17019         DELAY(200000);
17020     }
17021
17022     /* finish CFC init */
17023     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17024     if (val != 1) {
17025         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17026         return (-1);
17027     }
17028     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17029     if (val != 1) {
17030         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17031         return (-1);
17032     }
17033     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17034     if (val != 1) {
17035         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17036         return (-1);
17037     }
17038     REG_WR(sc, CFC_REG_DEBUG0, 0);
17039
17040     if (CHIP_IS_E1(sc)) {
17041         /* read NIG statistic to see if this is our first up since powerup */
17042         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17043         val = *BXE_SP(sc, wb_data[0]);
17044
17045         /* do internal memory self test */
17046         if ((val == 0) && bxe_int_mem_test(sc)) {
17047             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17048             return (-1);
17049         }
17050     }
17051
17052     bxe_setup_fan_failure_detection(sc);
17053
17054     /* clear PXP2 attentions */
17055     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17056
17057     bxe_enable_blocks_attention(sc);
17058
17059     if (!CHIP_REV_IS_SLOW(sc)) {
17060         ecore_enable_blocks_parity(sc);
17061     }
17062
17063     if (!BXE_NOMCP(sc)) {
17064         if (CHIP_IS_E1x(sc)) {
17065             bxe_common_init_phy(sc);
17066         }
17067     }
17068
17069     return (0);
17070 }
17071
17072 /**
17073  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17074  *
17075  * @sc:     driver handle
17076  */
17077 static int
17078 bxe_init_hw_common_chip(struct bxe_softc *sc)
17079 {
17080     int rc = bxe_init_hw_common(sc);
17081
17082     if (rc) {
17083         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17084         return (rc);
17085     }
17086
17087     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17088     if (!BXE_NOMCP(sc)) {
17089         bxe_common_init_phy(sc);
17090     }
17091
17092     return (0);
17093 }
17094
17095 static int
17096 bxe_init_hw_port(struct bxe_softc *sc)
17097 {
17098     int port = SC_PORT(sc);
17099     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17100     uint32_t low, high;
17101     uint32_t val;
17102
17103     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17104
17105     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17106
17107     ecore_init_block(sc, BLOCK_MISC, init_phase);
17108     ecore_init_block(sc, BLOCK_PXP, init_phase);
17109     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17110
17111     /*
17112      * Timers bug workaround: disables the pf_master bit in pglue at
17113      * common phase, we need to enable it here before any dmae access are
17114      * attempted. Therefore we manually added the enable-master to the
17115      * port phase (it also happens in the function phase)
17116      */
17117     if (!CHIP_IS_E1x(sc)) {
17118         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17119     }
17120
17121     ecore_init_block(sc, BLOCK_ATC, init_phase);
17122     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17123     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17124     ecore_init_block(sc, BLOCK_QM, init_phase);
17125
17126     ecore_init_block(sc, BLOCK_TCM, init_phase);
17127     ecore_init_block(sc, BLOCK_UCM, init_phase);
17128     ecore_init_block(sc, BLOCK_CCM, init_phase);
17129     ecore_init_block(sc, BLOCK_XCM, init_phase);
17130
17131     /* QM cid (connection) count */
17132     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17133
17134     if (CNIC_SUPPORT(sc)) {
17135         ecore_init_block(sc, BLOCK_TM, init_phase);
17136         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17137         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17138     }
17139
17140     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17141
17142     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17143
17144     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17145         if (IS_MF(sc)) {
17146             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17147         } else if (sc->mtu > 4096) {
17148             if (BXE_ONE_PORT(sc)) {
17149                 low = 160;
17150             } else {
17151                 val = sc->mtu;
17152                 /* (24*1024 + val*4)/256 */
17153                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17154             }
17155         } else {
17156             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17157         }
17158         high = (low + 56); /* 14*1024/256 */
17159         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17160         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17161     }
17162
17163     if (CHIP_IS_MODE_4_PORT(sc)) {
17164         REG_WR(sc, SC_PORT(sc) ?
17165                BRB1_REG_MAC_GUARANTIED_1 :
17166                BRB1_REG_MAC_GUARANTIED_0, 40);
17167     }
17168
17169     ecore_init_block(sc, BLOCK_PRS, init_phase);
17170     if (CHIP_IS_E3B0(sc)) {
17171         if (IS_MF_AFEX(sc)) {
17172             /* configure headers for AFEX mode */
17173             REG_WR(sc, SC_PORT(sc) ?
17174                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17175                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17176             REG_WR(sc, SC_PORT(sc) ?
17177                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17178                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17179             REG_WR(sc, SC_PORT(sc) ?
17180                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17181                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17182         } else {
17183             /* Ovlan exists only if we are in multi-function +
17184              * switch-dependent mode, in switch-independent there
17185              * is no ovlan headers
17186              */
17187             REG_WR(sc, SC_PORT(sc) ?
17188                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17189                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17190                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17191         }
17192     }
17193
17194     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17195     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17196     ecore_init_block(sc, BLOCK_USDM, init_phase);
17197     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17198
17199     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17200     ecore_init_block(sc, BLOCK_USEM, init_phase);
17201     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17202     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17203
17204     ecore_init_block(sc, BLOCK_UPB, init_phase);
17205     ecore_init_block(sc, BLOCK_XPB, init_phase);
17206
17207     ecore_init_block(sc, BLOCK_PBF, init_phase);
17208
17209     if (CHIP_IS_E1x(sc)) {
17210         /* configure PBF to work without PAUSE mtu 9000 */
17211         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17212
17213         /* update threshold */
17214         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17215         /* update init credit */
17216         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17217
17218         /* probe changes */
17219         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17220         DELAY(50);
17221         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17222     }
17223
17224     if (CNIC_SUPPORT(sc)) {
17225         ecore_init_block(sc, BLOCK_SRC, init_phase);
17226     }
17227
17228     ecore_init_block(sc, BLOCK_CDU, init_phase);
17229     ecore_init_block(sc, BLOCK_CFC, init_phase);
17230
17231     if (CHIP_IS_E1(sc)) {
17232         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17233         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17234     }
17235     ecore_init_block(sc, BLOCK_HC, init_phase);
17236
17237     ecore_init_block(sc, BLOCK_IGU, init_phase);
17238
17239     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17240     /* init aeu_mask_attn_func_0/1:
17241      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17242      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17243      *             bits 4-7 are used for "per vn group attention" */
17244     val = IS_MF(sc) ? 0xF7 : 0x7;
17245     /* Enable DCBX attention for all but E1 */
17246     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17247     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17248
17249     ecore_init_block(sc, BLOCK_NIG, init_phase);
17250
17251     if (!CHIP_IS_E1x(sc)) {
17252         /* Bit-map indicating which L2 hdrs may appear after the
17253          * basic Ethernet header
17254          */
17255         if (IS_MF_AFEX(sc)) {
17256             REG_WR(sc, SC_PORT(sc) ?
17257                    NIG_REG_P1_HDRS_AFTER_BASIC :
17258                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17259         } else {
17260             REG_WR(sc, SC_PORT(sc) ?
17261                    NIG_REG_P1_HDRS_AFTER_BASIC :
17262                    NIG_REG_P0_HDRS_AFTER_BASIC,
17263                    IS_MF_SD(sc) ? 7 : 6);
17264         }
17265
17266         if (CHIP_IS_E3(sc)) {
17267             REG_WR(sc, SC_PORT(sc) ?
17268                    NIG_REG_LLH1_MF_MODE :
17269                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17270         }
17271     }
17272     if (!CHIP_IS_E3(sc)) {
17273         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17274     }
17275
17276     if (!CHIP_IS_E1(sc)) {
17277         /* 0x2 disable mf_ov, 0x1 enable */
17278         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17279                (IS_MF_SD(sc) ? 0x1 : 0x2));
17280
17281         if (!CHIP_IS_E1x(sc)) {
17282             val = 0;
17283             switch (sc->devinfo.mf_info.mf_mode) {
17284             case MULTI_FUNCTION_SD:
17285                 val = 1;
17286                 break;
17287             case MULTI_FUNCTION_SI:
17288             case MULTI_FUNCTION_AFEX:
17289                 val = 2;
17290                 break;
17291             }
17292
17293             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17294                         NIG_REG_LLH0_CLS_TYPE), val);
17295         }
17296         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17297         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17298         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17299     }
17300
17301     /* If SPIO5 is set to generate interrupts, enable it for this port */
17302     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17303     if (val & MISC_SPIO_SPIO5) {
17304         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17305                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17306         val = REG_RD(sc, reg_addr);
17307         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17308         REG_WR(sc, reg_addr, val);
17309     }
17310
17311     return (0);
17312 }
17313
17314 static uint32_t
17315 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17316                        uint32_t         reg,
17317                        uint32_t         expected,
17318                        uint32_t         poll_count)
17319 {
17320     uint32_t cur_cnt = poll_count;
17321     uint32_t val;
17322
17323     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17324         DELAY(FLR_WAIT_INTERVAL);
17325     }
17326
17327     return (val);
17328 }
17329
17330 static int
17331 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17332                               uint32_t         reg,
17333                               char             *msg,
17334                               uint32_t         poll_cnt)
17335 {
17336     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17337
17338     if (val != 0) {
17339         BLOGE(sc, "%s usage count=%d\n", msg, val);
17340         return (1);
17341     }
17342
17343     return (0);
17344 }
17345
17346 /* Common routines with VF FLR cleanup */
17347 static uint32_t
17348 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17349 {
17350     /* adjust polling timeout */
17351     if (CHIP_REV_IS_EMUL(sc)) {
17352         return (FLR_POLL_CNT * 2000);
17353     }
17354
17355     if (CHIP_REV_IS_FPGA(sc)) {
17356         return (FLR_POLL_CNT * 120);
17357     }
17358
17359     return (FLR_POLL_CNT);
17360 }
17361
17362 static int
17363 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17364                            uint32_t         poll_cnt)
17365 {
17366     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17367     if (bxe_flr_clnup_poll_hw_counter(sc,
17368                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17369                                       "CFC PF usage counter timed out",
17370                                       poll_cnt)) {
17371         return (1);
17372     }
17373
17374     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17375     if (bxe_flr_clnup_poll_hw_counter(sc,
17376                                       DORQ_REG_PF_USAGE_CNT,
17377                                       "DQ PF usage counter timed out",
17378                                       poll_cnt)) {
17379         return (1);
17380     }
17381
17382     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17383     if (bxe_flr_clnup_poll_hw_counter(sc,
17384                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17385                                       "QM PF usage counter timed out",
17386                                       poll_cnt)) {
17387         return (1);
17388     }
17389
17390     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17391     if (bxe_flr_clnup_poll_hw_counter(sc,
17392                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17393                                       "Timers VNIC usage counter timed out",
17394                                       poll_cnt)) {
17395         return (1);
17396     }
17397
17398     if (bxe_flr_clnup_poll_hw_counter(sc,
17399                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17400                                       "Timers NUM_SCANS usage counter timed out",
17401                                       poll_cnt)) {
17402         return (1);
17403     }
17404
17405     /* Wait DMAE PF usage counter to zero */
17406     if (bxe_flr_clnup_poll_hw_counter(sc,
17407                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17408                                       "DMAE dommand register timed out",
17409                                       poll_cnt)) {
17410         return (1);
17411     }
17412
17413     return (0);
17414 }
17415
17416 #define OP_GEN_PARAM(param)                                            \
17417     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17418 #define OP_GEN_TYPE(type)                                           \
17419     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17420 #define OP_GEN_AGG_VECT(index)                                             \
17421     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17422
17423 static int
17424 bxe_send_final_clnup(struct bxe_softc *sc,
17425                      uint8_t          clnup_func,
17426                      uint32_t         poll_cnt)
17427 {
17428     uint32_t op_gen_command = 0;
17429     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17430                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17431     int ret = 0;
17432
17433     if (REG_RD(sc, comp_addr)) {
17434         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17435         return (1);
17436     }
17437
17438     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17439     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17440     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17441     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17442
17443     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17444     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17445
17446     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17447         BLOGE(sc, "FW final cleanup did not succeed\n");
17448         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17449               (REG_RD(sc, comp_addr)));
17450         bxe_panic(sc, ("FLR cleanup failed\n"));
17451         return (1);
17452     }
17453
17454     /* Zero completion for nxt FLR */
17455     REG_WR(sc, comp_addr, 0);
17456
17457     return (ret);
17458 }
17459
17460 static void
17461 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17462                        struct pbf_pN_buf_regs *regs,
17463                        uint32_t               poll_count)
17464 {
17465     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17466     uint32_t cur_cnt = poll_count;
17467
17468     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17469     crd = crd_start = REG_RD(sc, regs->crd);
17470     init_crd = REG_RD(sc, regs->init_crd);
17471
17472     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17473     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17474     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17475
17476     while ((crd != init_crd) &&
17477            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17478             (init_crd - crd_start))) {
17479         if (cur_cnt--) {
17480             DELAY(FLR_WAIT_INTERVAL);
17481             crd = REG_RD(sc, regs->crd);
17482             crd_freed = REG_RD(sc, regs->crd_freed);
17483         } else {
17484             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17485             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17486             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17487             break;
17488         }
17489     }
17490
17491     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17492           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17493 }
17494
17495 static void
17496 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17497                        struct pbf_pN_cmd_regs *regs,
17498                        uint32_t               poll_count)
17499 {
17500     uint32_t occup, to_free, freed, freed_start;
17501     uint32_t cur_cnt = poll_count;
17502
17503     occup = to_free = REG_RD(sc, regs->lines_occup);
17504     freed = freed_start = REG_RD(sc, regs->lines_freed);
17505
17506     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17507     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17508
17509     while (occup &&
17510            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17511         if (cur_cnt--) {
17512             DELAY(FLR_WAIT_INTERVAL);
17513             occup = REG_RD(sc, regs->lines_occup);
17514             freed = REG_RD(sc, regs->lines_freed);
17515         } else {
17516             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17517             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17518             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17519             break;
17520         }
17521     }
17522
17523     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17524           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17525 }
17526
17527 static void
17528 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17529 {
17530     struct pbf_pN_cmd_regs cmd_regs[] = {
17531         {0, (CHIP_IS_E3B0(sc)) ?
17532             PBF_REG_TQ_OCCUPANCY_Q0 :
17533             PBF_REG_P0_TQ_OCCUPANCY,
17534             (CHIP_IS_E3B0(sc)) ?
17535             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17536             PBF_REG_P0_TQ_LINES_FREED_CNT},
17537         {1, (CHIP_IS_E3B0(sc)) ?
17538             PBF_REG_TQ_OCCUPANCY_Q1 :
17539             PBF_REG_P1_TQ_OCCUPANCY,
17540             (CHIP_IS_E3B0(sc)) ?
17541             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17542             PBF_REG_P1_TQ_LINES_FREED_CNT},
17543         {4, (CHIP_IS_E3B0(sc)) ?
17544             PBF_REG_TQ_OCCUPANCY_LB_Q :
17545             PBF_REG_P4_TQ_OCCUPANCY,
17546             (CHIP_IS_E3B0(sc)) ?
17547             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17548             PBF_REG_P4_TQ_LINES_FREED_CNT}
17549     };
17550
17551     struct pbf_pN_buf_regs buf_regs[] = {
17552         {0, (CHIP_IS_E3B0(sc)) ?
17553             PBF_REG_INIT_CRD_Q0 :
17554             PBF_REG_P0_INIT_CRD ,
17555             (CHIP_IS_E3B0(sc)) ?
17556             PBF_REG_CREDIT_Q0 :
17557             PBF_REG_P0_CREDIT,
17558             (CHIP_IS_E3B0(sc)) ?
17559             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17560             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17561         {1, (CHIP_IS_E3B0(sc)) ?
17562             PBF_REG_INIT_CRD_Q1 :
17563             PBF_REG_P1_INIT_CRD,
17564             (CHIP_IS_E3B0(sc)) ?
17565             PBF_REG_CREDIT_Q1 :
17566             PBF_REG_P1_CREDIT,
17567             (CHIP_IS_E3B0(sc)) ?
17568             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17569             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17570         {4, (CHIP_IS_E3B0(sc)) ?
17571             PBF_REG_INIT_CRD_LB_Q :
17572             PBF_REG_P4_INIT_CRD,
17573             (CHIP_IS_E3B0(sc)) ?
17574             PBF_REG_CREDIT_LB_Q :
17575             PBF_REG_P4_CREDIT,
17576             (CHIP_IS_E3B0(sc)) ?
17577             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17578             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17579     };
17580
17581     int i;
17582
17583     /* Verify the command queues are flushed P0, P1, P4 */
17584     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17585         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17586     }
17587
17588     /* Verify the transmission buffers are flushed P0, P1, P4 */
17589     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17590         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17591     }
17592 }
17593
17594 static void
17595 bxe_hw_enable_status(struct bxe_softc *sc)
17596 {
17597     uint32_t val;
17598
17599     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17600     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17601
17602     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17603     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17604
17605     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17606     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17607
17608     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17609     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17610
17611     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17612     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17613
17614     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17615     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17616
17617     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17618     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17619
17620     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17621     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17622 }
17623
17624 static int
17625 bxe_pf_flr_clnup(struct bxe_softc *sc)
17626 {
17627     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17628
17629     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17630
17631     /* Re-enable PF target read access */
17632     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17633
17634     /* Poll HW usage counters */
17635     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17636     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17637         return (-1);
17638     }
17639
17640     /* Zero the igu 'trailing edge' and 'leading edge' */
17641
17642     /* Send the FW cleanup command */
17643     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17644         return (-1);
17645     }
17646
17647     /* ATC cleanup */
17648
17649     /* Verify TX hw is flushed */
17650     bxe_tx_hw_flushed(sc, poll_cnt);
17651
17652     /* Wait 100ms (not adjusted according to platform) */
17653     DELAY(100000);
17654
17655     /* Verify no pending pci transactions */
17656     if (bxe_is_pcie_pending(sc)) {
17657         BLOGE(sc, "PCIE Transactions still pending\n");
17658     }
17659
17660     /* Debug */
17661     bxe_hw_enable_status(sc);
17662
17663     /*
17664      * Master enable - Due to WB DMAE writes performed before this
17665      * register is re-initialized as part of the regular function init
17666      */
17667     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17668
17669     return (0);
17670 }
17671
17672 static int
17673 bxe_init_hw_func(struct bxe_softc *sc)
17674 {
17675     int port = SC_PORT(sc);
17676     int func = SC_FUNC(sc);
17677     int init_phase = PHASE_PF0 + func;
17678     struct ecore_ilt *ilt = sc->ilt;
17679     uint16_t cdu_ilt_start;
17680     uint32_t addr, val;
17681     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17682     int i, main_mem_width, rc;
17683
17684     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17685
17686     /* FLR cleanup */
17687     if (!CHIP_IS_E1x(sc)) {
17688         rc = bxe_pf_flr_clnup(sc);
17689         if (rc) {
17690             BLOGE(sc, "FLR cleanup failed!\n");
17691             // XXX bxe_fw_dump(sc);
17692             // XXX bxe_idle_chk(sc);
17693             return (rc);
17694         }
17695     }
17696
17697     /* set MSI reconfigure capability */
17698     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17699         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17700         val = REG_RD(sc, addr);
17701         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17702         REG_WR(sc, addr, val);
17703     }
17704
17705     ecore_init_block(sc, BLOCK_PXP, init_phase);
17706     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17707
17708     ilt = sc->ilt;
17709     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17710
17711     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17712         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17713         ilt->lines[cdu_ilt_start + i].page_mapping =
17714             sc->context[i].vcxt_dma.paddr;
17715         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17716     }
17717     ecore_ilt_init_op(sc, INITOP_SET);
17718
17719     /* Set NIC mode */
17720     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17721     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17722
17723     if (!CHIP_IS_E1x(sc)) {
17724         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17725
17726         /* Turn on a single ISR mode in IGU if driver is going to use
17727          * INT#x or MSI
17728          */
17729         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17730             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17731         }
17732
17733         /*
17734          * Timers workaround bug: function init part.
17735          * Need to wait 20msec after initializing ILT,
17736          * needed to make sure there are no requests in
17737          * one of the PXP internal queues with "old" ILT addresses
17738          */
17739         DELAY(20000);
17740
17741         /*
17742          * Master enable - Due to WB DMAE writes performed before this
17743          * register is re-initialized as part of the regular function
17744          * init
17745          */
17746         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17747         /* Enable the function in IGU */
17748         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17749     }
17750
17751     sc->dmae_ready = 1;
17752
17753     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17754
17755     if (!CHIP_IS_E1x(sc))
17756         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17757
17758     ecore_init_block(sc, BLOCK_ATC, init_phase);
17759     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17760     ecore_init_block(sc, BLOCK_NIG, init_phase);
17761     ecore_init_block(sc, BLOCK_SRC, init_phase);
17762     ecore_init_block(sc, BLOCK_MISC, init_phase);
17763     ecore_init_block(sc, BLOCK_TCM, init_phase);
17764     ecore_init_block(sc, BLOCK_UCM, init_phase);
17765     ecore_init_block(sc, BLOCK_CCM, init_phase);
17766     ecore_init_block(sc, BLOCK_XCM, init_phase);
17767     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17768     ecore_init_block(sc, BLOCK_USEM, init_phase);
17769     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17770     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17771
17772     if (!CHIP_IS_E1x(sc))
17773         REG_WR(sc, QM_REG_PF_EN, 1);
17774
17775     if (!CHIP_IS_E1x(sc)) {
17776         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17777         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17778         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17779         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17780     }
17781     ecore_init_block(sc, BLOCK_QM, init_phase);
17782
17783     ecore_init_block(sc, BLOCK_TM, init_phase);
17784     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17785
17786     bxe_iov_init_dq(sc);
17787
17788     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17789     ecore_init_block(sc, BLOCK_PRS, init_phase);
17790     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17791     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17792     ecore_init_block(sc, BLOCK_USDM, init_phase);
17793     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17794     ecore_init_block(sc, BLOCK_UPB, init_phase);
17795     ecore_init_block(sc, BLOCK_XPB, init_phase);
17796     ecore_init_block(sc, BLOCK_PBF, init_phase);
17797     if (!CHIP_IS_E1x(sc))
17798         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17799
17800     ecore_init_block(sc, BLOCK_CDU, init_phase);
17801
17802     ecore_init_block(sc, BLOCK_CFC, init_phase);
17803
17804     if (!CHIP_IS_E1x(sc))
17805         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17806
17807     if (IS_MF(sc)) {
17808         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17809         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17810     }
17811
17812     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17813
17814     /* HC init per function */
17815     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17816         if (CHIP_IS_E1H(sc)) {
17817             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17818
17819             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17820             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17821         }
17822         ecore_init_block(sc, BLOCK_HC, init_phase);
17823
17824     } else {
17825         int num_segs, sb_idx, prod_offset;
17826
17827         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17828
17829         if (!CHIP_IS_E1x(sc)) {
17830             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17831             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17832         }
17833
17834         ecore_init_block(sc, BLOCK_IGU, init_phase);
17835
17836         if (!CHIP_IS_E1x(sc)) {
17837             int dsb_idx = 0;
17838             /**
17839              * Producer memory:
17840              * E2 mode: address 0-135 match to the mapping memory;
17841              * 136 - PF0 default prod; 137 - PF1 default prod;
17842              * 138 - PF2 default prod; 139 - PF3 default prod;
17843              * 140 - PF0 attn prod;    141 - PF1 attn prod;
17844              * 142 - PF2 attn prod;    143 - PF3 attn prod;
17845              * 144-147 reserved.
17846              *
17847              * E1.5 mode - In backward compatible mode;
17848              * for non default SB; each even line in the memory
17849              * holds the U producer and each odd line hold
17850              * the C producer. The first 128 producers are for
17851              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
17852              * producers are for the DSB for each PF.
17853              * Each PF has five segments: (the order inside each
17854              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
17855              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
17856              * 144-147 attn prods;
17857              */
17858             /* non-default-status-blocks */
17859             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17860                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
17861             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
17862                 prod_offset = (sc->igu_base_sb + sb_idx) *
17863                     num_segs;
17864
17865                 for (i = 0; i < num_segs; i++) {
17866                     addr = IGU_REG_PROD_CONS_MEMORY +
17867                             (prod_offset + i) * 4;
17868                     REG_WR(sc, addr, 0);
17869                 }
17870                 /* send consumer update with value 0 */
17871                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
17872                            USTORM_ID, 0, IGU_INT_NOP, 1);
17873                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
17874             }
17875
17876             /* default-status-blocks */
17877             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17878                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
17879
17880             if (CHIP_IS_MODE_4_PORT(sc))
17881                 dsb_idx = SC_FUNC(sc);
17882             else
17883                 dsb_idx = SC_VN(sc);
17884
17885             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
17886                        IGU_BC_BASE_DSB_PROD + dsb_idx :
17887                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
17888
17889             /*
17890              * igu prods come in chunks of E1HVN_MAX (4) -
17891              * does not matters what is the current chip mode
17892              */
17893             for (i = 0; i < (num_segs * E1HVN_MAX);
17894                  i += E1HVN_MAX) {
17895                 addr = IGU_REG_PROD_CONS_MEMORY +
17896                             (prod_offset + i)*4;
17897                 REG_WR(sc, addr, 0);
17898             }
17899             /* send consumer update with 0 */
17900             if (CHIP_INT_MODE_IS_BC(sc)) {
17901                 bxe_ack_sb(sc, sc->igu_dsb_id,
17902                            USTORM_ID, 0, IGU_INT_NOP, 1);
17903                 bxe_ack_sb(sc, sc->igu_dsb_id,
17904                            CSTORM_ID, 0, IGU_INT_NOP, 1);
17905                 bxe_ack_sb(sc, sc->igu_dsb_id,
17906                            XSTORM_ID, 0, IGU_INT_NOP, 1);
17907                 bxe_ack_sb(sc, sc->igu_dsb_id,
17908                            TSTORM_ID, 0, IGU_INT_NOP, 1);
17909                 bxe_ack_sb(sc, sc->igu_dsb_id,
17910                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17911             } else {
17912                 bxe_ack_sb(sc, sc->igu_dsb_id,
17913                            USTORM_ID, 0, IGU_INT_NOP, 1);
17914                 bxe_ack_sb(sc, sc->igu_dsb_id,
17915                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17916             }
17917             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
17918
17919             /* !!! these should become driver const once
17920                rf-tool supports split-68 const */
17921             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
17922             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
17923             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
17924             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
17925             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
17926             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
17927         }
17928     }
17929
17930     /* Reset PCIE errors for debug */
17931     REG_WR(sc, 0x2114, 0xffffffff);
17932     REG_WR(sc, 0x2120, 0xffffffff);
17933
17934     if (CHIP_IS_E1x(sc)) {
17935         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
17936         main_mem_base = HC_REG_MAIN_MEMORY +
17937                 SC_PORT(sc) * (main_mem_size * 4);
17938         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
17939         main_mem_width = 8;
17940
17941         val = REG_RD(sc, main_mem_prty_clr);
17942         if (val) {
17943             BLOGD(sc, DBG_LOAD,
17944                   "Parity errors in HC block during function init (0x%x)!\n",
17945                   val);
17946         }
17947
17948         /* Clear "false" parity errors in MSI-X table */
17949         for (i = main_mem_base;
17950              i < main_mem_base + main_mem_size * 4;
17951              i += main_mem_width) {
17952             bxe_read_dmae(sc, i, main_mem_width / 4);
17953             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
17954                            i, main_mem_width / 4);
17955         }
17956         /* Clear HC parity attention */
17957         REG_RD(sc, main_mem_prty_clr);
17958     }
17959
17960 #if 1
17961     /* Enable STORMs SP logging */
17962     REG_WR8(sc, BAR_USTRORM_INTMEM +
17963            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17964     REG_WR8(sc, BAR_TSTRORM_INTMEM +
17965            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17966     REG_WR8(sc, BAR_CSTRORM_INTMEM +
17967            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17968     REG_WR8(sc, BAR_XSTRORM_INTMEM +
17969            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17970 #endif
17971
17972     elink_phy_probe(&sc->link_params);
17973
17974     return (0);
17975 }
17976
17977 static void
17978 bxe_link_reset(struct bxe_softc *sc)
17979 {
17980     if (!BXE_NOMCP(sc)) {
17981         bxe_acquire_phy_lock(sc);
17982         elink_lfa_reset(&sc->link_params, &sc->link_vars);
17983         bxe_release_phy_lock(sc);
17984     } else {
17985         if (!CHIP_REV_IS_SLOW(sc)) {
17986             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
17987         }
17988     }
17989 }
17990
17991 static void
17992 bxe_reset_port(struct bxe_softc *sc)
17993 {
17994     int port = SC_PORT(sc);
17995     uint32_t val;
17996
17997     /* reset physical Link */
17998     bxe_link_reset(sc);
17999
18000     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18001
18002     /* Do not rcv packets to BRB */
18003     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18004     /* Do not direct rcv packets that are not for MCP to the BRB */
18005     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18006                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18007
18008     /* Configure AEU */
18009     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18010
18011     DELAY(100000);
18012
18013     /* Check for BRB port occupancy */
18014     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18015     if (val) {
18016         BLOGD(sc, DBG_LOAD,
18017               "BRB1 is not empty, %d blocks are occupied\n", val);
18018     }
18019
18020     /* TODO: Close Doorbell port? */
18021 }
18022
18023 static void
18024 bxe_ilt_wr(struct bxe_softc *sc,
18025            uint32_t         index,
18026            bus_addr_t       addr)
18027 {
18028     int reg;
18029     uint32_t wb_write[2];
18030
18031     if (CHIP_IS_E1(sc)) {
18032         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18033     } else {
18034         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18035     }
18036
18037     wb_write[0] = ONCHIP_ADDR1(addr);
18038     wb_write[1] = ONCHIP_ADDR2(addr);
18039     REG_WR_DMAE(sc, reg, wb_write, 2);
18040 }
18041
18042 static void
18043 bxe_clear_func_ilt(struct bxe_softc *sc,
18044                    uint32_t         func)
18045 {
18046     uint32_t i, base = FUNC_ILT_BASE(func);
18047     for (i = base; i < base + ILT_PER_FUNC; i++) {
18048         bxe_ilt_wr(sc, i, 0);
18049     }
18050 }
18051
18052 static void
18053 bxe_reset_func(struct bxe_softc *sc)
18054 {
18055     struct bxe_fastpath *fp;
18056     int port = SC_PORT(sc);
18057     int func = SC_FUNC(sc);
18058     int i;
18059
18060     /* Disable the function in the FW */
18061     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18062     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18063     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18064     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18065
18066     /* FP SBs */
18067     FOR_EACH_ETH_QUEUE(sc, i) {
18068         fp = &sc->fp[i];
18069         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18070                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18071                 SB_DISABLED);
18072     }
18073
18074     /* SP SB */
18075     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18076             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18077             SB_DISABLED);
18078
18079     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18080         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18081     }
18082
18083     /* Configure IGU */
18084     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18085         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18086         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18087     } else {
18088         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18089         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18090     }
18091
18092     if (CNIC_LOADED(sc)) {
18093         /* Disable Timer scan */
18094         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18095         /*
18096          * Wait for at least 10ms and up to 2 second for the timers
18097          * scan to complete
18098          */
18099         for (i = 0; i < 200; i++) {
18100             DELAY(10000);
18101             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18102                 break;
18103         }
18104     }
18105
18106     /* Clear ILT */
18107     bxe_clear_func_ilt(sc, func);
18108
18109     /*
18110      * Timers workaround bug for E2: if this is vnic-3,
18111      * we need to set the entire ilt range for this timers.
18112      */
18113     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18114         struct ilt_client_info ilt_cli;
18115         /* use dummy TM client */
18116         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18117         ilt_cli.start = 0;
18118         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18119         ilt_cli.client_num = ILT_CLIENT_TM;
18120
18121         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18122     }
18123
18124     /* this assumes that reset_port() called before reset_func()*/
18125     if (!CHIP_IS_E1x(sc)) {
18126         bxe_pf_disable(sc);
18127     }
18128
18129     sc->dmae_ready = 0;
18130 }
18131
18132 static int
18133 bxe_gunzip_init(struct bxe_softc *sc)
18134 {
18135     return (0);
18136 }
18137
18138 static void
18139 bxe_gunzip_end(struct bxe_softc *sc)
18140 {
18141     return;
18142 }
18143
18144 static int
18145 bxe_init_firmware(struct bxe_softc *sc)
18146 {
18147     if (CHIP_IS_E1(sc)) {
18148         ecore_init_e1_firmware(sc);
18149         sc->iro_array = e1_iro_arr;
18150     } else if (CHIP_IS_E1H(sc)) {
18151         ecore_init_e1h_firmware(sc);
18152         sc->iro_array = e1h_iro_arr;
18153     } else if (!CHIP_IS_E1x(sc)) {
18154         ecore_init_e2_firmware(sc);
18155         sc->iro_array = e2_iro_arr;
18156     } else {
18157         BLOGE(sc, "Unsupported chip revision\n");
18158         return (-1);
18159     }
18160
18161     return (0);
18162 }
18163
18164 static void
18165 bxe_release_firmware(struct bxe_softc *sc)
18166 {
18167     /* Do nothing */
18168     return;
18169 }
18170
18171 static int
18172 ecore_gunzip(struct bxe_softc *sc,
18173              const uint8_t    *zbuf,
18174              int              len)
18175 {
18176     /* XXX : Implement... */
18177     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18178     return (FALSE);
18179 }
18180
18181 static void
18182 ecore_reg_wr_ind(struct bxe_softc *sc,
18183                  uint32_t         addr,
18184                  uint32_t         val)
18185 {
18186     bxe_reg_wr_ind(sc, addr, val);
18187 }
18188
18189 static void
18190 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18191                           bus_addr_t       phys_addr,
18192                           uint32_t         addr,
18193                           uint32_t         len)
18194 {
18195     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18196 }
18197
18198 void
18199 ecore_storm_memset_struct(struct bxe_softc *sc,
18200                           uint32_t         addr,
18201                           size_t           size,
18202                           uint32_t         *data)
18203 {
18204     uint8_t i;
18205     for (i = 0; i < size/4; i++) {
18206         REG_WR(sc, addr + (i * 4), data[i]);
18207     }
18208 }
18209
18210
18211 /*
18212  * character device - ioctl interface definitions
18213  */
18214
18215
18216 #include "bxe_dump.h"
18217 #include "bxe_ioctl.h"
18218 #include <sys/conf.h>
18219
18220 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18221                 struct thread *td);
18222
18223 static struct cdevsw bxe_cdevsw = {
18224     .d_version = D_VERSION,
18225     .d_ioctl = bxe_eioctl,
18226     .d_name = "bxecnic",
18227 };
18228
18229 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18230
18231
18232 #define DUMP_ALL_PRESETS        0x1FFF
18233 #define DUMP_MAX_PRESETS        13
18234 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18235 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18236 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18237 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18238 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18239
18240 #define IS_REG_IN_PRESET(presets, idx)  \
18241                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18242
18243
18244 static int
18245 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18246 {
18247     if (CHIP_IS_E1(sc))
18248         return dump_num_registers[0][preset-1];
18249     else if (CHIP_IS_E1H(sc))
18250         return dump_num_registers[1][preset-1];
18251     else if (CHIP_IS_E2(sc))
18252         return dump_num_registers[2][preset-1];
18253     else if (CHIP_IS_E3A0(sc))
18254         return dump_num_registers[3][preset-1];
18255     else if (CHIP_IS_E3B0(sc))
18256         return dump_num_registers[4][preset-1];
18257     else
18258         return 0;
18259 }
18260
18261 static int
18262 bxe_get_total_regs_len32(struct bxe_softc *sc)
18263 {
18264     uint32_t preset_idx;
18265     int regdump_len32 = 0;
18266
18267
18268     /* Calculate the total preset regs length */
18269     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18270         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18271     }
18272
18273     return regdump_len32;
18274 }
18275
18276 static const uint32_t *
18277 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18278 {
18279     if (CHIP_IS_E2(sc))
18280         return page_vals_e2;
18281     else if (CHIP_IS_E3(sc))
18282         return page_vals_e3;
18283     else
18284         return NULL;
18285 }
18286
18287 static uint32_t
18288 __bxe_get_page_reg_num(struct bxe_softc *sc)
18289 {
18290     if (CHIP_IS_E2(sc))
18291         return PAGE_MODE_VALUES_E2;
18292     else if (CHIP_IS_E3(sc))
18293         return PAGE_MODE_VALUES_E3;
18294     else
18295         return 0;
18296 }
18297
18298 static const uint32_t *
18299 __bxe_get_page_write_ar(struct bxe_softc *sc)
18300 {
18301     if (CHIP_IS_E2(sc))
18302         return page_write_regs_e2;
18303     else if (CHIP_IS_E3(sc))
18304         return page_write_regs_e3;
18305     else
18306         return NULL;
18307 }
18308
18309 static uint32_t
18310 __bxe_get_page_write_num(struct bxe_softc *sc)
18311 {
18312     if (CHIP_IS_E2(sc))
18313         return PAGE_WRITE_REGS_E2;
18314     else if (CHIP_IS_E3(sc))
18315         return PAGE_WRITE_REGS_E3;
18316     else
18317         return 0;
18318 }
18319
18320 static const struct reg_addr *
18321 __bxe_get_page_read_ar(struct bxe_softc *sc)
18322 {
18323     if (CHIP_IS_E2(sc))
18324         return page_read_regs_e2;
18325     else if (CHIP_IS_E3(sc))
18326         return page_read_regs_e3;
18327     else
18328         return NULL;
18329 }
18330
18331 static uint32_t
18332 __bxe_get_page_read_num(struct bxe_softc *sc)
18333 {
18334     if (CHIP_IS_E2(sc))
18335         return PAGE_READ_REGS_E2;
18336     else if (CHIP_IS_E3(sc))
18337         return PAGE_READ_REGS_E3;
18338     else
18339         return 0;
18340 }
18341
18342 static bool
18343 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18344 {
18345     if (CHIP_IS_E1(sc))
18346         return IS_E1_REG(reg_info->chips);
18347     else if (CHIP_IS_E1H(sc))
18348         return IS_E1H_REG(reg_info->chips);
18349     else if (CHIP_IS_E2(sc))
18350         return IS_E2_REG(reg_info->chips);
18351     else if (CHIP_IS_E3A0(sc))
18352         return IS_E3A0_REG(reg_info->chips);
18353     else if (CHIP_IS_E3B0(sc))
18354         return IS_E3B0_REG(reg_info->chips);
18355     else
18356         return 0;
18357 }
18358
18359 static bool
18360 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18361 {
18362     if (CHIP_IS_E1(sc))
18363         return IS_E1_REG(wreg_info->chips);
18364     else if (CHIP_IS_E1H(sc))
18365         return IS_E1H_REG(wreg_info->chips);
18366     else if (CHIP_IS_E2(sc))
18367         return IS_E2_REG(wreg_info->chips);
18368     else if (CHIP_IS_E3A0(sc))
18369         return IS_E3A0_REG(wreg_info->chips);
18370     else if (CHIP_IS_E3B0(sc))
18371         return IS_E3B0_REG(wreg_info->chips);
18372     else
18373         return 0;
18374 }
18375
18376 /**
18377  * bxe_read_pages_regs - read "paged" registers
18378  *
18379  * @bp          device handle
18380  * @p           output buffer
18381  *
18382  * Reads "paged" memories: memories that may only be read by first writing to a
18383  * specific address ("write address") and then reading from a specific address
18384  * ("read address"). There may be more than one write address per "page" and
18385  * more than one read address per write address.
18386  */
18387 static void
18388 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18389 {
18390     uint32_t i, j, k, n;
18391
18392     /* addresses of the paged registers */
18393     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18394     /* number of paged registers */
18395     int num_pages = __bxe_get_page_reg_num(sc);
18396     /* write addresses */
18397     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18398     /* number of write addresses */
18399     int write_num = __bxe_get_page_write_num(sc);
18400     /* read addresses info */
18401     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18402     /* number of read addresses */
18403     int read_num = __bxe_get_page_read_num(sc);
18404     uint32_t addr, size;
18405
18406     for (i = 0; i < num_pages; i++) {
18407         for (j = 0; j < write_num; j++) {
18408             REG_WR(sc, write_addr[j], page_addr[i]);
18409
18410             for (k = 0; k < read_num; k++) {
18411                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18412                     size = read_addr[k].size;
18413                     for (n = 0; n < size; n++) {
18414                         addr = read_addr[k].addr + n*4;
18415                         *p++ = REG_RD(sc, addr);
18416                     }
18417                 }
18418             }
18419         }
18420     }
18421     return;
18422 }
18423
18424
18425 static int
18426 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18427 {
18428     uint32_t i, j, addr;
18429     const struct wreg_addr *wreg_addr_p = NULL;
18430
18431     if (CHIP_IS_E1(sc))
18432         wreg_addr_p = &wreg_addr_e1;
18433     else if (CHIP_IS_E1H(sc))
18434         wreg_addr_p = &wreg_addr_e1h;
18435     else if (CHIP_IS_E2(sc))
18436         wreg_addr_p = &wreg_addr_e2;
18437     else if (CHIP_IS_E3A0(sc))
18438         wreg_addr_p = &wreg_addr_e3;
18439     else if (CHIP_IS_E3B0(sc))
18440         wreg_addr_p = &wreg_addr_e3b0;
18441     else
18442         return (-1);
18443
18444     /* Read the idle_chk registers */
18445     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18446         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18447             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18448             for (j = 0; j < idle_reg_addrs[i].size; j++)
18449                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18450         }
18451     }
18452
18453     /* Read the regular registers */
18454     for (i = 0; i < REGS_COUNT; i++) {
18455         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18456             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18457             for (j = 0; j < reg_addrs[i].size; j++)
18458                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18459         }
18460     }
18461
18462     /* Read the CAM registers */
18463     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18464         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18465         for (i = 0; i < wreg_addr_p->size; i++) {
18466             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18467
18468             /* In case of wreg_addr register, read additional
18469                registers from read_regs array
18470              */
18471             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18472                 addr = *(wreg_addr_p->read_regs);
18473                 *p++ = REG_RD(sc, addr + j*4);
18474             }
18475         }
18476     }
18477
18478     /* Paged registers are supported in E2 & E3 only */
18479     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18480         /* Read "paged" registers */
18481         bxe_read_pages_regs(sc, p, preset);
18482     }
18483
18484     return 0;
18485 }
18486
18487 int
18488 bxe_grc_dump(struct bxe_softc *sc)
18489 {
18490     int rval = 0;
18491     uint32_t preset_idx;
18492     uint8_t *buf;
18493     uint32_t size;
18494     struct  dump_header *d_hdr;
18495     uint32_t i;
18496     uint32_t reg_val;
18497     uint32_t reg_addr;
18498     uint32_t cmd_offset;
18499     int context_size;
18500     int allocated;
18501     struct ecore_ilt *ilt = SC_ILT(sc);
18502     struct bxe_fastpath *fp;
18503     struct ilt_client_info *ilt_cli;
18504     int grc_dump_size;
18505
18506
18507     if (sc->grcdump_done || sc->grcdump_started)
18508         return (rval);
18509     
18510     sc->grcdump_started = 1;
18511     BLOGI(sc, "Started collecting grcdump\n");
18512
18513     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18514                 sizeof(struct  dump_header);
18515
18516     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18517
18518     if (sc->grc_dump == NULL) {
18519         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18520         return(ENOMEM);
18521     }
18522
18523
18524
18525     /* Disable parity attentions as long as following dump may
18526      * cause false alarms by reading never written registers. We
18527      * will re-enable parity attentions right after the dump.
18528      */
18529
18530     /* Disable parity on path 0 */
18531     bxe_pretend_func(sc, 0);
18532
18533     ecore_disable_blocks_parity(sc);
18534
18535     /* Disable parity on path 1 */
18536     bxe_pretend_func(sc, 1);
18537     ecore_disable_blocks_parity(sc);
18538
18539     /* Return to current function */
18540     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18541
18542     buf = sc->grc_dump;
18543     d_hdr = sc->grc_dump;
18544
18545     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18546     d_hdr->version = BNX2X_DUMP_VERSION;
18547     d_hdr->preset = DUMP_ALL_PRESETS;
18548
18549     if (CHIP_IS_E1(sc)) {
18550         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18551     } else if (CHIP_IS_E1H(sc)) {
18552         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18553     } else if (CHIP_IS_E2(sc)) {
18554         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18555                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18556     } else if (CHIP_IS_E3A0(sc)) {
18557         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18558                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18559     } else if (CHIP_IS_E3B0(sc)) {
18560         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18561                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18562     }
18563
18564     buf += sizeof(struct  dump_header);
18565
18566     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18567
18568         /* Skip presets with IOR */
18569         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18570             (preset_idx == 11))
18571             continue;
18572
18573         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18574
18575         if (rval)
18576             break;
18577
18578         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18579
18580         buf += size;
18581     }
18582
18583     bxe_pretend_func(sc, 0);
18584     ecore_clear_blocks_parity(sc);
18585     ecore_enable_blocks_parity(sc);
18586
18587     bxe_pretend_func(sc, 1);
18588     ecore_clear_blocks_parity(sc);
18589     ecore_enable_blocks_parity(sc);
18590
18591     /* Return to current function */
18592     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18593
18594
18595     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
18596     for (i = 0, allocated = 0; allocated < context_size; i++) {
18597
18598         BLOGI(sc, "cdu_context i %d paddr %#jx vaddr %p size 0x%zx\n", i,
18599             (uintmax_t)sc->context[i].vcxt_dma.paddr,
18600             sc->context[i].vcxt_dma.vaddr,
18601             sc->context[i].size);
18602         allocated += sc->context[i].size;
18603     }
18604     BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18605         (uintmax_t)sc->fw_stats_req_mapping,
18606         (uintmax_t)sc->fw_stats_data_mapping,
18607         sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18608     BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18609         (void *)sc->def_sb_dma.paddr, sc->def_sb,
18610         sizeof(struct host_sp_status_block));
18611     BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18612         (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18613     BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18614         (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18615         sizeof(struct bxe_slowpath));
18616     BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18617         (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18618     BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18619         (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18620         FW_BUF_SIZE);
18621     for (i = 0; i < sc->num_queues; i++) {
18622         fp = &sc->fp[i];
18623         BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18624             (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18625             sizeof(union bxe_host_hc_status_block));
18626         BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18627             (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18628             (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18629         BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18630             (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18631             (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18632         BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18633             (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18634             (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18635         BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18636             (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18637             (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18638     }
18639
18640     ilt_cli = &ilt->clients[1];
18641     for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18642         BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18643             (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18644             ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18645     }
18646
18647
18648     cmd_offset = DMAE_REG_CMD_MEM;
18649     for (i = 0; i < 224; i++) {
18650         reg_addr = (cmd_offset +(i * 4));
18651         reg_val = REG_RD(sc, reg_addr);
18652         BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18653             reg_addr, reg_val);
18654     }
18655
18656
18657     BLOGI(sc, "Collection of grcdump done\n");
18658     sc->grcdump_done = 1;
18659     return(rval);
18660 }
18661
18662 static int
18663 bxe_add_cdev(struct bxe_softc *sc)
18664 {
18665     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18666
18667     if (sc->eeprom == NULL) {
18668         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18669         return (-1);
18670     }
18671
18672     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18673                             sc->ifp->if_dunit,
18674                             UID_ROOT,
18675                             GID_WHEEL,
18676                             0600,
18677                             "%s",
18678                             if_name(sc->ifp));
18679
18680     if (sc->ioctl_dev == NULL) {
18681         free(sc->eeprom, M_DEVBUF);
18682         sc->eeprom = NULL;
18683         return (-1);
18684     }
18685
18686     sc->ioctl_dev->si_drv1 = sc;
18687
18688     return (0);
18689 }
18690
18691 static void
18692 bxe_del_cdev(struct bxe_softc *sc)
18693 {
18694     if (sc->ioctl_dev != NULL)
18695         destroy_dev(sc->ioctl_dev);
18696
18697     if (sc->eeprom != NULL) {
18698         free(sc->eeprom, M_DEVBUF);
18699         sc->eeprom = NULL;
18700     }
18701     sc->ioctl_dev = NULL;
18702
18703     return;
18704 }
18705
18706 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18707 {
18708
18709     if ((if_getdrvflags(sc->ifp) & IFF_DRV_RUNNING) == 0)
18710         return FALSE;
18711
18712     return TRUE;
18713 }
18714
18715
18716 static int
18717 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18718 {
18719     int rval = 0;
18720
18721     if(!bxe_is_nvram_accessible(sc)) {
18722         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18723         return (-EAGAIN);
18724     }
18725     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18726
18727
18728    return (rval);
18729 }
18730
18731 static int
18732 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18733 {
18734     int rval = 0;
18735
18736     if(!bxe_is_nvram_accessible(sc)) {
18737         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18738         return (-EAGAIN);
18739     }
18740     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18741
18742    return (rval);
18743 }
18744
18745 static int
18746 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18747 {
18748     int rval = 0;
18749
18750     switch (eeprom->eeprom_cmd) {
18751
18752     case BXE_EEPROM_CMD_SET_EEPROM:
18753
18754         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18755                        eeprom->eeprom_data_len);
18756
18757         if (rval)
18758             break;
18759
18760         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18761                        eeprom->eeprom_data_len);
18762         break;
18763
18764     case BXE_EEPROM_CMD_GET_EEPROM:
18765
18766         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18767                        eeprom->eeprom_data_len);
18768
18769         if (rval) {
18770             break;
18771         }
18772
18773         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18774                        eeprom->eeprom_data_len);
18775         break;
18776
18777     default:
18778             rval = EINVAL;
18779             break;
18780     }
18781
18782     if (rval) {
18783         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18784     }
18785
18786     return (rval);
18787 }
18788
18789 static int
18790 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18791 {
18792     uint32_t ext_phy_config;
18793     int port = SC_PORT(sc);
18794     int cfg_idx = bxe_get_link_cfg_idx(sc);
18795
18796     dev_p->supported = sc->port.supported[cfg_idx] |
18797             (sc->port.supported[cfg_idx ^ 1] &
18798             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18799     dev_p->advertising = sc->port.advertising[cfg_idx];
18800     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18801         ELINK_ETH_PHY_SFP_1G_FIBER) {
18802         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18803         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18804     }
18805     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18806         !(sc->flags & BXE_MF_FUNC_DIS)) {
18807         dev_p->duplex = sc->link_vars.duplex;
18808         if (IS_MF(sc) && !BXE_NOMCP(sc))
18809             dev_p->speed = bxe_get_mf_speed(sc);
18810         else
18811             dev_p->speed = sc->link_vars.line_speed;
18812     } else {
18813         dev_p->duplex = DUPLEX_UNKNOWN;
18814         dev_p->speed = SPEED_UNKNOWN;
18815     }
18816
18817     dev_p->port = bxe_media_detect(sc);
18818
18819     ext_phy_config = SHMEM_RD(sc,
18820                          dev_info.port_hw_config[port].external_phy_config);
18821     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
18822         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
18823         dev_p->phy_address =  sc->port.phy_addr;
18824     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18825             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
18826         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18827             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
18828         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
18829     else
18830         dev_p->phy_address = 0;
18831
18832     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
18833         dev_p->autoneg = AUTONEG_ENABLE;
18834     else
18835        dev_p->autoneg = AUTONEG_DISABLE;
18836
18837
18838     return 0;
18839 }
18840
18841 static int
18842 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18843         struct thread *td)
18844 {
18845     struct bxe_softc    *sc;
18846     int                 rval = 0;
18847     device_t            pci_dev;
18848     bxe_grcdump_t       *dump = NULL;
18849     int grc_dump_size;
18850     bxe_drvinfo_t   *drv_infop = NULL;
18851     bxe_dev_setting_t  *dev_p;
18852     bxe_dev_setting_t  dev_set;
18853     bxe_get_regs_t  *reg_p;
18854     bxe_reg_rdw_t *reg_rdw_p;
18855     bxe_pcicfg_rdw_t *cfg_rdw_p;
18856     bxe_perm_mac_addr_t *mac_addr_p;
18857
18858
18859     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18860         return ENXIO;
18861
18862     pci_dev= sc->dev;
18863
18864     dump = (bxe_grcdump_t *)data;
18865
18866     switch(cmd) {
18867
18868         case BXE_GRC_DUMP_SIZE:
18869             dump->pci_func = sc->pcie_func;
18870             dump->grcdump_size =
18871                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18872                      sizeof(struct  dump_header);
18873             break;
18874
18875         case BXE_GRC_DUMP:
18876             
18877             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18878                                 sizeof(struct  dump_header);
18879             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
18880                 (dump->grcdump_size < grc_dump_size)) {
18881                 rval = EINVAL;
18882                 break;
18883             }
18884
18885             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
18886                 (!sc->grcdump_started)) {
18887                 rval =  bxe_grc_dump(sc);
18888             }
18889
18890             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
18891                 (sc->grc_dump != NULL))  {
18892                 dump->grcdump_dwords = grc_dump_size >> 2;
18893                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18894                 free(sc->grc_dump, M_DEVBUF);
18895                 sc->grc_dump = NULL;
18896                 sc->grcdump_started = 0;
18897                 sc->grcdump_done = 0;
18898             }
18899
18900             break;
18901
18902         case BXE_DRV_INFO:
18903             drv_infop = (bxe_drvinfo_t *)data;
18904             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
18905             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
18906                 BXE_DRIVER_VERSION);
18907             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
18908                 sc->devinfo.bc_ver_str);
18909             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
18910                 "%s", sc->fw_ver_str);
18911             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
18912             drv_infop->reg_dump_len =
18913                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
18914                     + sizeof(struct  dump_header);
18915             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
18916                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
18917             break;
18918
18919         case BXE_DEV_SETTING:
18920             dev_p = (bxe_dev_setting_t *)data;
18921             bxe_get_settings(sc, &dev_set);
18922             dev_p->supported = dev_set.supported;
18923             dev_p->advertising = dev_set.advertising;
18924             dev_p->speed = dev_set.speed;
18925             dev_p->duplex = dev_set.duplex;
18926             dev_p->port = dev_set.port;
18927             dev_p->phy_address = dev_set.phy_address;
18928             dev_p->autoneg = dev_set.autoneg;
18929
18930             break;
18931
18932         case BXE_GET_REGS:
18933
18934             reg_p = (bxe_get_regs_t *)data;
18935             grc_dump_size = reg_p->reg_buf_len;
18936
18937             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
18938                 bxe_grc_dump(sc);
18939             }
18940             if((sc->grcdump_done) && (sc->grcdump_started) &&
18941                 (sc->grc_dump != NULL))  {
18942                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
18943                 free(sc->grc_dump, M_DEVBUF);
18944                 sc->grc_dump = NULL;
18945                 sc->grcdump_started = 0;
18946                 sc->grcdump_done = 0;
18947             }
18948
18949             break;
18950
18951         case BXE_RDW_REG:
18952             reg_rdw_p = (bxe_reg_rdw_t *)data;
18953             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
18954                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18955                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
18956
18957             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
18958                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
18959                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
18960
18961             break;
18962
18963         case BXE_RDW_PCICFG:
18964             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
18965             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
18966
18967                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
18968                                          cfg_rdw_p->cfg_width);
18969
18970             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
18971                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
18972                             cfg_rdw_p->cfg_width);
18973             } else {
18974                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
18975             }
18976             break;
18977
18978         case BXE_MAC_ADDR:
18979             mac_addr_p = (bxe_perm_mac_addr_t *)data;
18980             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
18981                 sc->mac_addr_str);
18982             break;
18983
18984         case BXE_EEPROM:
18985             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
18986             break;
18987
18988
18989         default:
18990             break;
18991     }
18992
18993     return (rval);
18994 }