]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/bxe/bxe.c
MFC r333004
[FreeBSD/stable/10.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.91"
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         QLOGIC_VENDORID,
171         CHIP_NUM_57840_4_10,
172         PCI_ANY_ID, PCI_ANY_ID,
173         "QLogic NetXtreme II BCM57840 4x10GbE"
174     },
175     {
176         BRCM_VENDORID,
177         CHIP_NUM_57840_MF,
178         PCI_ANY_ID, PCI_ANY_ID,
179         "QLogic NetXtreme II BCM57840 MF 10GbE"
180     },
181     {
182         0, 0, 0, 0, NULL
183     }
184 };
185
186 MALLOC_DECLARE(M_BXE_ILT);
187 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
188
189 /*
190  * FreeBSD device entry points.
191  */
192 static int bxe_probe(device_t);
193 static int bxe_attach(device_t);
194 static int bxe_detach(device_t);
195 static int bxe_shutdown(device_t);
196
197 /*
198  * FreeBSD KLD module/device interface event handler method.
199  */
200 static device_method_t bxe_methods[] = {
201     /* Device interface (device_if.h) */
202     DEVMETHOD(device_probe,     bxe_probe),
203     DEVMETHOD(device_attach,    bxe_attach),
204     DEVMETHOD(device_detach,    bxe_detach),
205     DEVMETHOD(device_shutdown,  bxe_shutdown),
206     /* Bus interface (bus_if.h) */
207     DEVMETHOD(bus_print_child,  bus_generic_print_child),
208     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
209     KOBJMETHOD_END
210 };
211
212 /*
213  * FreeBSD KLD Module data declaration
214  */
215 static driver_t bxe_driver = {
216     "bxe",                   /* module name */
217     bxe_methods,             /* event handler */
218     sizeof(struct bxe_softc) /* extra data */
219 };
220
221 /*
222  * FreeBSD dev class is needed to manage dev instances and
223  * to associate with a bus type
224  */
225 static devclass_t bxe_devclass;
226
227 MODULE_DEPEND(bxe, pci, 1, 1, 1);
228 MODULE_DEPEND(bxe, ether, 1, 1, 1);
229 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
230
231 /* resources needed for unloading a previously loaded device */
232
233 #define BXE_PREV_WAIT_NEEDED 1
234 struct mtx bxe_prev_mtx;
235 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
236 struct bxe_prev_list_node {
237     LIST_ENTRY(bxe_prev_list_node) node;
238     uint8_t bus;
239     uint8_t slot;
240     uint8_t path;
241     uint8_t aer; /* XXX automatic error recovery */
242     uint8_t undi;
243 };
244 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
245
246 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
247
248 /* Tunable device values... */
249
250 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
251
252 /* Debug */
253 unsigned long bxe_debug = 0;
254 TUNABLE_ULONG("hw.bxe.debug", &bxe_debug);
255 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, (CTLFLAG_RDTUN),
256              &bxe_debug, 0, "Debug logging mode");
257
258 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
259 static int bxe_interrupt_mode = INTR_MODE_MSIX;
260 TUNABLE_INT("hw.bxe.interrupt_mode", &bxe_interrupt_mode);
261 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
262            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
263
264 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
265 static int bxe_queue_count = 4;
266 TUNABLE_INT("hw.bxe.queue_count", &bxe_queue_count);
267 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
268            &bxe_queue_count, 0, "Multi-Queue queue count");
269
270 /* max number of buffers per queue (default RX_BD_USABLE) */
271 static int bxe_max_rx_bufs = 0;
272 TUNABLE_INT("hw.bxe.max_rx_bufs", &bxe_max_rx_bufs);
273 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
274            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
275
276 /* Host interrupt coalescing RX tick timer (usecs) */
277 static int bxe_hc_rx_ticks = 25;
278 TUNABLE_INT("hw.bxe.hc_rx_ticks", &bxe_hc_rx_ticks);
279 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
280            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
281
282 /* Host interrupt coalescing TX tick timer (usecs) */
283 static int bxe_hc_tx_ticks = 50;
284 TUNABLE_INT("hw.bxe.hc_tx_ticks", &bxe_hc_tx_ticks);
285 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
286            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
287
288 /* Maximum number of Rx packets to process at a time */
289 static int bxe_rx_budget = 0xffffffff;
290 TUNABLE_INT("hw.bxe.rx_budget", &bxe_rx_budget);
291 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
292            &bxe_rx_budget, 0, "Rx processing budget");
293
294 /* Maximum LRO aggregation size */
295 static int bxe_max_aggregation_size = 0;
296 TUNABLE_INT("hw.bxe.max_aggregation_size", &bxe_max_aggregation_size);
297 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
298            &bxe_max_aggregation_size, 0, "max aggregation size");
299
300 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
301 static int bxe_mrrs = -1;
302 TUNABLE_INT("hw.bxe.mrrs", &bxe_mrrs);
303 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
304            &bxe_mrrs, 0, "PCIe maximum read request size");
305
306 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
307 static int bxe_autogreeen = 0;
308 TUNABLE_INT("hw.bxe.autogreeen", &bxe_autogreeen);
309 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
310            &bxe_autogreeen, 0, "AutoGrEEEn support");
311
312 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
313 static int bxe_udp_rss = 0;
314 TUNABLE_INT("hw.bxe.udp_rss", &bxe_udp_rss);
315 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
316            &bxe_udp_rss, 0, "UDP RSS support");
317
318
319 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
320
321 #define STATS_OFFSET32(stat_name)                   \
322     (offsetof(struct bxe_eth_stats, stat_name) / 4)
323
324 #define Q_STATS_OFFSET32(stat_name)                   \
325     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
326
327 static const struct {
328     uint32_t offset;
329     uint32_t size;
330     uint32_t flags;
331 #define STATS_FLAGS_PORT  1
332 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
333 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
334     char string[STAT_NAME_LEN];
335 } bxe_eth_stats_arr[] = {
336     { STATS_OFFSET32(total_bytes_received_hi),
337                 8, STATS_FLAGS_BOTH, "rx_bytes" },
338     { STATS_OFFSET32(error_bytes_received_hi),
339                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
340     { STATS_OFFSET32(total_unicast_packets_received_hi),
341                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
342     { STATS_OFFSET32(total_multicast_packets_received_hi),
343                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
344     { STATS_OFFSET32(total_broadcast_packets_received_hi),
345                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
346     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
347                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
348     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
349                 8, STATS_FLAGS_PORT, "rx_align_errors" },
350     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
351                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
352     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
353                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
354     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
355                 8, STATS_FLAGS_PORT, "rx_fragments" },
356     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
357                 8, STATS_FLAGS_PORT, "rx_jabbers" },
358     { STATS_OFFSET32(no_buff_discard_hi),
359                 8, STATS_FLAGS_BOTH, "rx_discards" },
360     { STATS_OFFSET32(mac_filter_discard),
361                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
362     { STATS_OFFSET32(mf_tag_discard),
363                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
364     { STATS_OFFSET32(pfc_frames_received_hi),
365                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
366     { STATS_OFFSET32(pfc_frames_sent_hi),
367                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
368     { STATS_OFFSET32(brb_drop_hi),
369                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
370     { STATS_OFFSET32(brb_truncate_hi),
371                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
372     { STATS_OFFSET32(pause_frames_received_hi),
373                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
374     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
375                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
376     { STATS_OFFSET32(nig_timer_max),
377                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
378     { STATS_OFFSET32(total_bytes_transmitted_hi),
379                 8, STATS_FLAGS_BOTH, "tx_bytes" },
380     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
381                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
382     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
383                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
384     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
385                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
386     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
387                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
388     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
389                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
390     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
391                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
392     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
393                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
394     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
395                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
396     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
397                 8, STATS_FLAGS_PORT, "tx_deferred" },
398     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
399                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
400     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
401                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
402     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
403                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
404     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
405                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
406     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
407                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
408     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
409                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
410     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
411                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
412     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
413                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
414     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
415                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
416     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
417                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
418     { STATS_OFFSET32(pause_frames_sent_hi),
419                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
420     { STATS_OFFSET32(total_tpa_aggregations_hi),
421                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
422     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
423                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
424     { STATS_OFFSET32(total_tpa_bytes_hi),
425                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
426     { STATS_OFFSET32(eee_tx_lpi),
427                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
428     { STATS_OFFSET32(rx_calls),
429                 4, STATS_FLAGS_FUNC, "rx_calls"},
430     { STATS_OFFSET32(rx_pkts),
431                 4, STATS_FLAGS_FUNC, "rx_pkts"},
432     { STATS_OFFSET32(rx_tpa_pkts),
433                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
434     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
435                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
436     { STATS_OFFSET32(rx_bxe_service_rxsgl),
437                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
438     { STATS_OFFSET32(rx_jumbo_sge_pkts),
439                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
440     { STATS_OFFSET32(rx_soft_errors),
441                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
442     { STATS_OFFSET32(rx_hw_csum_errors),
443                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
444     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
445                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
446     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
447                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
448     { STATS_OFFSET32(rx_budget_reached),
449                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
450     { STATS_OFFSET32(tx_pkts),
451                 4, STATS_FLAGS_FUNC, "tx_pkts"},
452     { STATS_OFFSET32(tx_soft_errors),
453                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
454     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
455                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
456     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
457                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
458     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
459                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
460     { STATS_OFFSET32(tx_ofld_frames_lso),
461                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
462     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
463                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
464     { STATS_OFFSET32(tx_encap_failures),
465                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
466     { STATS_OFFSET32(tx_hw_queue_full),
467                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
468     { STATS_OFFSET32(tx_hw_max_queue_depth),
469                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
470     { STATS_OFFSET32(tx_dma_mapping_failure),
471                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
472     { STATS_OFFSET32(tx_max_drbr_queue_depth),
473                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
474     { STATS_OFFSET32(tx_window_violation_std),
475                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
476     { STATS_OFFSET32(tx_window_violation_tso),
477                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
478     { STATS_OFFSET32(tx_chain_lost_mbuf),
479                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
480     { STATS_OFFSET32(tx_frames_deferred),
481                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
482     { STATS_OFFSET32(tx_queue_xoff),
483                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
484     { STATS_OFFSET32(mbuf_defrag_attempts),
485                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
486     { STATS_OFFSET32(mbuf_defrag_failures),
487                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
488     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
489                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
490     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
491                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
492     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
493                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
494     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
495                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
496     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
497                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
498     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
499                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
500     { STATS_OFFSET32(mbuf_alloc_tx),
501                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
502     { STATS_OFFSET32(mbuf_alloc_rx),
503                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
504     { STATS_OFFSET32(mbuf_alloc_sge),
505                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
506     { STATS_OFFSET32(mbuf_alloc_tpa),
507                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"},
508     { STATS_OFFSET32(tx_queue_full_return),
509                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
510     { STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
511                 4, STATS_FLAGS_FUNC, "bxe_tx_mq_sc_state_failures"},
512     { STATS_OFFSET32(tx_request_link_down_failures),
513                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
514     { STATS_OFFSET32(bd_avail_too_less_failures),
515                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
516     { STATS_OFFSET32(tx_mq_not_empty),
517                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"},
518     { STATS_OFFSET32(nsegs_path1_errors),
519                 4, STATS_FLAGS_FUNC, "nsegs_path1_errors"},
520     { STATS_OFFSET32(nsegs_path2_errors),
521                 4, STATS_FLAGS_FUNC, "nsegs_path2_errors"}
522
523
524 };
525
526 static const struct {
527     uint32_t offset;
528     uint32_t size;
529     char string[STAT_NAME_LEN];
530 } bxe_eth_q_stats_arr[] = {
531     { Q_STATS_OFFSET32(total_bytes_received_hi),
532                 8, "rx_bytes" },
533     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
534                 8, "rx_ucast_packets" },
535     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
536                 8, "rx_mcast_packets" },
537     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
538                 8, "rx_bcast_packets" },
539     { Q_STATS_OFFSET32(no_buff_discard_hi),
540                 8, "rx_discards" },
541     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
542                 8, "tx_bytes" },
543     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
544                 8, "tx_ucast_packets" },
545     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
546                 8, "tx_mcast_packets" },
547     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
548                 8, "tx_bcast_packets" },
549     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
550                 8, "tpa_aggregations" },
551     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
552                 8, "tpa_aggregated_frames"},
553     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
554                 8, "tpa_bytes"},
555     { Q_STATS_OFFSET32(rx_calls),
556                 4, "rx_calls"},
557     { Q_STATS_OFFSET32(rx_pkts),
558                 4, "rx_pkts"},
559     { Q_STATS_OFFSET32(rx_tpa_pkts),
560                 4, "rx_tpa_pkts"},
561     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
562                 4, "rx_erroneous_jumbo_sge_pkts"},
563     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
564                 4, "rx_bxe_service_rxsgl"},
565     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
566                 4, "rx_jumbo_sge_pkts"},
567     { Q_STATS_OFFSET32(rx_soft_errors),
568                 4, "rx_soft_errors"},
569     { Q_STATS_OFFSET32(rx_hw_csum_errors),
570                 4, "rx_hw_csum_errors"},
571     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
572                 4, "rx_ofld_frames_csum_ip"},
573     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
574                 4, "rx_ofld_frames_csum_tcp_udp"},
575     { Q_STATS_OFFSET32(rx_budget_reached),
576                 4, "rx_budget_reached"},
577     { Q_STATS_OFFSET32(tx_pkts),
578                 4, "tx_pkts"},
579     { Q_STATS_OFFSET32(tx_soft_errors),
580                 4, "tx_soft_errors"},
581     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
582                 4, "tx_ofld_frames_csum_ip"},
583     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
584                 4, "tx_ofld_frames_csum_tcp"},
585     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
586                 4, "tx_ofld_frames_csum_udp"},
587     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
588                 4, "tx_ofld_frames_lso"},
589     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
590                 4, "tx_ofld_frames_lso_hdr_splits"},
591     { Q_STATS_OFFSET32(tx_encap_failures),
592                 4, "tx_encap_failures"},
593     { Q_STATS_OFFSET32(tx_hw_queue_full),
594                 4, "tx_hw_queue_full"},
595     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
596                 4, "tx_hw_max_queue_depth"},
597     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
598                 4, "tx_dma_mapping_failure"},
599     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
600                 4, "tx_max_drbr_queue_depth"},
601     { Q_STATS_OFFSET32(tx_window_violation_std),
602                 4, "tx_window_violation_std"},
603     { Q_STATS_OFFSET32(tx_window_violation_tso),
604                 4, "tx_window_violation_tso"},
605     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
606                 4, "tx_chain_lost_mbuf"},
607     { Q_STATS_OFFSET32(tx_frames_deferred),
608                 4, "tx_frames_deferred"},
609     { Q_STATS_OFFSET32(tx_queue_xoff),
610                 4, "tx_queue_xoff"},
611     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
612                 4, "mbuf_defrag_attempts"},
613     { Q_STATS_OFFSET32(mbuf_defrag_failures),
614                 4, "mbuf_defrag_failures"},
615     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
616                 4, "mbuf_rx_bd_alloc_failed"},
617     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
618                 4, "mbuf_rx_bd_mapping_failed"},
619     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
620                 4, "mbuf_rx_tpa_alloc_failed"},
621     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
622                 4, "mbuf_rx_tpa_mapping_failed"},
623     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
624                 4, "mbuf_rx_sge_alloc_failed"},
625     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
626                 4, "mbuf_rx_sge_mapping_failed"},
627     { Q_STATS_OFFSET32(mbuf_alloc_tx),
628                 4, "mbuf_alloc_tx"},
629     { Q_STATS_OFFSET32(mbuf_alloc_rx),
630                 4, "mbuf_alloc_rx"},
631     { Q_STATS_OFFSET32(mbuf_alloc_sge),
632                 4, "mbuf_alloc_sge"},
633     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
634                 4, "mbuf_alloc_tpa"},
635     { Q_STATS_OFFSET32(tx_queue_full_return),
636                 4, "tx_queue_full_return"},
637     { Q_STATS_OFFSET32(bxe_tx_mq_sc_state_failures),
638                 4, "bxe_tx_mq_sc_state_failures"},
639     { Q_STATS_OFFSET32(tx_request_link_down_failures),
640                 4, "tx_request_link_down_failures"},
641     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
642                 4, "bd_avail_too_less_failures"},
643     { Q_STATS_OFFSET32(tx_mq_not_empty),
644                 4, "tx_mq_not_empty"},
645     { Q_STATS_OFFSET32(nsegs_path1_errors),
646                 4, "nsegs_path1_errors"},
647     { Q_STATS_OFFSET32(nsegs_path2_errors),
648                 4, "nsegs_path2_errors"}
649
650
651 };
652
653 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
654 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
655
656
657 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
658                                  uint8_t          read_cfg,
659                                  uint8_t          cmng_type);
660 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
661 static void    storm_memset_cmng(struct bxe_softc *sc,
662                                  struct cmng_init *cmng,
663                                  uint8_t          port);
664 static void    bxe_set_reset_global(struct bxe_softc *sc);
665 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
666 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
667                                  int              engine);
668 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
669 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
670                                    uint8_t          *global,
671                                    uint8_t          print);
672 static void    bxe_int_disable(struct bxe_softc *sc);
673 static int     bxe_release_leader_lock(struct bxe_softc *sc);
674 static void    bxe_pf_disable(struct bxe_softc *sc);
675 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
676 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
677                                       struct bxe_fastpath *fp,
678                                       uint16_t            rx_bd_prod,
679                                       uint16_t            rx_cq_prod,
680                                       uint16_t            rx_sge_prod);
681 static void    bxe_link_report_locked(struct bxe_softc *sc);
682 static void    bxe_link_report(struct bxe_softc *sc);
683 static void    bxe_link_status_update(struct bxe_softc *sc);
684 static void    bxe_periodic_callout_func(void *xsc);
685 static void    bxe_periodic_start(struct bxe_softc *sc);
686 static void    bxe_periodic_stop(struct bxe_softc *sc);
687 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
688                                     uint16_t prev_index,
689                                     uint16_t index);
690 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
691                                      int                 queue);
692 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
693                                      uint16_t            index);
694 static uint8_t bxe_txeof(struct bxe_softc *sc,
695                          struct bxe_fastpath *fp);
696 static void    bxe_task_fp(struct bxe_fastpath *fp);
697 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
698                                      struct mbuf      *m,
699                                      uint8_t          contents);
700 static int     bxe_alloc_mem(struct bxe_softc *sc);
701 static void    bxe_free_mem(struct bxe_softc *sc);
702 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
703 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
704 static int     bxe_interrupt_attach(struct bxe_softc *sc);
705 static void    bxe_interrupt_detach(struct bxe_softc *sc);
706 static void    bxe_set_rx_mode(struct bxe_softc *sc);
707 static int     bxe_init_locked(struct bxe_softc *sc);
708 static int     bxe_stop_locked(struct bxe_softc *sc);
709 static __noinline int bxe_nic_load(struct bxe_softc *sc,
710                                    int              load_mode);
711 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
712                                      uint32_t         unload_mode,
713                                      uint8_t          keep_link);
714
715 static void bxe_handle_sp_tq(void *context, int pending);
716 static void bxe_handle_fp_tq(void *context, int pending);
717
718 static int bxe_add_cdev(struct bxe_softc *sc);
719 static void bxe_del_cdev(struct bxe_softc *sc);
720 int bxe_grc_dump(struct bxe_softc *sc);
721 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
722 static void bxe_free_buf_rings(struct bxe_softc *sc);
723
724 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
725 uint32_t
726 calc_crc32(uint8_t  *crc32_packet,
727            uint32_t crc32_length,
728            uint32_t crc32_seed,
729            uint8_t  complement)
730 {
731    uint32_t byte         = 0;
732    uint32_t bit          = 0;
733    uint8_t  msb          = 0;
734    uint32_t temp         = 0;
735    uint32_t shft         = 0;
736    uint8_t  current_byte = 0;
737    uint32_t crc32_result = crc32_seed;
738    const uint32_t CRC32_POLY = 0x1edc6f41;
739
740    if ((crc32_packet == NULL) ||
741        (crc32_length == 0) ||
742        ((crc32_length % 8) != 0))
743     {
744         return (crc32_result);
745     }
746
747     for (byte = 0; byte < crc32_length; byte = byte + 1)
748     {
749         current_byte = crc32_packet[byte];
750         for (bit = 0; bit < 8; bit = bit + 1)
751         {
752             /* msb = crc32_result[31]; */
753             msb = (uint8_t)(crc32_result >> 31);
754
755             crc32_result = crc32_result << 1;
756
757             /* it (msb != current_byte[bit]) */
758             if (msb != (0x1 & (current_byte >> bit)))
759             {
760                 crc32_result = crc32_result ^ CRC32_POLY;
761                 /* crc32_result[0] = 1 */
762                 crc32_result |= 1;
763             }
764         }
765     }
766
767     /* Last step is to:
768      * 1. "mirror" every bit
769      * 2. swap the 4 bytes
770      * 3. complement each bit
771      */
772
773     /* Mirror */
774     temp = crc32_result;
775     shft = sizeof(crc32_result) * 8 - 1;
776
777     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
778     {
779         temp <<= 1;
780         temp |= crc32_result & 1;
781         shft-- ;
782     }
783
784     /* temp[31-bit] = crc32_result[bit] */
785     temp <<= shft;
786
787     /* Swap */
788     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
789     {
790         uint32_t t0, t1, t2, t3;
791         t0 = (0x000000ff & (temp >> 24));
792         t1 = (0x0000ff00 & (temp >> 8));
793         t2 = (0x00ff0000 & (temp << 8));
794         t3 = (0xff000000 & (temp << 24));
795         crc32_result = t0 | t1 | t2 | t3;
796     }
797
798     /* Complement */
799     if (complement)
800     {
801         crc32_result = ~crc32_result;
802     }
803
804     return (crc32_result);
805 }
806
807 int
808 bxe_test_bit(int                    nr,
809              volatile unsigned long *addr)
810 {
811     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
812 }
813
814 void
815 bxe_set_bit(unsigned int           nr,
816             volatile unsigned long *addr)
817 {
818     atomic_set_acq_long(addr, (1 << nr));
819 }
820
821 void
822 bxe_clear_bit(int                    nr,
823               volatile unsigned long *addr)
824 {
825     atomic_clear_acq_long(addr, (1 << nr));
826 }
827
828 int
829 bxe_test_and_set_bit(int                    nr,
830                        volatile unsigned long *addr)
831 {
832     unsigned long x;
833     nr = (1 << nr);
834     do {
835         x = *addr;
836     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
837     // if (x & nr) bit_was_set; else bit_was_not_set;
838     return (x & nr);
839 }
840
841 int
842 bxe_test_and_clear_bit(int                    nr,
843                        volatile unsigned long *addr)
844 {
845     unsigned long x;
846     nr = (1 << nr);
847     do {
848         x = *addr;
849     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
850     // if (x & nr) bit_was_set; else bit_was_not_set;
851     return (x & nr);
852 }
853
854 int
855 bxe_cmpxchg(volatile int *addr,
856             int          old,
857             int          new)
858 {
859     int x;
860     do {
861         x = *addr;
862     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
863     return (x);
864 }
865
866 /*
867  * Get DMA memory from the OS.
868  *
869  * Validates that the OS has provided DMA buffers in response to a
870  * bus_dmamap_load call and saves the physical address of those buffers.
871  * When the callback is used the OS will return 0 for the mapping function
872  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
873  * failures back to the caller.
874  *
875  * Returns:
876  *   Nothing.
877  */
878 static void
879 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
880 {
881     struct bxe_dma *dma = arg;
882
883     if (error) {
884         dma->paddr = 0;
885         dma->nseg  = 0;
886         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
887     } else {
888         dma->paddr = segs->ds_addr;
889         dma->nseg  = nseg;
890     }
891 }
892
893 /*
894  * Allocate a block of memory and map it for DMA. No partial completions
895  * allowed and release any resources acquired if we can't acquire all
896  * resources.
897  *
898  * Returns:
899  *   0 = Success, !0 = Failure
900  */
901 int
902 bxe_dma_alloc(struct bxe_softc *sc,
903               bus_size_t       size,
904               struct bxe_dma   *dma,
905               const char       *msg)
906 {
907     int rc;
908
909     if (dma->size > 0) {
910         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
911               (unsigned long)dma->size);
912         return (1);
913     }
914
915     memset(dma, 0, sizeof(*dma)); /* sanity */
916     dma->sc   = sc;
917     dma->size = size;
918     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
919
920     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
921                             BCM_PAGE_SIZE,      /* alignment */
922                             0,                  /* boundary limit */
923                             BUS_SPACE_MAXADDR,  /* restricted low */
924                             BUS_SPACE_MAXADDR,  /* restricted hi */
925                             NULL,               /* addr filter() */
926                             NULL,               /* addr filter() arg */
927                             size,               /* max map size */
928                             1,                  /* num discontinuous */
929                             size,               /* max seg size */
930                             BUS_DMA_ALLOCNOW,   /* flags */
931                             NULL,               /* lock() */
932                             NULL,               /* lock() arg */
933                             &dma->tag);         /* returned dma tag */
934     if (rc != 0) {
935         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
936         memset(dma, 0, sizeof(*dma));
937         return (1);
938     }
939
940     rc = bus_dmamem_alloc(dma->tag,
941                           (void **)&dma->vaddr,
942                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
943                           &dma->map);
944     if (rc != 0) {
945         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
946         bus_dma_tag_destroy(dma->tag);
947         memset(dma, 0, sizeof(*dma));
948         return (1);
949     }
950
951     rc = bus_dmamap_load(dma->tag,
952                          dma->map,
953                          dma->vaddr,
954                          size,
955                          bxe_dma_map_addr, /* BLOGD in here */
956                          dma,
957                          BUS_DMA_NOWAIT);
958     if (rc != 0) {
959         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
960         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
961         bus_dma_tag_destroy(dma->tag);
962         memset(dma, 0, sizeof(*dma));
963         return (1);
964     }
965
966     return (0);
967 }
968
969 void
970 bxe_dma_free(struct bxe_softc *sc,
971              struct bxe_dma   *dma)
972 {
973     if (dma->size > 0) {
974         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
975
976         bus_dmamap_sync(dma->tag, dma->map,
977                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
978         bus_dmamap_unload(dma->tag, dma->map);
979         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
980         bus_dma_tag_destroy(dma->tag);
981     }
982
983     memset(dma, 0, sizeof(*dma));
984 }
985
986 /*
987  * These indirect read and write routines are only during init.
988  * The locking is handled by the MCP.
989  */
990
991 void
992 bxe_reg_wr_ind(struct bxe_softc *sc,
993                uint32_t         addr,
994                uint32_t         val)
995 {
996     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
997     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
998     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
999 }
1000
1001 uint32_t
1002 bxe_reg_rd_ind(struct bxe_softc *sc,
1003                uint32_t         addr)
1004 {
1005     uint32_t val;
1006
1007     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
1008     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
1009     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
1010
1011     return (val);
1012 }
1013
1014 static int
1015 bxe_acquire_hw_lock(struct bxe_softc *sc,
1016                     uint32_t         resource)
1017 {
1018     uint32_t lock_status;
1019     uint32_t resource_bit = (1 << resource);
1020     int func = SC_FUNC(sc);
1021     uint32_t hw_lock_control_reg;
1022     int cnt;
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 not already taken */
1039     lock_status = REG_RD(sc, hw_lock_control_reg);
1040     if (lock_status & resource_bit) {
1041         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1042               resource, lock_status, resource_bit);
1043         return (-1);
1044     }
1045
1046     /* try every 5ms for 5 seconds */
1047     for (cnt = 0; cnt < 1000; cnt++) {
1048         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1049         lock_status = REG_RD(sc, hw_lock_control_reg);
1050         if (lock_status & resource_bit) {
1051             return (0);
1052         }
1053         DELAY(5000);
1054     }
1055
1056     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1057         resource, resource_bit);
1058     return (-1);
1059 }
1060
1061 static int
1062 bxe_release_hw_lock(struct bxe_softc *sc,
1063                     uint32_t         resource)
1064 {
1065     uint32_t lock_status;
1066     uint32_t resource_bit = (1 << resource);
1067     int func = SC_FUNC(sc);
1068     uint32_t hw_lock_control_reg;
1069
1070     /* validate the resource is within range */
1071     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1072         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1073             " resource_bit 0x%x\n", resource, resource_bit);
1074         return (-1);
1075     }
1076
1077     if (func <= 5) {
1078         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1079     } else {
1080         hw_lock_control_reg =
1081                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1082     }
1083
1084     /* validate the resource is currently taken */
1085     lock_status = REG_RD(sc, hw_lock_control_reg);
1086     if (!(lock_status & resource_bit)) {
1087         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1088               resource, lock_status, resource_bit);
1089         return (-1);
1090     }
1091
1092     REG_WR(sc, hw_lock_control_reg, resource_bit);
1093     return (0);
1094 }
1095 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1096 {
1097         BXE_PHY_LOCK(sc);
1098         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1099 }
1100
1101 static void bxe_release_phy_lock(struct bxe_softc *sc)
1102 {
1103         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1104         BXE_PHY_UNLOCK(sc);
1105 }
1106 /*
1107  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1108  * had we done things the other way around, if two pfs from the same port
1109  * would attempt to access nvram at the same time, we could run into a
1110  * scenario such as:
1111  * pf A takes the port lock.
1112  * pf B succeeds in taking the same lock since they are from the same port.
1113  * pf A takes the per pf misc lock. Performs eeprom access.
1114  * pf A finishes. Unlocks the per pf misc lock.
1115  * Pf B takes the lock and proceeds to perform it's own access.
1116  * pf A unlocks the per port lock, while pf B is still working (!).
1117  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1118  * access corrupted by pf B).*
1119  */
1120 static int
1121 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1122 {
1123     int port = SC_PORT(sc);
1124     int count, i;
1125     uint32_t val = 0;
1126
1127     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1128     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1129
1130     /* adjust timeout for emulation/FPGA */
1131     count = NVRAM_TIMEOUT_COUNT;
1132     if (CHIP_REV_IS_SLOW(sc)) {
1133         count *= 100;
1134     }
1135
1136     /* request access to nvram interface */
1137     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1138            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1139
1140     for (i = 0; i < count*10; i++) {
1141         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1142         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1143             break;
1144         }
1145
1146         DELAY(5);
1147     }
1148
1149     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1150         BLOGE(sc, "Cannot get access to nvram interface "
1151             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1152             port, val);
1153         return (-1);
1154     }
1155
1156     return (0);
1157 }
1158
1159 static int
1160 bxe_release_nvram_lock(struct bxe_softc *sc)
1161 {
1162     int port = SC_PORT(sc);
1163     int count, i;
1164     uint32_t val = 0;
1165
1166     /* adjust timeout for emulation/FPGA */
1167     count = NVRAM_TIMEOUT_COUNT;
1168     if (CHIP_REV_IS_SLOW(sc)) {
1169         count *= 100;
1170     }
1171
1172     /* relinquish nvram interface */
1173     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1174            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1175
1176     for (i = 0; i < count*10; i++) {
1177         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1178         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1179             break;
1180         }
1181
1182         DELAY(5);
1183     }
1184
1185     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1186         BLOGE(sc, "Cannot free access to nvram interface "
1187             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1188             port, val);
1189         return (-1);
1190     }
1191
1192     /* release HW lock: protect against other PFs in PF Direct Assignment */
1193     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1194
1195     return (0);
1196 }
1197
1198 static void
1199 bxe_enable_nvram_access(struct bxe_softc *sc)
1200 {
1201     uint32_t val;
1202
1203     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1204
1205     /* enable both bits, even on read */
1206     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1207            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1208 }
1209
1210 static void
1211 bxe_disable_nvram_access(struct bxe_softc *sc)
1212 {
1213     uint32_t val;
1214
1215     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1216
1217     /* disable both bits, even after read */
1218     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1219            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1220                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1221 }
1222
1223 static int
1224 bxe_nvram_read_dword(struct bxe_softc *sc,
1225                      uint32_t         offset,
1226                      uint32_t         *ret_val,
1227                      uint32_t         cmd_flags)
1228 {
1229     int count, i, rc;
1230     uint32_t val;
1231
1232     /* build the command word */
1233     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1234
1235     /* need to clear DONE bit separately */
1236     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1237
1238     /* address of the NVRAM to read from */
1239     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1240            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1241
1242     /* issue a read command */
1243     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1244
1245     /* adjust timeout for emulation/FPGA */
1246     count = NVRAM_TIMEOUT_COUNT;
1247     if (CHIP_REV_IS_SLOW(sc)) {
1248         count *= 100;
1249     }
1250
1251     /* wait for completion */
1252     *ret_val = 0;
1253     rc = -1;
1254     for (i = 0; i < count; i++) {
1255         DELAY(5);
1256         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1257
1258         if (val & MCPR_NVM_COMMAND_DONE) {
1259             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1260             /* we read nvram data in cpu order
1261              * but ethtool sees it as an array of bytes
1262              * converting to big-endian will do the work
1263              */
1264             *ret_val = htobe32(val);
1265             rc = 0;
1266             break;
1267         }
1268     }
1269
1270     if (rc == -1) {
1271         BLOGE(sc, "nvram read timeout expired "
1272             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1273             offset, cmd_flags, val);
1274     }
1275
1276     return (rc);
1277 }
1278
1279 static int
1280 bxe_nvram_read(struct bxe_softc *sc,
1281                uint32_t         offset,
1282                uint8_t          *ret_buf,
1283                int              buf_size)
1284 {
1285     uint32_t cmd_flags;
1286     uint32_t val;
1287     int rc;
1288
1289     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1290         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1291               offset, buf_size);
1292         return (-1);
1293     }
1294
1295     if ((offset + buf_size) > sc->devinfo.flash_size) {
1296         BLOGE(sc, "Invalid parameter, "
1297                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1298               offset, buf_size, sc->devinfo.flash_size);
1299         return (-1);
1300     }
1301
1302     /* request access to nvram interface */
1303     rc = bxe_acquire_nvram_lock(sc);
1304     if (rc) {
1305         return (rc);
1306     }
1307
1308     /* enable access to nvram interface */
1309     bxe_enable_nvram_access(sc);
1310
1311     /* read the first word(s) */
1312     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1313     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1314         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1315         memcpy(ret_buf, &val, 4);
1316
1317         /* advance to the next dword */
1318         offset += sizeof(uint32_t);
1319         ret_buf += sizeof(uint32_t);
1320         buf_size -= sizeof(uint32_t);
1321         cmd_flags = 0;
1322     }
1323
1324     if (rc == 0) {
1325         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1326         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1327         memcpy(ret_buf, &val, 4);
1328     }
1329
1330     /* disable access to nvram interface */
1331     bxe_disable_nvram_access(sc);
1332     bxe_release_nvram_lock(sc);
1333
1334     return (rc);
1335 }
1336
1337 static int
1338 bxe_nvram_write_dword(struct bxe_softc *sc,
1339                       uint32_t         offset,
1340                       uint32_t         val,
1341                       uint32_t         cmd_flags)
1342 {
1343     int count, i, rc;
1344
1345     /* build the command word */
1346     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1347
1348     /* need to clear DONE bit separately */
1349     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1350
1351     /* write the data */
1352     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1353
1354     /* address of the NVRAM to write to */
1355     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1356            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1357
1358     /* issue the write command */
1359     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1360
1361     /* adjust timeout for emulation/FPGA */
1362     count = NVRAM_TIMEOUT_COUNT;
1363     if (CHIP_REV_IS_SLOW(sc)) {
1364         count *= 100;
1365     }
1366
1367     /* wait for completion */
1368     rc = -1;
1369     for (i = 0; i < count; i++) {
1370         DELAY(5);
1371         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1372         if (val & MCPR_NVM_COMMAND_DONE) {
1373             rc = 0;
1374             break;
1375         }
1376     }
1377
1378     if (rc == -1) {
1379         BLOGE(sc, "nvram write timeout expired "
1380             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1381             offset, cmd_flags, val);
1382     }
1383
1384     return (rc);
1385 }
1386
1387 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1388
1389 static int
1390 bxe_nvram_write1(struct bxe_softc *sc,
1391                  uint32_t         offset,
1392                  uint8_t          *data_buf,
1393                  int              buf_size)
1394 {
1395     uint32_t cmd_flags;
1396     uint32_t align_offset;
1397     uint32_t val;
1398     int rc;
1399
1400     if ((offset + buf_size) > sc->devinfo.flash_size) {
1401         BLOGE(sc, "Invalid parameter, "
1402                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1403               offset, buf_size, sc->devinfo.flash_size);
1404         return (-1);
1405     }
1406
1407     /* request access to nvram interface */
1408     rc = bxe_acquire_nvram_lock(sc);
1409     if (rc) {
1410         return (rc);
1411     }
1412
1413     /* enable access to nvram interface */
1414     bxe_enable_nvram_access(sc);
1415
1416     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1417     align_offset = (offset & ~0x03);
1418     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1419
1420     if (rc == 0) {
1421         val &= ~(0xff << BYTE_OFFSET(offset));
1422         val |= (*data_buf << BYTE_OFFSET(offset));
1423
1424         /* nvram data is returned as an array of bytes
1425          * convert it back to cpu order
1426          */
1427         val = be32toh(val);
1428
1429         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1430     }
1431
1432     /* disable access to nvram interface */
1433     bxe_disable_nvram_access(sc);
1434     bxe_release_nvram_lock(sc);
1435
1436     return (rc);
1437 }
1438
1439 static int
1440 bxe_nvram_write(struct bxe_softc *sc,
1441                 uint32_t         offset,
1442                 uint8_t          *data_buf,
1443                 int              buf_size)
1444 {
1445     uint32_t cmd_flags;
1446     uint32_t val;
1447     uint32_t written_so_far;
1448     int rc;
1449
1450     if (buf_size == 1) {
1451         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1452     }
1453
1454     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1455         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1456               offset, buf_size);
1457         return (-1);
1458     }
1459
1460     if (buf_size == 0) {
1461         return (0); /* nothing to do */
1462     }
1463
1464     if ((offset + buf_size) > sc->devinfo.flash_size) {
1465         BLOGE(sc, "Invalid parameter, "
1466                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1467               offset, buf_size, sc->devinfo.flash_size);
1468         return (-1);
1469     }
1470
1471     /* request access to nvram interface */
1472     rc = bxe_acquire_nvram_lock(sc);
1473     if (rc) {
1474         return (rc);
1475     }
1476
1477     /* enable access to nvram interface */
1478     bxe_enable_nvram_access(sc);
1479
1480     written_so_far = 0;
1481     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1482     while ((written_so_far < buf_size) && (rc == 0)) {
1483         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1484             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1485         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1486             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1487         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1488             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1489         }
1490
1491         memcpy(&val, data_buf, 4);
1492
1493         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1494
1495         /* advance to the next dword */
1496         offset += sizeof(uint32_t);
1497         data_buf += sizeof(uint32_t);
1498         written_so_far += sizeof(uint32_t);
1499         cmd_flags = 0;
1500     }
1501
1502     /* disable access to nvram interface */
1503     bxe_disable_nvram_access(sc);
1504     bxe_release_nvram_lock(sc);
1505
1506     return (rc);
1507 }
1508
1509 /* copy command into DMAE command memory and set DMAE command Go */
1510 void
1511 bxe_post_dmae(struct bxe_softc    *sc,
1512               struct dmae_cmd *dmae,
1513               int                 idx)
1514 {
1515     uint32_t cmd_offset;
1516     int i;
1517
1518     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1519     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1520         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1521     }
1522
1523     REG_WR(sc, dmae_reg_go_c[idx], 1);
1524 }
1525
1526 uint32_t
1527 bxe_dmae_opcode_add_comp(uint32_t opcode,
1528                          uint8_t  comp_type)
1529 {
1530     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1531                       DMAE_CMD_C_TYPE_ENABLE));
1532 }
1533
1534 uint32_t
1535 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1536 {
1537     return (opcode & ~DMAE_CMD_SRC_RESET);
1538 }
1539
1540 uint32_t
1541 bxe_dmae_opcode(struct bxe_softc *sc,
1542                 uint8_t          src_type,
1543                 uint8_t          dst_type,
1544                 uint8_t          with_comp,
1545                 uint8_t          comp_type)
1546 {
1547     uint32_t opcode = 0;
1548
1549     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1550                (dst_type << DMAE_CMD_DST_SHIFT));
1551
1552     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1553
1554     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1555
1556     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1557                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1558
1559     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1560
1561 #ifdef __BIG_ENDIAN
1562     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1563 #else
1564     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1565 #endif
1566
1567     if (with_comp) {
1568         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1569     }
1570
1571     return (opcode);
1572 }
1573
1574 static void
1575 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1576                         struct dmae_cmd *dmae,
1577                         uint8_t             src_type,
1578                         uint8_t             dst_type)
1579 {
1580     memset(dmae, 0, sizeof(struct dmae_cmd));
1581
1582     /* set the opcode */
1583     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1584                                    TRUE, DMAE_COMP_PCI);
1585
1586     /* fill in the completion parameters */
1587     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1588     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1589     dmae->comp_val     = DMAE_COMP_VAL;
1590 }
1591
1592 /* issue a DMAE command over the init channel and wait for completion */
1593 static int
1594 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1595                          struct dmae_cmd *dmae)
1596 {
1597     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1598     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1599
1600     BXE_DMAE_LOCK(sc);
1601
1602     /* reset completion */
1603     *wb_comp = 0;
1604
1605     /* post the command on the channel used for initializations */
1606     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1607
1608     /* wait for completion */
1609     DELAY(5);
1610
1611     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1612         if (!timeout ||
1613             (sc->recovery_state != BXE_RECOVERY_DONE &&
1614              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1615             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1616                 *wb_comp, sc->recovery_state);
1617             BXE_DMAE_UNLOCK(sc);
1618             return (DMAE_TIMEOUT);
1619         }
1620
1621         timeout--;
1622         DELAY(50);
1623     }
1624
1625     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1626         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1627                 *wb_comp, sc->recovery_state);
1628         BXE_DMAE_UNLOCK(sc);
1629         return (DMAE_PCI_ERROR);
1630     }
1631
1632     BXE_DMAE_UNLOCK(sc);
1633     return (0);
1634 }
1635
1636 void
1637 bxe_read_dmae(struct bxe_softc *sc,
1638               uint32_t         src_addr,
1639               uint32_t         len32)
1640 {
1641     struct dmae_cmd dmae;
1642     uint32_t *data;
1643     int i, rc;
1644
1645     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1646
1647     if (!sc->dmae_ready) {
1648         data = BXE_SP(sc, wb_data[0]);
1649
1650         for (i = 0; i < len32; i++) {
1651             data[i] = (CHIP_IS_E1(sc)) ?
1652                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1653                           REG_RD(sc, (src_addr + (i * 4)));
1654         }
1655
1656         return;
1657     }
1658
1659     /* set opcode and fixed command fields */
1660     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1661
1662     /* fill in addresses and len */
1663     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1664     dmae.src_addr_hi = 0;
1665     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1666     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1667     dmae.len         = len32;
1668
1669     /* issue the command and wait for completion */
1670     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1671         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1672     };
1673 }
1674
1675 void
1676 bxe_write_dmae(struct bxe_softc *sc,
1677                bus_addr_t       dma_addr,
1678                uint32_t         dst_addr,
1679                uint32_t         len32)
1680 {
1681     struct dmae_cmd dmae;
1682     int rc;
1683
1684     if (!sc->dmae_ready) {
1685         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1686
1687         if (CHIP_IS_E1(sc)) {
1688             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1689         } else {
1690             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1691         }
1692
1693         return;
1694     }
1695
1696     /* set opcode and fixed command fields */
1697     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1698
1699     /* fill in addresses and len */
1700     dmae.src_addr_lo = U64_LO(dma_addr);
1701     dmae.src_addr_hi = U64_HI(dma_addr);
1702     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1703     dmae.dst_addr_hi = 0;
1704     dmae.len         = len32;
1705
1706     /* issue the command and wait for completion */
1707     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1708         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1709     }
1710 }
1711
1712 void
1713 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1714                         bus_addr_t       phys_addr,
1715                         uint32_t         addr,
1716                         uint32_t         len)
1717 {
1718     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1719     int offset = 0;
1720
1721     while (len > dmae_wr_max) {
1722         bxe_write_dmae(sc,
1723                        (phys_addr + offset), /* src DMA address */
1724                        (addr + offset),      /* dst GRC address */
1725                        dmae_wr_max);
1726         offset += (dmae_wr_max * 4);
1727         len -= dmae_wr_max;
1728     }
1729
1730     bxe_write_dmae(sc,
1731                    (phys_addr + offset), /* src DMA address */
1732                    (addr + offset),      /* dst GRC address */
1733                    len);
1734 }
1735
1736 void
1737 bxe_set_ctx_validation(struct bxe_softc   *sc,
1738                        struct eth_context *cxt,
1739                        uint32_t           cid)
1740 {
1741     /* ustorm cxt validation */
1742     cxt->ustorm_ag_context.cdu_usage =
1743         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1744             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1745     /* xcontext validation */
1746     cxt->xstorm_ag_context.cdu_reserved =
1747         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1748             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1749 }
1750
1751 static void
1752 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1753                             uint8_t          port,
1754                             uint8_t          fw_sb_id,
1755                             uint8_t          sb_index,
1756                             uint8_t          ticks)
1757 {
1758     uint32_t addr =
1759         (BAR_CSTRORM_INTMEM +
1760          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1761
1762     REG_WR8(sc, addr, ticks);
1763
1764     BLOGD(sc, DBG_LOAD,
1765           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1766           port, fw_sb_id, sb_index, ticks);
1767 }
1768
1769 static void
1770 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1771                             uint8_t          port,
1772                             uint16_t         fw_sb_id,
1773                             uint8_t          sb_index,
1774                             uint8_t          disable)
1775 {
1776     uint32_t enable_flag =
1777         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1778     uint32_t addr =
1779         (BAR_CSTRORM_INTMEM +
1780          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1781     uint8_t flags;
1782
1783     /* clear and set */
1784     flags = REG_RD8(sc, addr);
1785     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1786     flags |= enable_flag;
1787     REG_WR8(sc, addr, flags);
1788
1789     BLOGD(sc, DBG_LOAD,
1790           "port %d fw_sb_id %d sb_index %d disable %d\n",
1791           port, fw_sb_id, sb_index, disable);
1792 }
1793
1794 void
1795 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1796                              uint8_t          fw_sb_id,
1797                              uint8_t          sb_index,
1798                              uint8_t          disable,
1799                              uint16_t         usec)
1800 {
1801     int port = SC_PORT(sc);
1802     uint8_t ticks = (usec / 4); /* XXX ??? */
1803
1804     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1805
1806     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1807     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1808 }
1809
1810 void
1811 elink_cb_udelay(struct bxe_softc *sc,
1812                 uint32_t         usecs)
1813 {
1814     DELAY(usecs);
1815 }
1816
1817 uint32_t
1818 elink_cb_reg_read(struct bxe_softc *sc,
1819                   uint32_t         reg_addr)
1820 {
1821     return (REG_RD(sc, reg_addr));
1822 }
1823
1824 void
1825 elink_cb_reg_write(struct bxe_softc *sc,
1826                    uint32_t         reg_addr,
1827                    uint32_t         val)
1828 {
1829     REG_WR(sc, reg_addr, val);
1830 }
1831
1832 void
1833 elink_cb_reg_wb_write(struct bxe_softc *sc,
1834                       uint32_t         offset,
1835                       uint32_t         *wb_write,
1836                       uint16_t         len)
1837 {
1838     REG_WR_DMAE(sc, offset, wb_write, len);
1839 }
1840
1841 void
1842 elink_cb_reg_wb_read(struct bxe_softc *sc,
1843                      uint32_t         offset,
1844                      uint32_t         *wb_write,
1845                      uint16_t         len)
1846 {
1847     REG_RD_DMAE(sc, offset, wb_write, len);
1848 }
1849
1850 uint8_t
1851 elink_cb_path_id(struct bxe_softc *sc)
1852 {
1853     return (SC_PATH(sc));
1854 }
1855
1856 void
1857 elink_cb_event_log(struct bxe_softc     *sc,
1858                    const elink_log_id_t elink_log_id,
1859                    ...)
1860 {
1861     /* XXX */
1862     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1863 }
1864
1865 static int
1866 bxe_set_spio(struct bxe_softc *sc,
1867              int              spio,
1868              uint32_t         mode)
1869 {
1870     uint32_t spio_reg;
1871
1872     /* Only 2 SPIOs are configurable */
1873     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1874         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1875         return (-1);
1876     }
1877
1878     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1879
1880     /* read SPIO and mask except the float bits */
1881     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1882
1883     switch (mode) {
1884     case MISC_SPIO_OUTPUT_LOW:
1885         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1886         /* clear FLOAT and set CLR */
1887         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1888         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1889         break;
1890
1891     case MISC_SPIO_OUTPUT_HIGH:
1892         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1893         /* clear FLOAT and set SET */
1894         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1895         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1896         break;
1897
1898     case MISC_SPIO_INPUT_HI_Z:
1899         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1900         /* set FLOAT */
1901         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1902         break;
1903
1904     default:
1905         break;
1906     }
1907
1908     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1909     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1910
1911     return (0);
1912 }
1913
1914 static int
1915 bxe_gpio_read(struct bxe_softc *sc,
1916               int              gpio_num,
1917               uint8_t          port)
1918 {
1919     /* The GPIO should be swapped if swap register is set and active */
1920     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1921                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1922     int gpio_shift = (gpio_num +
1923                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1924     uint32_t gpio_mask = (1 << gpio_shift);
1925     uint32_t gpio_reg;
1926
1927     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1928         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1929             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1930             gpio_mask);
1931         return (-1);
1932     }
1933
1934     /* read GPIO value */
1935     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1936
1937     /* get the requested pin value */
1938     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1939 }
1940
1941 static int
1942 bxe_gpio_write(struct bxe_softc *sc,
1943                int              gpio_num,
1944                uint32_t         mode,
1945                uint8_t          port)
1946 {
1947     /* The GPIO should be swapped if swap register is set and active */
1948     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1949                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1950     int gpio_shift = (gpio_num +
1951                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1952     uint32_t gpio_mask = (1 << gpio_shift);
1953     uint32_t gpio_reg;
1954
1955     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1956         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1957             " gpio_shift %d gpio_mask 0x%x\n",
1958             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1959         return (-1);
1960     }
1961
1962     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1963
1964     /* read GPIO and mask except the float bits */
1965     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1966
1967     switch (mode) {
1968     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1969         BLOGD(sc, DBG_PHY,
1970               "Set GPIO %d (shift %d) -> output low\n",
1971               gpio_num, gpio_shift);
1972         /* clear FLOAT and set CLR */
1973         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1974         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1975         break;
1976
1977     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1978         BLOGD(sc, DBG_PHY,
1979               "Set GPIO %d (shift %d) -> output high\n",
1980               gpio_num, gpio_shift);
1981         /* clear FLOAT and set SET */
1982         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1983         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1984         break;
1985
1986     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1987         BLOGD(sc, DBG_PHY,
1988               "Set GPIO %d (shift %d) -> input\n",
1989               gpio_num, gpio_shift);
1990         /* set FLOAT */
1991         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1992         break;
1993
1994     default:
1995         break;
1996     }
1997
1998     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1999     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2000
2001     return (0);
2002 }
2003
2004 static int
2005 bxe_gpio_mult_write(struct bxe_softc *sc,
2006                     uint8_t          pins,
2007                     uint32_t         mode)
2008 {
2009     uint32_t gpio_reg;
2010
2011     /* any port swapping should be handled by caller */
2012
2013     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2014
2015     /* read GPIO and mask except the float bits */
2016     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
2017     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2018     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
2019     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
2020
2021     switch (mode) {
2022     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2023         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2024         /* set CLR */
2025         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2026         break;
2027
2028     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2029         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2030         /* set SET */
2031         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2032         break;
2033
2034     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2035         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2036         /* set FLOAT */
2037         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2038         break;
2039
2040     default:
2041         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2042             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2043         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2044         return (-1);
2045     }
2046
2047     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2048     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2049
2050     return (0);
2051 }
2052
2053 static int
2054 bxe_gpio_int_write(struct bxe_softc *sc,
2055                    int              gpio_num,
2056                    uint32_t         mode,
2057                    uint8_t          port)
2058 {
2059     /* The GPIO should be swapped if swap register is set and active */
2060     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2061                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2062     int gpio_shift = (gpio_num +
2063                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2064     uint32_t gpio_mask = (1 << gpio_shift);
2065     uint32_t gpio_reg;
2066
2067     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2068         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2069             " gpio_shift %d gpio_mask 0x%x\n",
2070             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2071         return (-1);
2072     }
2073
2074     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2075
2076     /* read GPIO int */
2077     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2078
2079     switch (mode) {
2080     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2081         BLOGD(sc, DBG_PHY,
2082               "Clear GPIO INT %d (shift %d) -> output low\n",
2083               gpio_num, gpio_shift);
2084         /* clear SET and set CLR */
2085         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2086         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2087         break;
2088
2089     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2090         BLOGD(sc, DBG_PHY,
2091               "Set GPIO INT %d (shift %d) -> output high\n",
2092               gpio_num, gpio_shift);
2093         /* clear CLR and set SET */
2094         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2095         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2096         break;
2097
2098     default:
2099         break;
2100     }
2101
2102     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2103     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2104
2105     return (0);
2106 }
2107
2108 uint32_t
2109 elink_cb_gpio_read(struct bxe_softc *sc,
2110                    uint16_t         gpio_num,
2111                    uint8_t          port)
2112 {
2113     return (bxe_gpio_read(sc, gpio_num, port));
2114 }
2115
2116 uint8_t
2117 elink_cb_gpio_write(struct bxe_softc *sc,
2118                     uint16_t         gpio_num,
2119                     uint8_t          mode, /* 0=low 1=high */
2120                     uint8_t          port)
2121 {
2122     return (bxe_gpio_write(sc, gpio_num, mode, port));
2123 }
2124
2125 uint8_t
2126 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2127                          uint8_t          pins,
2128                          uint8_t          mode) /* 0=low 1=high */
2129 {
2130     return (bxe_gpio_mult_write(sc, pins, mode));
2131 }
2132
2133 uint8_t
2134 elink_cb_gpio_int_write(struct bxe_softc *sc,
2135                         uint16_t         gpio_num,
2136                         uint8_t          mode, /* 0=low 1=high */
2137                         uint8_t          port)
2138 {
2139     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2140 }
2141
2142 void
2143 elink_cb_notify_link_changed(struct bxe_softc *sc)
2144 {
2145     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2146                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2147 }
2148
2149 /* send the MCP a request, block until there is a reply */
2150 uint32_t
2151 elink_cb_fw_command(struct bxe_softc *sc,
2152                     uint32_t         command,
2153                     uint32_t         param)
2154 {
2155     int mb_idx = SC_FW_MB_IDX(sc);
2156     uint32_t seq;
2157     uint32_t rc = 0;
2158     uint32_t cnt = 1;
2159     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2160
2161     BXE_FWMB_LOCK(sc);
2162
2163     seq = ++sc->fw_seq;
2164     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2165     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2166
2167     BLOGD(sc, DBG_PHY,
2168           "wrote command 0x%08x to FW MB param 0x%08x\n",
2169           (command | seq), param);
2170
2171     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2172     do {
2173         DELAY(delay * 1000);
2174         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2175     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2176
2177     BLOGD(sc, DBG_PHY,
2178           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2179           cnt*delay, rc, seq);
2180
2181     /* is this a reply to our command? */
2182     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2183         rc &= FW_MSG_CODE_MASK;
2184     } else {
2185         /* Ruh-roh! */
2186         BLOGE(sc, "FW failed to respond!\n");
2187         // XXX bxe_fw_dump(sc);
2188         rc = 0;
2189     }
2190
2191     BXE_FWMB_UNLOCK(sc);
2192     return (rc);
2193 }
2194
2195 static uint32_t
2196 bxe_fw_command(struct bxe_softc *sc,
2197                uint32_t         command,
2198                uint32_t         param)
2199 {
2200     return (elink_cb_fw_command(sc, command, param));
2201 }
2202
2203 static void
2204 __storm_memset_dma_mapping(struct bxe_softc *sc,
2205                            uint32_t         addr,
2206                            bus_addr_t       mapping)
2207 {
2208     REG_WR(sc, addr, U64_LO(mapping));
2209     REG_WR(sc, (addr + 4), U64_HI(mapping));
2210 }
2211
2212 static void
2213 storm_memset_spq_addr(struct bxe_softc *sc,
2214                       bus_addr_t       mapping,
2215                       uint16_t         abs_fid)
2216 {
2217     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2218                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2219     __storm_memset_dma_mapping(sc, addr, mapping);
2220 }
2221
2222 static void
2223 storm_memset_vf_to_pf(struct bxe_softc *sc,
2224                       uint16_t         abs_fid,
2225                       uint16_t         pf_id)
2226 {
2227     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2228     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2229     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2230     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2231 }
2232
2233 static void
2234 storm_memset_func_en(struct bxe_softc *sc,
2235                      uint16_t         abs_fid,
2236                      uint8_t          enable)
2237 {
2238     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2239     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2240     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2241     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2242 }
2243
2244 static void
2245 storm_memset_eq_data(struct bxe_softc       *sc,
2246                      struct event_ring_data *eq_data,
2247                      uint16_t               pfid)
2248 {
2249     uint32_t addr;
2250     size_t size;
2251
2252     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2253     size = sizeof(struct event_ring_data);
2254     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2255 }
2256
2257 static void
2258 storm_memset_eq_prod(struct bxe_softc *sc,
2259                      uint16_t         eq_prod,
2260                      uint16_t         pfid)
2261 {
2262     uint32_t addr = (BAR_CSTRORM_INTMEM +
2263                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2264     REG_WR16(sc, addr, eq_prod);
2265 }
2266
2267 /*
2268  * Post a slowpath command.
2269  *
2270  * A slowpath command is used to propogate a configuration change through
2271  * the controller in a controlled manner, allowing each STORM processor and
2272  * other H/W blocks to phase in the change.  The commands sent on the
2273  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2274  * completion of the ramrod will occur in different ways.  Here's a
2275  * breakdown of ramrods and how they complete:
2276  *
2277  * RAMROD_CMD_ID_ETH_PORT_SETUP
2278  *   Used to setup the leading connection on a port.  Completes on the
2279  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2280  *
2281  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2282  *   Used to setup an additional connection on a port.  Completes on the
2283  *   RCQ of the multi-queue/RSS connection being initialized.
2284  *
2285  * RAMROD_CMD_ID_ETH_STAT_QUERY
2286  *   Used to force the storm processors to update the statistics database
2287  *   in host memory.  This ramrod is send on the leading connection CID and
2288  *   completes as an index increment of the CSTORM on the default status
2289  *   block.
2290  *
2291  * RAMROD_CMD_ID_ETH_UPDATE
2292  *   Used to update the state of the leading connection, usually to udpate
2293  *   the RSS indirection table.  Completes on the RCQ of the leading
2294  *   connection. (Not currently used under FreeBSD until OS support becomes
2295  *   available.)
2296  *
2297  * RAMROD_CMD_ID_ETH_HALT
2298  *   Used when tearing down a connection prior to driver unload.  Completes
2299  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2300  *   use this on the leading connection.
2301  *
2302  * RAMROD_CMD_ID_ETH_SET_MAC
2303  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2304  *   the RCQ of the leading connection.
2305  *
2306  * RAMROD_CMD_ID_ETH_CFC_DEL
2307  *   Used when tearing down a conneciton prior to driver unload.  Completes
2308  *   on the RCQ of the leading connection (since the current connection
2309  *   has been completely removed from controller memory).
2310  *
2311  * RAMROD_CMD_ID_ETH_PORT_DEL
2312  *   Used to tear down the leading connection prior to driver unload,
2313  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2314  *   default status block.
2315  *
2316  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2317  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2318  *   RSS connection that is being offloaded.  (Not currently used under
2319  *   FreeBSD.)
2320  *
2321  * There can only be one command pending per function.
2322  *
2323  * Returns:
2324  *   0 = Success, !0 = Failure.
2325  */
2326
2327 /* must be called under the spq lock */
2328 static inline
2329 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2330 {
2331     struct eth_spe *next_spe = sc->spq_prod_bd;
2332
2333     if (sc->spq_prod_bd == sc->spq_last_bd) {
2334         /* wrap back to the first eth_spq */
2335         sc->spq_prod_bd = sc->spq;
2336         sc->spq_prod_idx = 0;
2337     } else {
2338         sc->spq_prod_bd++;
2339         sc->spq_prod_idx++;
2340     }
2341
2342     return (next_spe);
2343 }
2344
2345 /* must be called under the spq lock */
2346 static inline
2347 void bxe_sp_prod_update(struct bxe_softc *sc)
2348 {
2349     int func = SC_FUNC(sc);
2350
2351     /*
2352      * Make sure that BD data is updated before writing the producer.
2353      * BD data is written to the memory, the producer is read from the
2354      * memory, thus we need a full memory barrier to ensure the ordering.
2355      */
2356     mb();
2357
2358     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2359              sc->spq_prod_idx);
2360
2361     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2362                       BUS_SPACE_BARRIER_WRITE);
2363 }
2364
2365 /**
2366  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2367  *
2368  * @cmd:      command to check
2369  * @cmd_type: command type
2370  */
2371 static inline
2372 int bxe_is_contextless_ramrod(int cmd,
2373                               int cmd_type)
2374 {
2375     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2376         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2377         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2378         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2379         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2380         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2381         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2382         return (TRUE);
2383     } else {
2384         return (FALSE);
2385     }
2386 }
2387
2388 /**
2389  * bxe_sp_post - place a single command on an SP ring
2390  *
2391  * @sc:         driver handle
2392  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2393  * @cid:        SW CID the command is related to
2394  * @data_hi:    command private data address (high 32 bits)
2395  * @data_lo:    command private data address (low 32 bits)
2396  * @cmd_type:   command type (e.g. NONE, ETH)
2397  *
2398  * SP data is handled as if it's always an address pair, thus data fields are
2399  * not swapped to little endian in upper functions. Instead this function swaps
2400  * data as if it's two uint32 fields.
2401  */
2402 int
2403 bxe_sp_post(struct bxe_softc *sc,
2404             int              command,
2405             int              cid,
2406             uint32_t         data_hi,
2407             uint32_t         data_lo,
2408             int              cmd_type)
2409 {
2410     struct eth_spe *spe;
2411     uint16_t type;
2412     int common;
2413
2414     common = bxe_is_contextless_ramrod(command, cmd_type);
2415
2416     BXE_SP_LOCK(sc);
2417
2418     if (common) {
2419         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2420             BLOGE(sc, "EQ ring is full!\n");
2421             BXE_SP_UNLOCK(sc);
2422             return (-1);
2423         }
2424     } else {
2425         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2426             BLOGE(sc, "SPQ ring is full!\n");
2427             BXE_SP_UNLOCK(sc);
2428             return (-1);
2429         }
2430     }
2431
2432     spe = bxe_sp_get_next(sc);
2433
2434     /* CID needs port number to be encoded int it */
2435     spe->hdr.conn_and_cmd_data =
2436         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2437
2438     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2439
2440     /* TBD: Check if it works for VFs */
2441     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2442              SPE_HDR_T_FUNCTION_ID);
2443
2444     spe->hdr.type = htole16(type);
2445
2446     spe->data.update_data_addr.hi = htole32(data_hi);
2447     spe->data.update_data_addr.lo = htole32(data_lo);
2448
2449     /*
2450      * It's ok if the actual decrement is issued towards the memory
2451      * somewhere between the lock and unlock. Thus no more explict
2452      * memory barrier is needed.
2453      */
2454     if (common) {
2455         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2456     } else {
2457         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2458     }
2459
2460     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2461     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2462           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2463     BLOGD(sc, DBG_SP,
2464           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2465           sc->spq_prod_idx,
2466           (uint32_t)U64_HI(sc->spq_dma.paddr),
2467           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2468           command,
2469           common,
2470           HW_CID(sc, cid),
2471           data_hi,
2472           data_lo,
2473           type,
2474           atomic_load_acq_long(&sc->cq_spq_left),
2475           atomic_load_acq_long(&sc->eq_spq_left));
2476
2477     bxe_sp_prod_update(sc);
2478
2479     BXE_SP_UNLOCK(sc);
2480     return (0);
2481 }
2482
2483 /**
2484  * bxe_debug_print_ind_table - prints the indirection table configuration.
2485  *
2486  * @sc: driver hanlde
2487  * @p:  pointer to rss configuration
2488  */
2489
2490 /*
2491  * FreeBSD Device probe function.
2492  *
2493  * Compares the device found to the driver's list of supported devices and
2494  * reports back to the bsd loader whether this is the right driver for the device.
2495  * This is the driver entry function called from the "kldload" command.
2496  *
2497  * Returns:
2498  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2499  */
2500 static int
2501 bxe_probe(device_t dev)
2502 {
2503     struct bxe_softc *sc;
2504     struct bxe_device_type *t;
2505     char *descbuf;
2506     uint16_t did, sdid, svid, vid;
2507
2508     /* Find our device structure */
2509     sc = device_get_softc(dev);
2510     sc->dev = dev;
2511     t = bxe_devs;
2512
2513     /* Get the data for the device to be probed. */
2514     vid  = pci_get_vendor(dev);
2515     did  = pci_get_device(dev);
2516     svid = pci_get_subvendor(dev);
2517     sdid = pci_get_subdevice(dev);
2518
2519     BLOGD(sc, DBG_LOAD,
2520           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2521           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2522
2523     /* Look through the list of known devices for a match. */
2524     while (t->bxe_name != NULL) {
2525         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2526             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2527             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2528             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2529             if (descbuf == NULL)
2530                 return (ENOMEM);
2531
2532             /* Print out the device identity. */
2533             snprintf(descbuf, BXE_DEVDESC_MAX,
2534                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2535                      (((pci_read_config(dev, PCIR_REVID, 4) &
2536                         0xf0) >> 4) + 'A'),
2537                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2538                      BXE_DRIVER_VERSION);
2539
2540             device_set_desc_copy(dev, descbuf);
2541             free(descbuf, M_TEMP);
2542             return (BUS_PROBE_DEFAULT);
2543         }
2544         t++;
2545     }
2546
2547     return (ENXIO);
2548 }
2549
2550 static void
2551 bxe_init_mutexes(struct bxe_softc *sc)
2552 {
2553 #ifdef BXE_CORE_LOCK_SX
2554     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2555              "bxe%d_core_lock", sc->unit);
2556     sx_init(&sc->core_sx, sc->core_sx_name);
2557 #else
2558     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2559              "bxe%d_core_lock", sc->unit);
2560     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2561 #endif
2562
2563     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2564              "bxe%d_sp_lock", sc->unit);
2565     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2566
2567     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2568              "bxe%d_dmae_lock", sc->unit);
2569     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2570
2571     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2572              "bxe%d_phy_lock", sc->unit);
2573     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2574
2575     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2576              "bxe%d_fwmb_lock", sc->unit);
2577     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2578
2579     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2580              "bxe%d_print_lock", sc->unit);
2581     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2582
2583     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2584              "bxe%d_stats_lock", sc->unit);
2585     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2586
2587     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2588              "bxe%d_mcast_lock", sc->unit);
2589     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2590 }
2591
2592 static void
2593 bxe_release_mutexes(struct bxe_softc *sc)
2594 {
2595 #ifdef BXE_CORE_LOCK_SX
2596     sx_destroy(&sc->core_sx);
2597 #else
2598     if (mtx_initialized(&sc->core_mtx)) {
2599         mtx_destroy(&sc->core_mtx);
2600     }
2601 #endif
2602
2603     if (mtx_initialized(&sc->sp_mtx)) {
2604         mtx_destroy(&sc->sp_mtx);
2605     }
2606
2607     if (mtx_initialized(&sc->dmae_mtx)) {
2608         mtx_destroy(&sc->dmae_mtx);
2609     }
2610
2611     if (mtx_initialized(&sc->port.phy_mtx)) {
2612         mtx_destroy(&sc->port.phy_mtx);
2613     }
2614
2615     if (mtx_initialized(&sc->fwmb_mtx)) {
2616         mtx_destroy(&sc->fwmb_mtx);
2617     }
2618
2619     if (mtx_initialized(&sc->print_mtx)) {
2620         mtx_destroy(&sc->print_mtx);
2621     }
2622
2623     if (mtx_initialized(&sc->stats_mtx)) {
2624         mtx_destroy(&sc->stats_mtx);
2625     }
2626
2627     if (mtx_initialized(&sc->mcast_mtx)) {
2628         mtx_destroy(&sc->mcast_mtx);
2629     }
2630 }
2631
2632 static void
2633 bxe_tx_disable(struct bxe_softc* sc)
2634 {
2635     struct ifnet *ifp = sc->ifnet;
2636
2637     /* tell the stack the driver is stopped and TX queue is full */
2638     if (ifp != NULL) {
2639         ifp->if_drv_flags = 0;
2640     }
2641 }
2642
2643 static void
2644 bxe_drv_pulse(struct bxe_softc *sc)
2645 {
2646     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2647              sc->fw_drv_pulse_wr_seq);
2648 }
2649
2650 static inline uint16_t
2651 bxe_tx_avail(struct bxe_softc *sc,
2652              struct bxe_fastpath *fp)
2653 {
2654     int16_t  used;
2655     uint16_t prod;
2656     uint16_t cons;
2657
2658     prod = fp->tx_bd_prod;
2659     cons = fp->tx_bd_cons;
2660
2661     used = SUB_S16(prod, cons);
2662
2663     return (int16_t)(sc->tx_ring_size) - used;
2664 }
2665
2666 static inline int
2667 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2668 {
2669     uint16_t hw_cons;
2670
2671     mb(); /* status block fields can change */
2672     hw_cons = le16toh(*fp->tx_cons_sb);
2673     return (hw_cons != fp->tx_pkt_cons);
2674 }
2675
2676 static inline uint8_t
2677 bxe_has_tx_work(struct bxe_fastpath *fp)
2678 {
2679     /* expand this for multi-cos if ever supported */
2680     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2681 }
2682
2683 static inline int
2684 bxe_has_rx_work(struct bxe_fastpath *fp)
2685 {
2686     uint16_t rx_cq_cons_sb;
2687
2688     mb(); /* status block fields can change */
2689     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2690     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2691         rx_cq_cons_sb++;
2692     return (fp->rx_cq_cons != rx_cq_cons_sb);
2693 }
2694
2695 static void
2696 bxe_sp_event(struct bxe_softc    *sc,
2697              struct bxe_fastpath *fp,
2698              union eth_rx_cqe    *rr_cqe)
2699 {
2700     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2701     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2702     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2703     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2704
2705     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2706           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2707
2708     switch (command) {
2709     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2710         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2711         drv_cmd = ECORE_Q_CMD_UPDATE;
2712         break;
2713
2714     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2715         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2716         drv_cmd = ECORE_Q_CMD_SETUP;
2717         break;
2718
2719     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2720         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2721         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2722         break;
2723
2724     case (RAMROD_CMD_ID_ETH_HALT):
2725         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2726         drv_cmd = ECORE_Q_CMD_HALT;
2727         break;
2728
2729     case (RAMROD_CMD_ID_ETH_TERMINATE):
2730         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2731         drv_cmd = ECORE_Q_CMD_TERMINATE;
2732         break;
2733
2734     case (RAMROD_CMD_ID_ETH_EMPTY):
2735         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2736         drv_cmd = ECORE_Q_CMD_EMPTY;
2737         break;
2738
2739     default:
2740         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2741               command, fp->index);
2742         return;
2743     }
2744
2745     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2746         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2747         /*
2748          * q_obj->complete_cmd() failure means that this was
2749          * an unexpected completion.
2750          *
2751          * In this case we don't want to increase the sc->spq_left
2752          * because apparently we haven't sent this command the first
2753          * place.
2754          */
2755         // bxe_panic(sc, ("Unexpected SP completion\n"));
2756         return;
2757     }
2758
2759     atomic_add_acq_long(&sc->cq_spq_left, 1);
2760
2761     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2762           atomic_load_acq_long(&sc->cq_spq_left));
2763 }
2764
2765 /*
2766  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2767  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2768  * the current aggregation queue as in-progress.
2769  */
2770 static void
2771 bxe_tpa_start(struct bxe_softc            *sc,
2772               struct bxe_fastpath         *fp,
2773               uint16_t                    queue,
2774               uint16_t                    cons,
2775               uint16_t                    prod,
2776               struct eth_fast_path_rx_cqe *cqe)
2777 {
2778     struct bxe_sw_rx_bd tmp_bd;
2779     struct bxe_sw_rx_bd *rx_buf;
2780     struct eth_rx_bd *rx_bd;
2781     int max_agg_queues;
2782     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2783     uint16_t index;
2784
2785     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2786                        "cons=%d prod=%d\n",
2787           fp->index, queue, cons, prod);
2788
2789     max_agg_queues = MAX_AGG_QS(sc);
2790
2791     KASSERT((queue < max_agg_queues),
2792             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2793              fp->index, queue, max_agg_queues));
2794
2795     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2796             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2797              fp->index, queue));
2798
2799     /* copy the existing mbuf and mapping from the TPA pool */
2800     tmp_bd = tpa_info->bd;
2801
2802     if (tmp_bd.m == NULL) {
2803         uint32_t *tmp;
2804
2805         tmp = (uint32_t *)cqe;
2806
2807         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2808               fp->index, queue, cons, prod);
2809         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2810             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2811             
2812         /* XXX Error handling? */
2813         return;
2814     }
2815
2816     /* change the TPA queue to the start state */
2817     tpa_info->state            = BXE_TPA_STATE_START;
2818     tpa_info->placement_offset = cqe->placement_offset;
2819     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2820     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2821     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2822
2823     fp->rx_tpa_queue_used |= (1 << queue);
2824
2825     /*
2826      * If all the buffer descriptors are filled with mbufs then fill in
2827      * the current consumer index with a new BD. Else if a maximum Rx
2828      * buffer limit is imposed then fill in the next producer index.
2829      */
2830     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2831                 prod : cons;
2832
2833     /* move the received mbuf and mapping to TPA pool */
2834     tpa_info->bd = fp->rx_mbuf_chain[cons];
2835
2836     /* release any existing RX BD mbuf mappings */
2837     if (cons != index) {
2838         rx_buf = &fp->rx_mbuf_chain[cons];
2839
2840         if (rx_buf->m_map != NULL) {
2841             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2842                             BUS_DMASYNC_POSTREAD);
2843             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2844         }
2845
2846         /*
2847          * We get here when the maximum number of rx buffers is less than
2848          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2849          * it out here without concern of a memory leak.
2850          */
2851         fp->rx_mbuf_chain[cons].m = NULL;
2852     }
2853
2854     /* update the Rx SW BD with the mbuf info from the TPA pool */
2855     fp->rx_mbuf_chain[index] = tmp_bd;
2856
2857     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2858     rx_bd = &fp->rx_chain[index];
2859     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2860     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2861 }
2862
2863 /*
2864  * When a TPA aggregation is completed, loop through the individual mbufs
2865  * of the aggregation, combining them into a single mbuf which will be sent
2866  * up the stack. Refill all freed SGEs with mbufs as we go along.
2867  */
2868 static int
2869 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2870                    struct bxe_fastpath       *fp,
2871                    struct bxe_sw_tpa_info    *tpa_info,
2872                    uint16_t                  queue,
2873                    uint16_t                  pages,
2874                    struct mbuf               *m,
2875                                struct eth_end_agg_rx_cqe *cqe,
2876                    uint16_t                  cqe_idx)
2877 {
2878     struct mbuf *m_frag;
2879     uint32_t frag_len, frag_size, i;
2880     uint16_t sge_idx;
2881     int rc = 0;
2882     int j;
2883
2884     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2885
2886     BLOGD(sc, DBG_LRO,
2887           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2888           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2889
2890     /* make sure the aggregated frame is not too big to handle */
2891     if (pages > 8 * PAGES_PER_SGE) {
2892
2893         uint32_t *tmp = (uint32_t *)cqe;
2894
2895         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2896                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2897               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2898               tpa_info->len_on_bd, frag_size);
2899
2900         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2901             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2902
2903         bxe_panic(sc, ("sge page count error\n"));
2904         return (EINVAL);
2905     }
2906
2907     /*
2908      * Scan through the scatter gather list pulling individual mbufs into a
2909      * single mbuf for the host stack.
2910      */
2911     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2912         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2913
2914         /*
2915          * Firmware gives the indices of the SGE as if the ring is an array
2916          * (meaning that the "next" element will consume 2 indices).
2917          */
2918         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2919
2920         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2921                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2922               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2923
2924         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2925
2926         /* allocate a new mbuf for the SGE */
2927         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2928         if (rc) {
2929             /* Leave all remaining SGEs in the ring! */
2930             return (rc);
2931         }
2932
2933         /* update the fragment length */
2934         m_frag->m_len = frag_len;
2935
2936         /* concatenate the fragment to the head mbuf */
2937         m_cat(m, m_frag);
2938         fp->eth_q_stats.mbuf_alloc_sge--;
2939
2940         /* update the TPA mbuf size and remaining fragment size */
2941         m->m_pkthdr.len += frag_len;
2942         frag_size -= frag_len;
2943     }
2944
2945     BLOGD(sc, DBG_LRO,
2946           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2947           fp->index, queue, frag_size);
2948
2949     return (rc);
2950 }
2951
2952 static inline void
2953 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2954 {
2955     int i, j;
2956
2957     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2958         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2959
2960         for (j = 0; j < 2; j++) {
2961             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2962             idx--;
2963         }
2964     }
2965 }
2966
2967 static inline void
2968 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2969 {
2970     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2971     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2972
2973     /*
2974      * Clear the two last indices in the page to 1. These are the indices that
2975      * correspond to the "next" element, hence will never be indicated and
2976      * should be removed from the calculations.
2977      */
2978     bxe_clear_sge_mask_next_elems(fp);
2979 }
2980
2981 static inline void
2982 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2983                         uint16_t            idx)
2984 {
2985     uint16_t last_max = fp->last_max_sge;
2986
2987     if (SUB_S16(idx, last_max) > 0) {
2988         fp->last_max_sge = idx;
2989     }
2990 }
2991
2992 static inline void
2993 bxe_update_sge_prod(struct bxe_softc          *sc,
2994                     struct bxe_fastpath       *fp,
2995                     uint16_t                  sge_len,
2996                     union eth_sgl_or_raw_data *cqe)
2997 {
2998     uint16_t last_max, last_elem, first_elem;
2999     uint16_t delta = 0;
3000     uint16_t i;
3001
3002     if (!sge_len) {
3003         return;
3004     }
3005
3006     /* first mark all used pages */
3007     for (i = 0; i < sge_len; i++) {
3008         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
3009                             RX_SGE(le16toh(cqe->sgl[i])));
3010     }
3011
3012     BLOGD(sc, DBG_LRO,
3013           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
3014           fp->index, sge_len - 1,
3015           le16toh(cqe->sgl[sge_len - 1]));
3016
3017     /* assume that the last SGE index is the biggest */
3018     bxe_update_last_max_sge(fp,
3019                             le16toh(cqe->sgl[sge_len - 1]));
3020
3021     last_max = RX_SGE(fp->last_max_sge);
3022     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3023     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3024
3025     /* if ring is not full */
3026     if (last_elem + 1 != first_elem) {
3027         last_elem++;
3028     }
3029
3030     /* now update the prod */
3031     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3032         if (__predict_true(fp->sge_mask[i])) {
3033             break;
3034         }
3035
3036         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3037         delta += BIT_VEC64_ELEM_SZ;
3038     }
3039
3040     if (delta > 0) {
3041         fp->rx_sge_prod += delta;
3042         /* clear page-end entries */
3043         bxe_clear_sge_mask_next_elems(fp);
3044     }
3045
3046     BLOGD(sc, DBG_LRO,
3047           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3048           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3049 }
3050
3051 /*
3052  * The aggregation on the current TPA queue has completed. Pull the individual
3053  * mbuf fragments together into a single mbuf, perform all necessary checksum
3054  * calculations, and send the resuting mbuf to the stack.
3055  */
3056 static void
3057 bxe_tpa_stop(struct bxe_softc          *sc,
3058              struct bxe_fastpath       *fp,
3059              struct bxe_sw_tpa_info    *tpa_info,
3060              uint16_t                  queue,
3061              uint16_t                  pages,
3062                          struct eth_end_agg_rx_cqe *cqe,
3063              uint16_t                  cqe_idx)
3064 {
3065     struct ifnet *ifp = sc->ifnet;
3066     struct mbuf *m;
3067     int rc = 0;
3068
3069     BLOGD(sc, DBG_LRO,
3070           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3071           fp->index, queue, tpa_info->placement_offset,
3072           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3073
3074     m = tpa_info->bd.m;
3075
3076     /* allocate a replacement before modifying existing mbuf */
3077     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3078     if (rc) {
3079         /* drop the frame and log an error */
3080         fp->eth_q_stats.rx_soft_errors++;
3081         goto bxe_tpa_stop_exit;
3082     }
3083
3084     /* we have a replacement, fixup the current mbuf */
3085     m_adj(m, tpa_info->placement_offset);
3086     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3087
3088     /* mark the checksums valid (taken care of by the firmware) */
3089     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3090     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3091     m->m_pkthdr.csum_data = 0xffff;
3092     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3093                                CSUM_IP_VALID   |
3094                                CSUM_DATA_VALID |
3095                                CSUM_PSEUDO_HDR);
3096
3097     /* aggregate all of the SGEs into a single mbuf */
3098     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3099     if (rc) {
3100         /* drop the packet and log an error */
3101         fp->eth_q_stats.rx_soft_errors++;
3102         m_freem(m);
3103     } else {
3104         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3105             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3106             m->m_flags |= M_VLANTAG;
3107         }
3108
3109         /* assign packet to this interface interface */
3110         m->m_pkthdr.rcvif = ifp;
3111
3112 #if __FreeBSD_version >= 800000
3113         /* specify what RSS queue was used for this flow */
3114         m->m_pkthdr.flowid = fp->index;
3115         BXE_SET_FLOWID(m);
3116 #endif
3117
3118         ifp->if_ipackets++;
3119         fp->eth_q_stats.rx_tpa_pkts++;
3120
3121         /* pass the frame to the stack */
3122         (*ifp->if_input)(ifp, m);
3123     }
3124
3125     /* we passed an mbuf up the stack or dropped the frame */
3126     fp->eth_q_stats.mbuf_alloc_tpa--;
3127
3128 bxe_tpa_stop_exit:
3129
3130     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3131     fp->rx_tpa_queue_used &= ~(1 << queue);
3132 }
3133
3134 static uint8_t
3135 bxe_service_rxsgl(
3136                  struct bxe_fastpath *fp,
3137                  uint16_t len,
3138                  uint16_t lenonbd,
3139                  struct mbuf *m,
3140                  struct eth_fast_path_rx_cqe *cqe_fp)
3141 {
3142     struct mbuf *m_frag;
3143     uint16_t frags, frag_len;
3144     uint16_t sge_idx = 0;
3145     uint16_t j;
3146     uint8_t i, rc = 0;
3147     uint32_t frag_size;
3148
3149     /* adjust the mbuf */
3150     m->m_len = lenonbd;
3151
3152     frag_size =  len - lenonbd;
3153     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3154
3155     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3156         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3157
3158         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3159         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3160         m_frag->m_len = frag_len;
3161
3162        /* allocate a new mbuf for the SGE */
3163         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3164         if (rc) {
3165             /* Leave all remaining SGEs in the ring! */
3166             return (rc);
3167         }
3168         fp->eth_q_stats.mbuf_alloc_sge--;
3169
3170         /* concatenate the fragment to the head mbuf */
3171         m_cat(m, m_frag);
3172
3173         frag_size -= frag_len;
3174     }
3175
3176     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3177
3178     return rc;
3179 }
3180
3181 static uint8_t
3182 bxe_rxeof(struct bxe_softc    *sc,
3183           struct bxe_fastpath *fp)
3184 {
3185     struct ifnet *ifp = sc->ifnet;
3186     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3187     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3188     int rx_pkts = 0;
3189     int rc = 0;
3190
3191     BXE_FP_RX_LOCK(fp);
3192
3193     /* CQ "next element" is of the size of the regular element */
3194     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3195     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3196         hw_cq_cons++;
3197     }
3198
3199     bd_cons = fp->rx_bd_cons;
3200     bd_prod = fp->rx_bd_prod;
3201     bd_prod_fw = bd_prod;
3202     sw_cq_cons = fp->rx_cq_cons;
3203     sw_cq_prod = fp->rx_cq_prod;
3204
3205     /*
3206      * Memory barrier necessary as speculative reads of the rx
3207      * buffer can be ahead of the index in the status block
3208      */
3209     rmb();
3210
3211     BLOGD(sc, DBG_RX,
3212           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3213           fp->index, hw_cq_cons, sw_cq_cons);
3214
3215     while (sw_cq_cons != hw_cq_cons) {
3216         struct bxe_sw_rx_bd *rx_buf = NULL;
3217         union eth_rx_cqe *cqe;
3218         struct eth_fast_path_rx_cqe *cqe_fp;
3219         uint8_t cqe_fp_flags;
3220         enum eth_rx_cqe_type cqe_fp_type;
3221         uint16_t len, lenonbd,  pad;
3222         struct mbuf *m = NULL;
3223
3224         comp_ring_cons = RCQ(sw_cq_cons);
3225         bd_prod = RX_BD(bd_prod);
3226         bd_cons = RX_BD(bd_cons);
3227
3228         cqe          = &fp->rcq_chain[comp_ring_cons];
3229         cqe_fp       = &cqe->fast_path_cqe;
3230         cqe_fp_flags = cqe_fp->type_error_flags;
3231         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3232
3233         BLOGD(sc, DBG_RX,
3234               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3235               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3236               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3237               fp->index,
3238               hw_cq_cons,
3239               sw_cq_cons,
3240               bd_prod,
3241               bd_cons,
3242               CQE_TYPE(cqe_fp_flags),
3243               cqe_fp_flags,
3244               cqe_fp->status_flags,
3245               le32toh(cqe_fp->rss_hash_result),
3246               le16toh(cqe_fp->vlan_tag),
3247               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3248               le16toh(cqe_fp->len_on_bd));
3249
3250         /* is this a slowpath msg? */
3251         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3252             bxe_sp_event(sc, fp, cqe);
3253             goto next_cqe;
3254         }
3255
3256         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3257
3258         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3259             struct bxe_sw_tpa_info *tpa_info;
3260             uint16_t frag_size, pages;
3261             uint8_t queue;
3262
3263             if (CQE_TYPE_START(cqe_fp_type)) {
3264                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3265                               bd_cons, bd_prod, cqe_fp);
3266                 m = NULL; /* packet not ready yet */
3267                 goto next_rx;
3268             }
3269
3270             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3271                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3272
3273             queue = cqe->end_agg_cqe.queue_index;
3274             tpa_info = &fp->rx_tpa_info[queue];
3275
3276             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3277                   fp->index, queue);
3278
3279             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3280                          tpa_info->len_on_bd);
3281             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3282
3283             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3284                          &cqe->end_agg_cqe, comp_ring_cons);
3285
3286             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3287
3288             goto next_cqe;
3289         }
3290
3291         /* non TPA */
3292
3293         /* is this an error packet? */
3294         if (__predict_false(cqe_fp_flags &
3295                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3296             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3297             fp->eth_q_stats.rx_soft_errors++;
3298             goto next_rx;
3299         }
3300
3301         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3302         lenonbd = le16toh(cqe_fp->len_on_bd);
3303         pad = cqe_fp->placement_offset;
3304
3305         m = rx_buf->m;
3306
3307         if (__predict_false(m == NULL)) {
3308             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3309                   bd_cons, fp->index);
3310             goto next_rx;
3311         }
3312
3313         /* XXX double copy if packet length under a threshold */
3314
3315         /*
3316          * If all the buffer descriptors are filled with mbufs then fill in
3317          * the current consumer index with a new BD. Else if a maximum Rx
3318          * buffer limit is imposed then fill in the next producer index.
3319          */
3320         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3321                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3322                                       bd_prod : bd_cons);
3323         if (rc != 0) {
3324
3325             /* we simply reuse the received mbuf and don't post it to the stack */
3326             m = NULL;
3327
3328             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3329                   fp->index, rc);
3330             fp->eth_q_stats.rx_soft_errors++;
3331
3332             if (sc->max_rx_bufs != RX_BD_USABLE) {
3333                 /* copy this consumer index to the producer index */
3334                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3335                        sizeof(struct bxe_sw_rx_bd));
3336                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3337             }
3338
3339             goto next_rx;
3340         }
3341
3342         /* current mbuf was detached from the bd */
3343         fp->eth_q_stats.mbuf_alloc_rx--;
3344
3345         /* we allocated a replacement mbuf, fixup the current one */
3346         m_adj(m, pad);
3347         m->m_pkthdr.len = m->m_len = len;
3348
3349         if ((len > 60) && (len > lenonbd)) {
3350             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3351             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3352             if (rc)
3353                 break;
3354             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3355         } else if (lenonbd < len) {
3356             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3357         }
3358
3359         /* assign packet to this interface interface */
3360         m->m_pkthdr.rcvif = ifp;
3361
3362         /* assume no hardware checksum has complated */
3363         m->m_pkthdr.csum_flags = 0;
3364
3365         /* validate checksum if offload enabled */
3366         if (ifp->if_capenable & IFCAP_RXCSUM) {
3367             /* check for a valid IP frame */
3368             if (!(cqe->fast_path_cqe.status_flags &
3369                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3370                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3371                 if (__predict_false(cqe_fp_flags &
3372                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3373                     fp->eth_q_stats.rx_hw_csum_errors++;
3374                 } else {
3375                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3376                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3377                 }
3378             }
3379
3380             /* check for a valid TCP/UDP frame */
3381             if (!(cqe->fast_path_cqe.status_flags &
3382                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3383                 if (__predict_false(cqe_fp_flags &
3384                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3385                     fp->eth_q_stats.rx_hw_csum_errors++;
3386                 } else {
3387                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3388                     m->m_pkthdr.csum_data = 0xFFFF;
3389                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3390                                                CSUM_PSEUDO_HDR);
3391                 }
3392             }
3393         }
3394
3395         /* if there is a VLAN tag then flag that info */
3396         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3397             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3398             m->m_flags |= M_VLANTAG;
3399         }
3400
3401 #if __FreeBSD_version >= 800000
3402         /* specify what RSS queue was used for this flow */
3403         m->m_pkthdr.flowid = fp->index;
3404         BXE_SET_FLOWID(m);
3405 #endif
3406
3407 next_rx:
3408
3409         bd_cons    = RX_BD_NEXT(bd_cons);
3410         bd_prod    = RX_BD_NEXT(bd_prod);
3411         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3412
3413         /* pass the frame to the stack */
3414         if (__predict_true(m != NULL)) {
3415             ifp->if_ipackets++;
3416             rx_pkts++;
3417             (*ifp->if_input)(ifp, m);
3418         }
3419
3420 next_cqe:
3421
3422         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3423         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3424
3425         /* limit spinning on the queue */
3426         if (rc != 0)
3427             break;
3428
3429         if (rx_pkts == sc->rx_budget) {
3430             fp->eth_q_stats.rx_budget_reached++;
3431             break;
3432         }
3433     } /* while work to do */
3434
3435     fp->rx_bd_cons = bd_cons;
3436     fp->rx_bd_prod = bd_prod_fw;
3437     fp->rx_cq_cons = sw_cq_cons;
3438     fp->rx_cq_prod = sw_cq_prod;
3439
3440     /* Update producers */
3441     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3442
3443     fp->eth_q_stats.rx_pkts += rx_pkts;
3444     fp->eth_q_stats.rx_calls++;
3445
3446     BXE_FP_RX_UNLOCK(fp);
3447
3448     return (sw_cq_cons != hw_cq_cons);
3449 }
3450
3451 static uint16_t
3452 bxe_free_tx_pkt(struct bxe_softc    *sc,
3453                 struct bxe_fastpath *fp,
3454                 uint16_t            idx)
3455 {
3456     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3457     struct eth_tx_start_bd *tx_start_bd;
3458     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3459     uint16_t new_cons;
3460     int nbd;
3461
3462     /* unmap the mbuf from non-paged memory */
3463     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3464
3465     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3466     nbd = le16toh(tx_start_bd->nbd) - 1;
3467
3468     new_cons = (tx_buf->first_bd + nbd);
3469
3470     /* free the mbuf */
3471     if (__predict_true(tx_buf->m != NULL)) {
3472         m_freem(tx_buf->m);
3473         fp->eth_q_stats.mbuf_alloc_tx--;
3474     } else {
3475         fp->eth_q_stats.tx_chain_lost_mbuf++;
3476     }
3477
3478     tx_buf->m = NULL;
3479     tx_buf->first_bd = 0;
3480
3481     return (new_cons);
3482 }
3483
3484 /* transmit timeout watchdog */
3485 static int
3486 bxe_watchdog(struct bxe_softc    *sc,
3487              struct bxe_fastpath *fp)
3488 {
3489     BXE_FP_TX_LOCK(fp);
3490
3491     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3492         BXE_FP_TX_UNLOCK(fp);
3493         return (0);
3494     }
3495
3496     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3497     if(sc->trigger_grcdump) {
3498          /* taking grcdump */
3499          bxe_grc_dump(sc);
3500     }
3501
3502     BXE_FP_TX_UNLOCK(fp);
3503
3504     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3505     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3506
3507     return (-1);
3508 }
3509
3510 /* processes transmit completions */
3511 static uint8_t
3512 bxe_txeof(struct bxe_softc    *sc,
3513           struct bxe_fastpath *fp)
3514 {
3515     struct ifnet *ifp = sc->ifnet;
3516     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3517     uint16_t tx_bd_avail;
3518
3519     BXE_FP_TX_LOCK_ASSERT(fp);
3520
3521     bd_cons = fp->tx_bd_cons;
3522     hw_cons = le16toh(*fp->tx_cons_sb);
3523     sw_cons = fp->tx_pkt_cons;
3524
3525     while (sw_cons != hw_cons) {
3526         pkt_cons = TX_BD(sw_cons);
3527
3528         BLOGD(sc, DBG_TX,
3529               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3530               fp->index, hw_cons, sw_cons, pkt_cons);
3531
3532         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3533
3534         sw_cons++;
3535     }
3536
3537     fp->tx_pkt_cons = sw_cons;
3538     fp->tx_bd_cons  = bd_cons;
3539
3540     BLOGD(sc, DBG_TX,
3541           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3542           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3543
3544     mb();
3545
3546     tx_bd_avail = bxe_tx_avail(sc, fp);
3547
3548     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3549         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3550     } else {
3551         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3552     }
3553
3554     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3555         /* reset the watchdog timer if there are pending transmits */
3556         fp->watchdog_timer = BXE_TX_TIMEOUT;
3557         return (TRUE);
3558     } else {
3559         /* clear watchdog when there are no pending transmits */
3560         fp->watchdog_timer = 0;
3561         return (FALSE);
3562     }
3563 }
3564
3565 static void
3566 bxe_drain_tx_queues(struct bxe_softc *sc)
3567 {
3568     struct bxe_fastpath *fp;
3569     int i, count;
3570
3571     /* wait until all TX fastpath tasks have completed */
3572     for (i = 0; i < sc->num_queues; i++) {
3573         fp = &sc->fp[i];
3574
3575         count = 1000;
3576
3577         while (bxe_has_tx_work(fp)) {
3578
3579             BXE_FP_TX_LOCK(fp);
3580             bxe_txeof(sc, fp);
3581             BXE_FP_TX_UNLOCK(fp);
3582
3583             if (count == 0) {
3584                 BLOGE(sc, "Timeout waiting for fp[%d] "
3585                           "transmits to complete!\n", i);
3586                 bxe_panic(sc, ("tx drain failure\n"));
3587                 return;
3588             }
3589
3590             count--;
3591             DELAY(1000);
3592             rmb();
3593         }
3594     }
3595
3596     return;
3597 }
3598
3599 static int
3600 bxe_del_all_macs(struct bxe_softc          *sc,
3601                  struct ecore_vlan_mac_obj *mac_obj,
3602                  int                       mac_type,
3603                  uint8_t                   wait_for_comp)
3604 {
3605     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3606     int rc;
3607
3608     /* wait for completion of requested */
3609     if (wait_for_comp) {
3610         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3611     }
3612
3613     /* Set the mac type of addresses we want to clear */
3614     bxe_set_bit(mac_type, &vlan_mac_flags);
3615
3616     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3617     if (rc < 0) {
3618         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3619             rc, mac_type, wait_for_comp);
3620     }
3621
3622     return (rc);
3623 }
3624
3625 static int
3626 bxe_fill_accept_flags(struct bxe_softc *sc,
3627                       uint32_t         rx_mode,
3628                       unsigned long    *rx_accept_flags,
3629                       unsigned long    *tx_accept_flags)
3630 {
3631     /* Clear the flags first */
3632     *rx_accept_flags = 0;
3633     *tx_accept_flags = 0;
3634
3635     switch (rx_mode) {
3636     case BXE_RX_MODE_NONE:
3637         /*
3638          * 'drop all' supersedes any accept flags that may have been
3639          * passed to the function.
3640          */
3641         break;
3642
3643     case BXE_RX_MODE_NORMAL:
3644         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3645         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3646         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3647
3648         /* internal switching mode */
3649         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3650         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3651         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3652
3653         break;
3654
3655     case BXE_RX_MODE_ALLMULTI:
3656         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3657         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3658         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3659
3660         /* internal switching mode */
3661         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3662         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3663         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3664
3665         break;
3666
3667     case BXE_RX_MODE_PROMISC:
3668         /*
3669          * According to deffinition of SI mode, iface in promisc mode
3670          * should receive matched and unmatched (in resolution of port)
3671          * unicast packets.
3672          */
3673         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3674         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3675         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3676         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3677
3678         /* internal switching mode */
3679         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3680         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3681
3682         if (IS_MF_SI(sc)) {
3683             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3684         } else {
3685             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3686         }
3687
3688         break;
3689
3690     default:
3691         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3692         return (-1);
3693     }
3694
3695     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3696     if (rx_mode != BXE_RX_MODE_NONE) {
3697         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3698         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3699     }
3700
3701     return (0);
3702 }
3703
3704 static int
3705 bxe_set_q_rx_mode(struct bxe_softc *sc,
3706                   uint8_t          cl_id,
3707                   unsigned long    rx_mode_flags,
3708                   unsigned long    rx_accept_flags,
3709                   unsigned long    tx_accept_flags,
3710                   unsigned long    ramrod_flags)
3711 {
3712     struct ecore_rx_mode_ramrod_params ramrod_param;
3713     int rc;
3714
3715     memset(&ramrod_param, 0, sizeof(ramrod_param));
3716
3717     /* Prepare ramrod parameters */
3718     ramrod_param.cid = 0;
3719     ramrod_param.cl_id = cl_id;
3720     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3721     ramrod_param.func_id = SC_FUNC(sc);
3722
3723     ramrod_param.pstate = &sc->sp_state;
3724     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3725
3726     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3727     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3728
3729     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3730
3731     ramrod_param.ramrod_flags = ramrod_flags;
3732     ramrod_param.rx_mode_flags = rx_mode_flags;
3733
3734     ramrod_param.rx_accept_flags = rx_accept_flags;
3735     ramrod_param.tx_accept_flags = tx_accept_flags;
3736
3737     rc = ecore_config_rx_mode(sc, &ramrod_param);
3738     if (rc < 0) {
3739         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3740             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3741             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3742             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3743             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3744         return (rc);
3745     }
3746
3747     return (0);
3748 }
3749
3750 static int
3751 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3752 {
3753     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3754     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3755     int rc;
3756
3757     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3758                                &tx_accept_flags);
3759     if (rc) {
3760         return (rc);
3761     }
3762
3763     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3764     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3765
3766     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3767     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3768                               rx_accept_flags, tx_accept_flags,
3769                               ramrod_flags));
3770 }
3771
3772 /* returns the "mcp load_code" according to global load_count array */
3773 static int
3774 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3775 {
3776     int path = SC_PATH(sc);
3777     int port = SC_PORT(sc);
3778
3779     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3780           path, load_count[path][0], load_count[path][1],
3781           load_count[path][2]);
3782     load_count[path][0]++;
3783     load_count[path][1 + port]++;
3784     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3785           path, load_count[path][0], load_count[path][1],
3786           load_count[path][2]);
3787     if (load_count[path][0] == 1) {
3788         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3789     } else if (load_count[path][1 + port] == 1) {
3790         return (FW_MSG_CODE_DRV_LOAD_PORT);
3791     } else {
3792         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3793     }
3794 }
3795
3796 /* returns the "mcp load_code" according to global load_count array */
3797 static int
3798 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3799 {
3800     int port = SC_PORT(sc);
3801     int path = SC_PATH(sc);
3802
3803     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3804           path, load_count[path][0], load_count[path][1],
3805           load_count[path][2]);
3806     load_count[path][0]--;
3807     load_count[path][1 + port]--;
3808     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3809           path, load_count[path][0], load_count[path][1],
3810           load_count[path][2]);
3811     if (load_count[path][0] == 0) {
3812         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3813     } else if (load_count[path][1 + port] == 0) {
3814         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3815     } else {
3816         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3817     }
3818 }
3819
3820 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3821 static uint32_t
3822 bxe_send_unload_req(struct bxe_softc *sc,
3823                     int              unload_mode)
3824 {
3825     uint32_t reset_code = 0;
3826
3827     /* Select the UNLOAD request mode */
3828     if (unload_mode == UNLOAD_NORMAL) {
3829         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3830     } else {
3831         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3832     }
3833
3834     /* Send the request to the MCP */
3835     if (!BXE_NOMCP(sc)) {
3836         reset_code = bxe_fw_command(sc, reset_code, 0);
3837     } else {
3838         reset_code = bxe_nic_unload_no_mcp(sc);
3839     }
3840
3841     return (reset_code);
3842 }
3843
3844 /* send UNLOAD_DONE command to the MCP */
3845 static void
3846 bxe_send_unload_done(struct bxe_softc *sc,
3847                      uint8_t          keep_link)
3848 {
3849     uint32_t reset_param =
3850         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3851
3852     /* Report UNLOAD_DONE to MCP */
3853     if (!BXE_NOMCP(sc)) {
3854         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3855     }
3856 }
3857
3858 static int
3859 bxe_func_wait_started(struct bxe_softc *sc)
3860 {
3861     int tout = 50;
3862
3863     if (!sc->port.pmf) {
3864         return (0);
3865     }
3866
3867     /*
3868      * (assumption: No Attention from MCP at this stage)
3869      * PMF probably in the middle of TX disable/enable transaction
3870      * 1. Sync IRS for default SB
3871      * 2. Sync SP queue - this guarantees us that attention handling started
3872      * 3. Wait, that TX disable/enable transaction completes
3873      *
3874      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3875      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3876      * received completion for the transaction the state is TX_STOPPED.
3877      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3878      * transaction.
3879      */
3880
3881     /* XXX make sure default SB ISR is done */
3882     /* need a way to synchronize an irq (intr_mtx?) */
3883
3884     /* XXX flush any work queues */
3885
3886     while (ecore_func_get_state(sc, &sc->func_obj) !=
3887            ECORE_F_STATE_STARTED && tout--) {
3888         DELAY(20000);
3889     }
3890
3891     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3892         /*
3893          * Failed to complete the transaction in a "good way"
3894          * Force both transactions with CLR bit.
3895          */
3896         struct ecore_func_state_params func_params = { NULL };
3897
3898         BLOGE(sc, "Unexpected function state! "
3899                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3900
3901         func_params.f_obj = &sc->func_obj;
3902         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3903
3904         /* STARTED-->TX_STOPPED */
3905         func_params.cmd = ECORE_F_CMD_TX_STOP;
3906         ecore_func_state_change(sc, &func_params);
3907
3908         /* TX_STOPPED-->STARTED */
3909         func_params.cmd = ECORE_F_CMD_TX_START;
3910         return (ecore_func_state_change(sc, &func_params));
3911     }
3912
3913     return (0);
3914 }
3915
3916 static int
3917 bxe_stop_queue(struct bxe_softc *sc,
3918                int              index)
3919 {
3920     struct bxe_fastpath *fp = &sc->fp[index];
3921     struct ecore_queue_state_params q_params = { NULL };
3922     int rc;
3923
3924     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3925
3926     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3927     /* We want to wait for completion in this context */
3928     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3929
3930     /* Stop the primary connection: */
3931
3932     /* ...halt the connection */
3933     q_params.cmd = ECORE_Q_CMD_HALT;
3934     rc = ecore_queue_state_change(sc, &q_params);
3935     if (rc) {
3936         return (rc);
3937     }
3938
3939     /* ...terminate the connection */
3940     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3941     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3942     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3943     rc = ecore_queue_state_change(sc, &q_params);
3944     if (rc) {
3945         return (rc);
3946     }
3947
3948     /* ...delete cfc entry */
3949     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3950     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3951     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3952     return (ecore_queue_state_change(sc, &q_params));
3953 }
3954
3955 /* wait for the outstanding SP commands */
3956 static inline uint8_t
3957 bxe_wait_sp_comp(struct bxe_softc *sc,
3958                  unsigned long    mask)
3959 {
3960     unsigned long tmp;
3961     int tout = 5000; /* wait for 5 secs tops */
3962
3963     while (tout--) {
3964         mb();
3965         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3966             return (TRUE);
3967         }
3968
3969         DELAY(1000);
3970     }
3971
3972     mb();
3973
3974     tmp = atomic_load_acq_long(&sc->sp_state);
3975     if (tmp & mask) {
3976         BLOGE(sc, "Filtering completion timed out: "
3977                   "sp_state 0x%lx, mask 0x%lx\n",
3978               tmp, mask);
3979         return (FALSE);
3980     }
3981
3982     return (FALSE);
3983 }
3984
3985 static int
3986 bxe_func_stop(struct bxe_softc *sc)
3987 {
3988     struct ecore_func_state_params func_params = { NULL };
3989     int rc;
3990
3991     /* prepare parameters for function state transitions */
3992     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3993     func_params.f_obj = &sc->func_obj;
3994     func_params.cmd = ECORE_F_CMD_STOP;
3995
3996     /*
3997      * Try to stop the function the 'good way'. If it fails (in case
3998      * of a parity error during bxe_chip_cleanup()) and we are
3999      * not in a debug mode, perform a state transaction in order to
4000      * enable further HW_RESET transaction.
4001      */
4002     rc = ecore_func_state_change(sc, &func_params);
4003     if (rc) {
4004         BLOGE(sc, "FUNC_STOP ramrod failed. "
4005                   "Running a dry transaction (%d)\n", rc);
4006         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
4007         return (ecore_func_state_change(sc, &func_params));
4008     }
4009
4010     return (0);
4011 }
4012
4013 static int
4014 bxe_reset_hw(struct bxe_softc *sc,
4015              uint32_t         load_code)
4016 {
4017     struct ecore_func_state_params func_params = { NULL };
4018
4019     /* Prepare parameters for function state transitions */
4020     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4021
4022     func_params.f_obj = &sc->func_obj;
4023     func_params.cmd = ECORE_F_CMD_HW_RESET;
4024
4025     func_params.params.hw_init.load_phase = load_code;
4026
4027     return (ecore_func_state_change(sc, &func_params));
4028 }
4029
4030 static void
4031 bxe_int_disable_sync(struct bxe_softc *sc,
4032                      int              disable_hw)
4033 {
4034     if (disable_hw) {
4035         /* prevent the HW from sending interrupts */
4036         bxe_int_disable(sc);
4037     }
4038
4039     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4040     /* make sure all ISRs are done */
4041
4042     /* XXX make sure sp_task is not running */
4043     /* cancel and flush work queues */
4044 }
4045
4046 static void
4047 bxe_chip_cleanup(struct bxe_softc *sc,
4048                  uint32_t         unload_mode,
4049                  uint8_t          keep_link)
4050 {
4051     int port = SC_PORT(sc);
4052     struct ecore_mcast_ramrod_params rparam = { NULL };
4053     uint32_t reset_code;
4054     int i, rc = 0;
4055
4056     bxe_drain_tx_queues(sc);
4057
4058     /* give HW time to discard old tx messages */
4059     DELAY(1000);
4060
4061     /* Clean all ETH MACs */
4062     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4063     if (rc < 0) {
4064         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4065     }
4066
4067     /* Clean up UC list  */
4068     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4069     if (rc < 0) {
4070         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4071     }
4072
4073     /* Disable LLH */
4074     if (!CHIP_IS_E1(sc)) {
4075         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4076     }
4077
4078     /* Set "drop all" to stop Rx */
4079
4080     /*
4081      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4082      * a race between the completion code and this code.
4083      */
4084     BXE_MCAST_LOCK(sc);
4085
4086     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4087         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4088     } else {
4089         bxe_set_storm_rx_mode(sc);
4090     }
4091
4092     /* Clean up multicast configuration */
4093     rparam.mcast_obj = &sc->mcast_obj;
4094     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4095     if (rc < 0) {
4096         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4097     }
4098
4099     BXE_MCAST_UNLOCK(sc);
4100
4101     // XXX bxe_iov_chip_cleanup(sc);
4102
4103     /*
4104      * Send the UNLOAD_REQUEST to the MCP. This will return if
4105      * this function should perform FUNCTION, PORT, or COMMON HW
4106      * reset.
4107      */
4108     reset_code = bxe_send_unload_req(sc, unload_mode);
4109
4110     /*
4111      * (assumption: No Attention from MCP at this stage)
4112      * PMF probably in the middle of TX disable/enable transaction
4113      */
4114     rc = bxe_func_wait_started(sc);
4115     if (rc) {
4116         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4117     }
4118
4119     /*
4120      * Close multi and leading connections
4121      * Completions for ramrods are collected in a synchronous way
4122      */
4123     for (i = 0; i < sc->num_queues; i++) {
4124         if (bxe_stop_queue(sc, i)) {
4125             goto unload_error;
4126         }
4127     }
4128
4129     /*
4130      * If SP settings didn't get completed so far - something
4131      * very wrong has happen.
4132      */
4133     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4134         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4135     }
4136
4137 unload_error:
4138
4139     rc = bxe_func_stop(sc);
4140     if (rc) {
4141         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4142     }
4143
4144     /* disable HW interrupts */
4145     bxe_int_disable_sync(sc, TRUE);
4146
4147     /* detach interrupts */
4148     bxe_interrupt_detach(sc);
4149
4150     /* Reset the chip */
4151     rc = bxe_reset_hw(sc, reset_code);
4152     if (rc) {
4153         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4154     }
4155
4156     /* Report UNLOAD_DONE to MCP */
4157     bxe_send_unload_done(sc, keep_link);
4158 }
4159
4160 static void
4161 bxe_disable_close_the_gate(struct bxe_softc *sc)
4162 {
4163     uint32_t val;
4164     int port = SC_PORT(sc);
4165
4166     BLOGD(sc, DBG_LOAD,
4167           "Disabling 'close the gates'\n");
4168
4169     if (CHIP_IS_E1(sc)) {
4170         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4171                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4172         val = REG_RD(sc, addr);
4173         val &= ~(0x300);
4174         REG_WR(sc, addr, val);
4175     } else {
4176         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4177         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4178                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4179         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4180     }
4181 }
4182
4183 /*
4184  * Cleans the object that have internal lists without sending
4185  * ramrods. Should be run when interrutps are disabled.
4186  */
4187 static void
4188 bxe_squeeze_objects(struct bxe_softc *sc)
4189 {
4190     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4191     struct ecore_mcast_ramrod_params rparam = { NULL };
4192     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4193     int rc;
4194
4195     /* Cleanup MACs' object first... */
4196
4197     /* Wait for completion of requested */
4198     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4199     /* Perform a dry cleanup */
4200     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4201
4202     /* Clean ETH primary MAC */
4203     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4204     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4205                              &ramrod_flags);
4206     if (rc != 0) {
4207         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4208     }
4209
4210     /* Cleanup UC list */
4211     vlan_mac_flags = 0;
4212     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4213     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4214                              &ramrod_flags);
4215     if (rc != 0) {
4216         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4217     }
4218
4219     /* Now clean mcast object... */
4220
4221     rparam.mcast_obj = &sc->mcast_obj;
4222     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4223
4224     /* Add a DEL command... */
4225     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4226     if (rc < 0) {
4227         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4228     }
4229
4230     /* now wait until all pending commands are cleared */
4231
4232     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4233     while (rc != 0) {
4234         if (rc < 0) {
4235             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4236             return;
4237         }
4238
4239         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4240     }
4241 }
4242
4243 /* stop the controller */
4244 static __noinline int
4245 bxe_nic_unload(struct bxe_softc *sc,
4246                uint32_t         unload_mode,
4247                uint8_t          keep_link)
4248 {
4249     uint8_t global = FALSE;
4250     uint32_t val;
4251     int i;
4252
4253     BXE_CORE_LOCK_ASSERT(sc);
4254
4255     sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
4256
4257     for (i = 0; i < sc->num_queues; i++) {
4258         struct bxe_fastpath *fp;
4259
4260         fp = &sc->fp[i];
4261         BXE_FP_TX_LOCK(fp);
4262         BXE_FP_TX_UNLOCK(fp);
4263     }
4264
4265     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4266
4267     /* mark driver as unloaded in shmem2 */
4268     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4269         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4270         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4271                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4272     }
4273
4274     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4275         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4276         /*
4277          * We can get here if the driver has been unloaded
4278          * during parity error recovery and is either waiting for a
4279          * leader to complete or for other functions to unload and
4280          * then ifconfig down has been issued. In this case we want to
4281          * unload and let other functions to complete a recovery
4282          * process.
4283          */
4284         sc->recovery_state = BXE_RECOVERY_DONE;
4285         sc->is_leader = 0;
4286         bxe_release_leader_lock(sc);
4287         mb();
4288
4289         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4290         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4291             " state = 0x%x\n", sc->recovery_state, sc->state);
4292         return (-1);
4293     }
4294
4295     /*
4296      * Nothing to do during unload if previous bxe_nic_load()
4297      * did not completed succesfully - all resourses are released.
4298      */
4299     if ((sc->state == BXE_STATE_CLOSED) ||
4300         (sc->state == BXE_STATE_ERROR)) {
4301         return (0);
4302     }
4303
4304     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4305     mb();
4306
4307     /* stop tx */
4308     bxe_tx_disable(sc);
4309
4310     sc->rx_mode = BXE_RX_MODE_NONE;
4311     /* XXX set rx mode ??? */
4312
4313     if (IS_PF(sc) && !sc->grcdump_done) {
4314         /* set ALWAYS_ALIVE bit in shmem */
4315         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4316
4317         bxe_drv_pulse(sc);
4318
4319         bxe_stats_handle(sc, STATS_EVENT_STOP);
4320         bxe_save_statistics(sc);
4321     }
4322
4323     /* wait till consumers catch up with producers in all queues */
4324     bxe_drain_tx_queues(sc);
4325
4326     /* if VF indicate to PF this function is going down (PF will delete sp
4327      * elements and clear initializations
4328      */
4329     if (IS_VF(sc)) {
4330         ; /* bxe_vfpf_close_vf(sc); */
4331     } else if (unload_mode != UNLOAD_RECOVERY) {
4332         /* if this is a normal/close unload need to clean up chip */
4333         if (!sc->grcdump_done)
4334             bxe_chip_cleanup(sc, unload_mode, keep_link);
4335     } else {
4336         /* Send the UNLOAD_REQUEST to the MCP */
4337         bxe_send_unload_req(sc, unload_mode);
4338
4339         /*
4340          * Prevent transactions to host from the functions on the
4341          * engine that doesn't reset global blocks in case of global
4342          * attention once gloabl blocks are reset and gates are opened
4343          * (the engine which leader will perform the recovery
4344          * last).
4345          */
4346         if (!CHIP_IS_E1x(sc)) {
4347             bxe_pf_disable(sc);
4348         }
4349
4350         /* disable HW interrupts */
4351         bxe_int_disable_sync(sc, TRUE);
4352
4353         /* detach interrupts */
4354         bxe_interrupt_detach(sc);
4355
4356         /* Report UNLOAD_DONE to MCP */
4357         bxe_send_unload_done(sc, FALSE);
4358     }
4359
4360     /*
4361      * At this stage no more interrupts will arrive so we may safely clean
4362      * the queue'able objects here in case they failed to get cleaned so far.
4363      */
4364     if (IS_PF(sc)) {
4365         bxe_squeeze_objects(sc);
4366     }
4367
4368     /* There should be no more pending SP commands at this stage */
4369     sc->sp_state = 0;
4370
4371     sc->port.pmf = 0;
4372
4373     bxe_free_fp_buffers(sc);
4374
4375     if (IS_PF(sc)) {
4376         bxe_free_mem(sc);
4377     }
4378
4379     bxe_free_fw_stats_mem(sc);
4380
4381     sc->state = BXE_STATE_CLOSED;
4382
4383     /*
4384      * Check if there are pending parity attentions. If there are - set
4385      * RECOVERY_IN_PROGRESS.
4386      */
4387     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4388         bxe_set_reset_in_progress(sc);
4389
4390         /* Set RESET_IS_GLOBAL if needed */
4391         if (global) {
4392             bxe_set_reset_global(sc);
4393         }
4394     }
4395
4396     /*
4397      * The last driver must disable a "close the gate" if there is no
4398      * parity attention or "process kill" pending.
4399      */
4400     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4401         bxe_reset_is_done(sc, SC_PATH(sc))) {
4402         bxe_disable_close_the_gate(sc);
4403     }
4404
4405     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4406
4407     return (0);
4408 }
4409
4410 /*
4411  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4412  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4413  */
4414 static int
4415 bxe_ifmedia_update(struct ifnet *ifp)
4416 {
4417     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4418     struct ifmedia *ifm;
4419
4420     ifm = &sc->ifmedia;
4421
4422     /* We only support Ethernet media type. */
4423     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4424         return (EINVAL);
4425     }
4426
4427     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4428     case IFM_AUTO:
4429          break;
4430     case IFM_10G_CX4:
4431     case IFM_10G_SR:
4432     case IFM_10G_T:
4433     case IFM_10G_TWINAX:
4434     default:
4435         /* We don't support changing the media type. */
4436         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4437               IFM_SUBTYPE(ifm->ifm_media));
4438         return (EINVAL);
4439     }
4440
4441     return (0);
4442 }
4443
4444 /*
4445  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4446  */
4447 static void
4448 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4449 {
4450     struct bxe_softc *sc = ifp->if_softc;
4451
4452     /* Report link down if the driver isn't running. */
4453     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4454         ifmr->ifm_active |= IFM_NONE;
4455         return;
4456     }
4457
4458     /* Setup the default interface info. */
4459     ifmr->ifm_status = IFM_AVALID;
4460     ifmr->ifm_active = IFM_ETHER;
4461
4462     if (sc->link_vars.link_up) {
4463         ifmr->ifm_status |= IFM_ACTIVE;
4464     } else {
4465         ifmr->ifm_active |= IFM_NONE;
4466         return;
4467     }
4468
4469     ifmr->ifm_active |= sc->media;
4470
4471     if (sc->link_vars.duplex == DUPLEX_FULL) {
4472         ifmr->ifm_active |= IFM_FDX;
4473     } else {
4474         ifmr->ifm_active |= IFM_HDX;
4475     }
4476 }
4477
4478 static void
4479 bxe_handle_chip_tq(void *context,
4480                    int  pending)
4481 {
4482     struct bxe_softc *sc = (struct bxe_softc *)context;
4483     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4484
4485     switch (work)
4486     {
4487     case CHIP_TQ_REINIT:
4488         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4489             /* restart the interface */
4490             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4491             bxe_periodic_stop(sc);
4492             BXE_CORE_LOCK(sc);
4493             bxe_stop_locked(sc);
4494             bxe_init_locked(sc);
4495             BXE_CORE_UNLOCK(sc);
4496         }
4497         break;
4498
4499     default:
4500         break;
4501     }
4502 }
4503
4504 /*
4505  * Handles any IOCTL calls from the operating system.
4506  *
4507  * Returns:
4508  *   0 = Success, >0 Failure
4509  */
4510 static int
4511 bxe_ioctl(struct ifnet *ifp,
4512           u_long       command,
4513           caddr_t      data)
4514 {
4515     struct bxe_softc *sc = ifp->if_softc;
4516     struct ifreq *ifr = (struct ifreq *)data;
4517     int mask = 0;
4518     int reinit = 0;
4519     int error = 0;
4520
4521     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4522     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4523
4524     switch (command)
4525     {
4526     case SIOCSIFMTU:
4527         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4528               ifr->ifr_mtu);
4529
4530         if (sc->mtu == ifr->ifr_mtu) {
4531             /* nothing to change */
4532             break;
4533         }
4534
4535         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4536             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4537                   ifr->ifr_mtu, mtu_min, mtu_max);
4538             error = EINVAL;
4539             break;
4540         }
4541
4542         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4543                              (unsigned long)ifr->ifr_mtu);
4544         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4545                               (unsigned long)ifr->ifr_mtu);
4546
4547         reinit = 1;
4548         break;
4549
4550     case SIOCSIFFLAGS:
4551         /* toggle the interface state up or down */
4552         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4553
4554         BXE_CORE_LOCK(sc);
4555         /* check if the interface is up */
4556         if (ifp->if_flags & IFF_UP) {
4557             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4558                 /* set the receive mode flags */
4559                 bxe_set_rx_mode(sc);
4560             } else if(sc->state != BXE_STATE_DISABLED) {
4561                 bxe_init_locked(sc);
4562             }
4563         } else {
4564             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4565                 bxe_periodic_stop(sc);
4566                 bxe_stop_locked(sc);
4567             }
4568         }
4569         BXE_CORE_UNLOCK(sc);
4570
4571         break;
4572
4573     case SIOCADDMULTI:
4574     case SIOCDELMULTI:
4575         /* add/delete multicast addresses */
4576         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4577
4578         /* check if the interface is up */
4579         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4580             /* set the receive mode flags */
4581             BXE_CORE_LOCK(sc);
4582             bxe_set_rx_mode(sc);
4583             BXE_CORE_UNLOCK(sc); 
4584         }
4585
4586         break;
4587
4588     case SIOCSIFCAP:
4589         /* find out which capabilities have changed */
4590         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4591
4592         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4593               mask);
4594
4595         /* toggle the LRO capabilites enable flag */
4596         if (mask & IFCAP_LRO) {
4597             ifp->if_capenable ^= IFCAP_LRO;
4598             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4599                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4600             reinit = 1;
4601         }
4602
4603         /* toggle the TXCSUM checksum capabilites enable flag */
4604         if (mask & IFCAP_TXCSUM) {
4605             ifp->if_capenable ^= IFCAP_TXCSUM;
4606             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4607                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4608             if (ifp->if_capenable & IFCAP_TXCSUM) {
4609                 ifp->if_hwassist = (CSUM_IP       |
4610                                     CSUM_TCP      |
4611                                     CSUM_UDP      |
4612                                     CSUM_TSO      |
4613                                     CSUM_TCP_IPV6 |
4614                                     CSUM_UDP_IPV6);
4615             } else {
4616                 ifp->if_hwassist = 0;
4617             }
4618         }
4619
4620         /* toggle the RXCSUM checksum capabilities enable flag */
4621         if (mask & IFCAP_RXCSUM) {
4622             ifp->if_capenable ^= IFCAP_RXCSUM;
4623             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4624                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4625             if (ifp->if_capenable & IFCAP_RXCSUM) {
4626                 ifp->if_hwassist = (CSUM_IP       |
4627                                     CSUM_TCP      |
4628                                     CSUM_UDP      |
4629                                     CSUM_TSO      |
4630                                     CSUM_TCP_IPV6 |
4631                                     CSUM_UDP_IPV6);
4632             } else {
4633                 ifp->if_hwassist = 0;
4634             }
4635         }
4636
4637         /* toggle TSO4 capabilities enabled flag */
4638         if (mask & IFCAP_TSO4) {
4639             ifp->if_capenable ^= IFCAP_TSO4;
4640             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4641                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4642         }
4643
4644         /* toggle TSO6 capabilities enabled flag */
4645         if (mask & IFCAP_TSO6) {
4646             ifp->if_capenable ^= IFCAP_TSO6;
4647             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4648                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4649         }
4650
4651         /* toggle VLAN_HWTSO capabilities enabled flag */
4652         if (mask & IFCAP_VLAN_HWTSO) {
4653             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4654             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4655                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4656         }
4657
4658         /* toggle VLAN_HWCSUM capabilities enabled flag */
4659         if (mask & IFCAP_VLAN_HWCSUM) {
4660             /* XXX investigate this... */
4661             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4662             error = EINVAL;
4663         }
4664
4665         /* toggle VLAN_MTU capabilities enable flag */
4666         if (mask & IFCAP_VLAN_MTU) {
4667             /* XXX investigate this... */
4668             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4669             error = EINVAL;
4670         }
4671
4672         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4673         if (mask & IFCAP_VLAN_HWTAGGING) {
4674             /* XXX investigate this... */
4675             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4676             error = EINVAL;
4677         }
4678
4679         /* toggle VLAN_HWFILTER capabilities enabled flag */
4680         if (mask & IFCAP_VLAN_HWFILTER) {
4681             /* XXX investigate this... */
4682             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4683             error = EINVAL;
4684         }
4685
4686         /* XXX not yet...
4687          * IFCAP_WOL_MAGIC
4688          */
4689
4690         break;
4691
4692     case SIOCSIFMEDIA:
4693     case SIOCGIFMEDIA:
4694         /* set/get interface media */
4695         BLOGD(sc, DBG_IOCTL,
4696               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4697               (command & 0xff));
4698         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4699         break;
4700
4701     default:
4702         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4703               (command & 0xff));
4704         error = ether_ioctl(ifp, command, data);
4705         break;
4706     }
4707
4708     if (reinit && (ifp->if_drv_flags & IFF_DRV_RUNNING)) {
4709         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4710               "Re-initializing hardware from IOCTL change\n");
4711         bxe_periodic_stop(sc);
4712         BXE_CORE_LOCK(sc);
4713         bxe_stop_locked(sc);
4714         bxe_init_locked(sc);
4715         BXE_CORE_UNLOCK(sc);
4716     }
4717
4718     return (error);
4719 }
4720
4721 static __noinline void
4722 bxe_dump_mbuf(struct bxe_softc *sc,
4723               struct mbuf      *m,
4724               uint8_t          contents)
4725 {
4726     char * type;
4727     int i = 0;
4728
4729     if (!(sc->debug & DBG_MBUF)) {
4730         return;
4731     }
4732
4733     if (m == NULL) {
4734         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4735         return;
4736     }
4737
4738     while (m) {
4739
4740 #if __FreeBSD_version >= 1000000
4741         BLOGD(sc, DBG_MBUF,
4742               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4743               i, m, m->m_len, m->m_flags, M_FLAG_BITS, m->m_data);
4744
4745         if (m->m_flags & M_PKTHDR) {
4746              BLOGD(sc, DBG_MBUF,
4747                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4748                    i, m->m_pkthdr.len, m->m_flags, M_FLAG_BITS,
4749                    (int)m->m_pkthdr.csum_flags, CSUM_BITS);
4750         }
4751 #else
4752         BLOGD(sc, DBG_MBUF,
4753               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4754               i, m, m->m_len, m->m_flags,
4755               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4756
4757         if (m->m_flags & M_PKTHDR) {
4758              BLOGD(sc, DBG_MBUF,
4759                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4760                    i, m->m_pkthdr.len, m->m_flags,
4761                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4762                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4763                    "\22M_PROMISC\23M_NOFREE",
4764                    (int)m->m_pkthdr.csum_flags,
4765                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4766                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4767                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4768                    "\14CSUM_PSEUDO_HDR");
4769         }
4770 #endif /* #if __FreeBSD_version >= 1000000 */
4771
4772         if (m->m_flags & M_EXT) {
4773             switch (m->m_ext.ext_type) {
4774             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4775             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4776             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4777             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4778             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4779             case EXT_PACKET:     type = "EXT_PACKET";     break;
4780             case EXT_MBUF:       type = "EXT_MBUF";       break;
4781             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4782             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4783             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4784             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4785             default:             type = "UNKNOWN";        break;
4786             }
4787
4788             BLOGD(sc, DBG_MBUF,
4789                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4790                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4791         }
4792
4793         if (contents) {
4794             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4795         }
4796
4797         m = m->m_next;
4798         i++;
4799     }
4800 }
4801
4802 /*
4803  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4804  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4805  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4806  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4807  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4808  */
4809 static int
4810 bxe_chktso_window(struct bxe_softc  *sc,
4811                   int               nsegs,
4812                   bus_dma_segment_t *segs,
4813                   struct mbuf       *m)
4814 {
4815     uint32_t num_wnds, wnd_size, wnd_sum;
4816     int32_t frag_idx, wnd_idx;
4817     unsigned short lso_mss;
4818     int defrag;
4819
4820     defrag = 0;
4821     wnd_sum = 0;
4822     wnd_size = 10;
4823     num_wnds = nsegs - wnd_size;
4824     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4825
4826     /*
4827      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4828      * first window sum of data while skipping the first assuming it is the
4829      * header in FreeBSD.
4830      */
4831     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4832         wnd_sum += htole16(segs[frag_idx].ds_len);
4833     }
4834
4835     /* check the first 10 bd window size */
4836     if (wnd_sum < lso_mss) {
4837         return (1);
4838     }
4839
4840     /* run through the windows */
4841     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4842         /* subtract the first mbuf->m_len of the last wndw(-header) */
4843         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4844         /* add the next mbuf len to the len of our new window */
4845         wnd_sum += htole16(segs[frag_idx].ds_len);
4846         if (wnd_sum < lso_mss) {
4847             return (1);
4848         }
4849     }
4850
4851     return (0);
4852 }
4853
4854 static uint8_t
4855 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4856                     struct mbuf         *m,
4857                     uint32_t            *parsing_data)
4858 {
4859     struct ether_vlan_header *eh = NULL;
4860     struct ip *ip4 = NULL;
4861     struct ip6_hdr *ip6 = NULL;
4862     caddr_t ip = NULL;
4863     struct tcphdr *th = NULL;
4864     int e_hlen, ip_hlen, l4_off;
4865     uint16_t proto;
4866
4867     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4868         /* no L4 checksum offload needed */
4869         return (0);
4870     }
4871
4872     /* get the Ethernet header */
4873     eh = mtod(m, struct ether_vlan_header *);
4874
4875     /* handle VLAN encapsulation if present */
4876     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4877         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4878         proto  = ntohs(eh->evl_proto);
4879     } else {
4880         e_hlen = ETHER_HDR_LEN;
4881         proto  = ntohs(eh->evl_encap_proto);
4882     }
4883
4884     switch (proto) {
4885     case ETHERTYPE_IP:
4886         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4887         ip4 = (m->m_len < sizeof(struct ip)) ?
4888                   (struct ip *)m->m_next->m_data :
4889                   (struct ip *)(m->m_data + e_hlen);
4890         /* ip_hl is number of 32-bit words */
4891         ip_hlen = (ip4->ip_hl << 2);
4892         ip = (caddr_t)ip4;
4893         break;
4894     case ETHERTYPE_IPV6:
4895         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4896         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4897                   (struct ip6_hdr *)m->m_next->m_data :
4898                   (struct ip6_hdr *)(m->m_data + e_hlen);
4899         /* XXX cannot support offload with IPv6 extensions */
4900         ip_hlen = sizeof(struct ip6_hdr);
4901         ip = (caddr_t)ip6;
4902         break;
4903     default:
4904         /* We can't offload in this case... */
4905         /* XXX error stat ??? */
4906         return (0);
4907     }
4908
4909     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4910     l4_off = (e_hlen + ip_hlen);
4911
4912     *parsing_data |=
4913         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4914          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4915
4916     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4917                                   CSUM_TSO |
4918                                   CSUM_TCP_IPV6)) {
4919         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4920         th = (struct tcphdr *)(ip + ip_hlen);
4921         /* th_off is number of 32-bit words */
4922         *parsing_data |= ((th->th_off <<
4923                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4924                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4925         return (l4_off + (th->th_off << 2)); /* entire header length */
4926     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4927                                          CSUM_UDP_IPV6)) {
4928         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4929         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4930     } else {
4931         /* XXX error stat ??? */
4932         return (0);
4933     }
4934 }
4935
4936 static uint8_t
4937 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4938                  struct mbuf                *m,
4939                  struct eth_tx_parse_bd_e1x *pbd)
4940 {
4941     struct ether_vlan_header *eh = NULL;
4942     struct ip *ip4 = NULL;
4943     struct ip6_hdr *ip6 = NULL;
4944     caddr_t ip = NULL;
4945     struct tcphdr *th = NULL;
4946     struct udphdr *uh = NULL;
4947     int e_hlen, ip_hlen;
4948     uint16_t proto;
4949     uint8_t hlen;
4950     uint16_t tmp_csum;
4951     uint32_t *tmp_uh;
4952
4953     /* get the Ethernet header */
4954     eh = mtod(m, struct ether_vlan_header *);
4955
4956     /* handle VLAN encapsulation if present */
4957     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4958         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4959         proto  = ntohs(eh->evl_proto);
4960     } else {
4961         e_hlen = ETHER_HDR_LEN;
4962         proto  = ntohs(eh->evl_encap_proto);
4963     }
4964
4965     switch (proto) {
4966     case ETHERTYPE_IP:
4967         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4968         ip4 = (m->m_len < sizeof(struct ip)) ?
4969                   (struct ip *)m->m_next->m_data :
4970                   (struct ip *)(m->m_data + e_hlen);
4971         /* ip_hl is number of 32-bit words */
4972         ip_hlen = (ip4->ip_hl << 1);
4973         ip = (caddr_t)ip4;
4974         break;
4975     case ETHERTYPE_IPV6:
4976         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4977         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4978                   (struct ip6_hdr *)m->m_next->m_data :
4979                   (struct ip6_hdr *)(m->m_data + e_hlen);
4980         /* XXX cannot support offload with IPv6 extensions */
4981         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4982         ip = (caddr_t)ip6;
4983         break;
4984     default:
4985         /* We can't offload in this case... */
4986         /* XXX error stat ??? */
4987         return (0);
4988     }
4989
4990     hlen = (e_hlen >> 1);
4991
4992     /* note that rest of global_data is indirectly zeroed here */
4993     if (m->m_flags & M_VLANTAG) {
4994         pbd->global_data =
4995             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4996     } else {
4997         pbd->global_data = htole16(hlen);
4998     }
4999
5000     pbd->ip_hlen_w = ip_hlen;
5001
5002     hlen += pbd->ip_hlen_w;
5003
5004     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5005
5006     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5007                                   CSUM_TSO |
5008                                   CSUM_TCP_IPV6)) {
5009         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5010         /* th_off is number of 32-bit words */
5011         hlen += (uint16_t)(th->th_off << 1);
5012     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5013                                          CSUM_UDP_IPV6)) {
5014         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5015         hlen += (sizeof(struct udphdr) / 2);
5016     } else {
5017         /* valid case as only CSUM_IP was set */
5018         return (0);
5019     }
5020
5021     pbd->total_hlen_w = htole16(hlen);
5022
5023     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5024                                   CSUM_TSO |
5025                                   CSUM_TCP_IPV6)) {
5026         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5027         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5028     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5029                                          CSUM_UDP_IPV6)) {
5030         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5031
5032         /*
5033          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5034          * checksums and does not know anything about the UDP header and where
5035          * the checksum field is located. It only knows about TCP. Therefore
5036          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5037          * offload. Since the checksum field offset for TCP is 16 bytes and
5038          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5039          * bytes less than the start of the UDP header. This allows the
5040          * hardware to write the checksum in the correct spot. But the
5041          * hardware will compute a checksum which includes the last 10 bytes
5042          * of the IP header. To correct this we tweak the stack computed
5043          * pseudo checksum by folding in the calculation of the inverse
5044          * checksum for those final 10 bytes of the IP header. This allows
5045          * the correct checksum to be computed by the hardware.
5046          */
5047
5048         /* set pointer 10 bytes before UDP header */
5049         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5050
5051         /* calculate a pseudo header checksum over the first 10 bytes */
5052         tmp_csum = in_pseudo(*tmp_uh,
5053                              *(tmp_uh + 1),
5054                              *(uint16_t *)(tmp_uh + 2));
5055
5056         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5057     }
5058
5059     return (hlen * 2); /* entire header length, number of bytes */
5060 }
5061
5062 static void
5063 bxe_set_pbd_lso_e2(struct mbuf *m,
5064                    uint32_t    *parsing_data)
5065 {
5066     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5067                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5068                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5069
5070     /* XXX test for IPv6 with extension header... */
5071 }
5072
5073 static void
5074 bxe_set_pbd_lso(struct mbuf                *m,
5075                 struct eth_tx_parse_bd_e1x *pbd)
5076 {
5077     struct ether_vlan_header *eh = NULL;
5078     struct ip *ip = NULL;
5079     struct tcphdr *th = NULL;
5080     int e_hlen;
5081
5082     /* get the Ethernet header */
5083     eh = mtod(m, struct ether_vlan_header *);
5084
5085     /* handle VLAN encapsulation if present */
5086     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5087                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5088
5089     /* get the IP and TCP header, with LSO entire header in first mbuf */
5090     /* XXX assuming IPv4 */
5091     ip = (struct ip *)(m->m_data + e_hlen);
5092     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5093
5094     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5095     pbd->tcp_send_seq = ntohl(th->th_seq);
5096     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5097
5098 #if 1
5099         /* XXX IPv4 */
5100         pbd->ip_id = ntohs(ip->ip_id);
5101         pbd->tcp_pseudo_csum =
5102             ntohs(in_pseudo(ip->ip_src.s_addr,
5103                             ip->ip_dst.s_addr,
5104                             htons(IPPROTO_TCP)));
5105 #else
5106         /* XXX IPv6 */
5107         pbd->tcp_pseudo_csum =
5108             ntohs(in_pseudo(&ip6->ip6_src,
5109                             &ip6->ip6_dst,
5110                             htons(IPPROTO_TCP)));
5111 #endif
5112
5113     pbd->global_data |=
5114         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5115 }
5116
5117 /*
5118  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5119  * visible to the controller.
5120  *
5121  * If an mbuf is submitted to this routine and cannot be given to the
5122  * controller (e.g. it has too many fragments) then the function may free
5123  * the mbuf and return to the caller.
5124  *
5125  * Returns:
5126  *   0 = Success, !0 = Failure
5127  *   Note the side effect that an mbuf may be freed if it causes a problem.
5128  */
5129 static int
5130 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5131 {
5132     bus_dma_segment_t segs[32];
5133     struct mbuf *m0;
5134     struct bxe_sw_tx_bd *tx_buf;
5135     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5136     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5137     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5138     struct eth_tx_bd *tx_data_bd;
5139     struct eth_tx_bd *tx_total_pkt_size_bd;
5140     struct eth_tx_start_bd *tx_start_bd;
5141     uint16_t bd_prod, pkt_prod, total_pkt_size;
5142     uint8_t mac_type;
5143     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5144     struct bxe_softc *sc;
5145     uint16_t tx_bd_avail;
5146     struct ether_vlan_header *eh;
5147     uint32_t pbd_e2_parsing_data = 0;
5148     uint8_t hlen = 0;
5149     int tmp_bd;
5150     int i;
5151
5152     sc = fp->sc;
5153
5154 #if __FreeBSD_version >= 800000
5155     M_ASSERTPKTHDR(*m_head);
5156 #endif /* #if __FreeBSD_version >= 800000 */
5157
5158     m0 = *m_head;
5159     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5160     tx_start_bd = NULL;
5161     tx_data_bd = NULL;
5162     tx_total_pkt_size_bd = NULL;
5163
5164     /* get the H/W pointer for packets and BDs */
5165     pkt_prod = fp->tx_pkt_prod;
5166     bd_prod = fp->tx_bd_prod;
5167
5168     mac_type = UNICAST_ADDRESS;
5169
5170     /* map the mbuf into the next open DMAable memory */
5171     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5172     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5173                                     tx_buf->m_map, m0,
5174                                     segs, &nsegs, BUS_DMA_NOWAIT);
5175
5176     /* mapping errors */
5177     if(__predict_false(error != 0)) {
5178         fp->eth_q_stats.tx_dma_mapping_failure++;
5179         if (error == ENOMEM) {
5180             /* resource issue, try again later */
5181             rc = ENOMEM;
5182         } else if (error == EFBIG) {
5183             /* possibly recoverable with defragmentation */
5184             fp->eth_q_stats.mbuf_defrag_attempts++;
5185             m0 = m_defrag(*m_head, M_DONTWAIT);
5186             if (m0 == NULL) {
5187                 fp->eth_q_stats.mbuf_defrag_failures++;
5188                 rc = ENOBUFS;
5189             } else {
5190                 /* defrag successful, try mapping again */
5191                 *m_head = m0;
5192                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5193                                                 tx_buf->m_map, m0,
5194                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5195                 if (error) {
5196                     fp->eth_q_stats.tx_dma_mapping_failure++;
5197                     rc = error;
5198                 }
5199             }
5200         } else {
5201             /* unknown, unrecoverable mapping error */
5202             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5203             bxe_dump_mbuf(sc, m0, FALSE);
5204             rc = error;
5205         }
5206
5207         goto bxe_tx_encap_continue;
5208     }
5209
5210     tx_bd_avail = bxe_tx_avail(sc, fp);
5211
5212     /* make sure there is enough room in the send queue */
5213     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5214         /* Recoverable, try again later. */
5215         fp->eth_q_stats.tx_hw_queue_full++;
5216         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5217         rc = ENOMEM;
5218         goto bxe_tx_encap_continue;
5219     }
5220
5221     /* capture the current H/W TX chain high watermark */
5222     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5223                         (TX_BD_USABLE - tx_bd_avail))) {
5224         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5225     }
5226
5227     /* make sure it fits in the packet window */
5228     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5229         /*
5230          * The mbuf may be to big for the controller to handle. If the frame
5231          * is a TSO frame we'll need to do an additional check.
5232          */
5233         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5234             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5235                 goto bxe_tx_encap_continue; /* OK to send */
5236             } else {
5237                 fp->eth_q_stats.tx_window_violation_tso++;
5238             }
5239         } else {
5240             fp->eth_q_stats.tx_window_violation_std++;
5241         }
5242
5243         /* lets try to defragment this mbuf and remap it */
5244         fp->eth_q_stats.mbuf_defrag_attempts++;
5245         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5246
5247         m0 = m_defrag(*m_head, M_DONTWAIT);
5248         if (m0 == NULL) {
5249             fp->eth_q_stats.mbuf_defrag_failures++;
5250             /* Ugh, just drop the frame... :( */
5251             rc = ENOBUFS;
5252         } else {
5253             /* defrag successful, try mapping again */
5254             *m_head = m0;
5255             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5256                                             tx_buf->m_map, m0,
5257                                             segs, &nsegs, BUS_DMA_NOWAIT);
5258             if (error) {
5259                 fp->eth_q_stats.tx_dma_mapping_failure++;
5260                 /* No sense in trying to defrag/copy chain, drop it. :( */
5261                 rc = error;
5262             } else {
5263                /* if the chain is still too long then drop it */
5264                 if(m0->m_pkthdr.csum_flags & CSUM_TSO) {
5265                     /*
5266                      * in case TSO is enabled nsegs should be checked against
5267                      * BXE_TSO_MAX_SEGMENTS
5268                      */
5269                     if (__predict_false(nsegs > BXE_TSO_MAX_SEGMENTS)) {
5270                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5271                         fp->eth_q_stats.nsegs_path1_errors++;
5272                         rc = ENODEV;
5273                     }
5274                 } else {
5275                     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5276                         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5277                         fp->eth_q_stats.nsegs_path2_errors++;
5278                         rc = ENODEV;
5279                     }
5280                 }
5281             }
5282         }
5283     }
5284
5285 bxe_tx_encap_continue:
5286
5287     /* Check for errors */
5288     if (rc) {
5289         if (rc == ENOMEM) {
5290             /* recoverable try again later  */
5291         } else {
5292             fp->eth_q_stats.tx_soft_errors++;
5293             fp->eth_q_stats.mbuf_alloc_tx--;
5294             m_freem(*m_head);
5295             *m_head = NULL;
5296         }
5297
5298         return (rc);
5299     }
5300
5301     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5302     if (m0->m_flags & M_BCAST) {
5303         mac_type = BROADCAST_ADDRESS;
5304     } else if (m0->m_flags & M_MCAST) {
5305         mac_type = MULTICAST_ADDRESS;
5306     }
5307
5308     /* store the mbuf into the mbuf ring */
5309     tx_buf->m        = m0;
5310     tx_buf->first_bd = fp->tx_bd_prod;
5311     tx_buf->flags    = 0;
5312
5313     /* prepare the first transmit (start) BD for the mbuf */
5314     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5315
5316     BLOGD(sc, DBG_TX,
5317           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5318           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5319
5320     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5321     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5322     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5323     total_pkt_size += tx_start_bd->nbytes;
5324     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5325
5326     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5327
5328     /* all frames have at least Start BD + Parsing BD */
5329     nbds = nsegs + 1;
5330     tx_start_bd->nbd = htole16(nbds);
5331
5332     if (m0->m_flags & M_VLANTAG) {
5333         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5334         tx_start_bd->bd_flags.as_bitfield |=
5335             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5336     } else {
5337         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5338         if (IS_VF(sc)) {
5339             /* map ethernet header to find type and header length */
5340             eh = mtod(m0, struct ether_vlan_header *);
5341             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5342         } else {
5343             /* used by FW for packet accounting */
5344             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5345         }
5346     }
5347
5348     /*
5349      * add a parsing BD from the chain. The parsing BD is always added
5350      * though it is only used for TSO and chksum
5351      */
5352     bd_prod = TX_BD_NEXT(bd_prod);
5353
5354     if (m0->m_pkthdr.csum_flags) {
5355         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5356             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5357             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5358         }
5359
5360         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5361             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5362                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5363         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5364             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5365                                                   ETH_TX_BD_FLAGS_IS_UDP |
5366                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5367         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5368                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5369             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5370         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5371             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5372                                                   ETH_TX_BD_FLAGS_IS_UDP);
5373         }
5374     }
5375
5376     if (!CHIP_IS_E1x(sc)) {
5377         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5378         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5379
5380         if (m0->m_pkthdr.csum_flags) {
5381             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5382         }
5383
5384         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5385                  mac_type);
5386     } else {
5387         uint16_t global_data = 0;
5388
5389         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5390         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5391
5392         if (m0->m_pkthdr.csum_flags) {
5393             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5394         }
5395
5396         SET_FLAG(global_data,
5397                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5398         pbd_e1x->global_data |= htole16(global_data);
5399     }
5400
5401     /* setup the parsing BD with TSO specific info */
5402     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5403         fp->eth_q_stats.tx_ofld_frames_lso++;
5404         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5405
5406         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5407             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5408
5409             /* split the first BD into header/data making the fw job easy */
5410             nbds++;
5411             tx_start_bd->nbd = htole16(nbds);
5412             tx_start_bd->nbytes = htole16(hlen);
5413
5414             bd_prod = TX_BD_NEXT(bd_prod);
5415
5416             /* new transmit BD after the tx_parse_bd */
5417             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5418             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5419             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5420             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5421             if (tx_total_pkt_size_bd == NULL) {
5422                 tx_total_pkt_size_bd = tx_data_bd;
5423             }
5424
5425             BLOGD(sc, DBG_TX,
5426                   "TSO split header size is %d (%x:%x) nbds %d\n",
5427                   le16toh(tx_start_bd->nbytes),
5428                   le32toh(tx_start_bd->addr_hi),
5429                   le32toh(tx_start_bd->addr_lo),
5430                   nbds);
5431         }
5432
5433         if (!CHIP_IS_E1x(sc)) {
5434             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5435         } else {
5436             bxe_set_pbd_lso(m0, pbd_e1x);
5437         }
5438     }
5439
5440     if (pbd_e2_parsing_data) {
5441         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5442     }
5443
5444     /* prepare remaining BDs, start tx bd contains first seg/frag */
5445     for (i = 1; i < nsegs ; i++) {
5446         bd_prod = TX_BD_NEXT(bd_prod);
5447         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5448         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5449         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5450         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5451         if (tx_total_pkt_size_bd == NULL) {
5452             tx_total_pkt_size_bd = tx_data_bd;
5453         }
5454         total_pkt_size += tx_data_bd->nbytes;
5455     }
5456
5457     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5458
5459     if (tx_total_pkt_size_bd != NULL) {
5460         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5461     }
5462
5463     if (__predict_false(sc->debug & DBG_TX)) {
5464         tmp_bd = tx_buf->first_bd;
5465         for (i = 0; i < nbds; i++)
5466         {
5467             if (i == 0) {
5468                 BLOGD(sc, DBG_TX,
5469                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5470                       "bd_flags=0x%x hdr_nbds=%d\n",
5471                       tx_start_bd,
5472                       tmp_bd,
5473                       le16toh(tx_start_bd->nbd),
5474                       le16toh(tx_start_bd->vlan_or_ethertype),
5475                       tx_start_bd->bd_flags.as_bitfield,
5476                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5477             } else if (i == 1) {
5478                 if (pbd_e1x) {
5479                     BLOGD(sc, DBG_TX,
5480                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5481                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5482                           "tcp_seq=%u total_hlen_w=%u\n",
5483                           pbd_e1x,
5484                           tmp_bd,
5485                           pbd_e1x->global_data,
5486                           pbd_e1x->ip_hlen_w,
5487                           pbd_e1x->ip_id,
5488                           pbd_e1x->lso_mss,
5489                           pbd_e1x->tcp_flags,
5490                           pbd_e1x->tcp_pseudo_csum,
5491                           pbd_e1x->tcp_send_seq,
5492                           le16toh(pbd_e1x->total_hlen_w));
5493                 } else { /* if (pbd_e2) */
5494                     BLOGD(sc, DBG_TX,
5495                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5496                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5497                           pbd_e2,
5498                           tmp_bd,
5499                           pbd_e2->data.mac_addr.dst_hi,
5500                           pbd_e2->data.mac_addr.dst_mid,
5501                           pbd_e2->data.mac_addr.dst_lo,
5502                           pbd_e2->data.mac_addr.src_hi,
5503                           pbd_e2->data.mac_addr.src_mid,
5504                           pbd_e2->data.mac_addr.src_lo,
5505                           pbd_e2->parsing_data);
5506                 }
5507             }
5508
5509             if (i != 1) { /* skip parse db as it doesn't hold data */
5510                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5511                 BLOGD(sc, DBG_TX,
5512                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5513                       tx_data_bd,
5514                       tmp_bd,
5515                       le16toh(tx_data_bd->nbytes),
5516                       le32toh(tx_data_bd->addr_hi),
5517                       le32toh(tx_data_bd->addr_lo));
5518             }
5519
5520             tmp_bd = TX_BD_NEXT(tmp_bd);
5521         }
5522     }
5523
5524     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5525
5526     /* update TX BD producer index value for next TX */
5527     bd_prod = TX_BD_NEXT(bd_prod);
5528
5529     /*
5530      * If the chain of tx_bd's describing this frame is adjacent to or spans
5531      * an eth_tx_next_bd element then we need to increment the nbds value.
5532      */
5533     if (TX_BD_IDX(bd_prod) < nbds) {
5534         nbds++;
5535     }
5536
5537     /* don't allow reordering of writes for nbd and packets */
5538     mb();
5539
5540     fp->tx_db.data.prod += nbds;
5541
5542     /* producer points to the next free tx_bd at this point */
5543     fp->tx_pkt_prod++;
5544     fp->tx_bd_prod = bd_prod;
5545
5546     DOORBELL(sc, fp->index, fp->tx_db.raw);
5547
5548     fp->eth_q_stats.tx_pkts++;
5549
5550     /* Prevent speculative reads from getting ahead of the status block. */
5551     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5552                       0, 0, BUS_SPACE_BARRIER_READ);
5553
5554     /* Prevent speculative reads from getting ahead of the doorbell. */
5555     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5556                       0, 0, BUS_SPACE_BARRIER_READ);
5557
5558     return (0);
5559 }
5560
5561 static void
5562 bxe_tx_start_locked(struct bxe_softc    *sc,
5563                     struct ifnet        *ifp,
5564                     struct bxe_fastpath *fp)
5565 {
5566     struct mbuf *m = NULL;
5567     int tx_count = 0;
5568     uint16_t tx_bd_avail;
5569
5570     BXE_FP_TX_LOCK_ASSERT(fp);
5571
5572     /* keep adding entries while there are frames to send */
5573     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5574
5575         /*
5576          * check for any frames to send
5577          * dequeue can still be NULL even if queue is not empty
5578          */
5579         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5580         if (__predict_false(m == NULL)) {
5581             break;
5582         }
5583
5584         /* the mbuf now belongs to us */
5585         fp->eth_q_stats.mbuf_alloc_tx++;
5586
5587         /*
5588          * Put the frame into the transmit ring. If we don't have room,
5589          * place the mbuf back at the head of the TX queue, set the
5590          * OACTIVE flag, and wait for the NIC to drain the chain.
5591          */
5592         if (__predict_false(bxe_tx_encap(fp, &m))) {
5593             fp->eth_q_stats.tx_encap_failures++;
5594             if (m != NULL) {
5595                 /* mark the TX queue as full and return the frame */
5596                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5597                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5598                 fp->eth_q_stats.mbuf_alloc_tx--;
5599                 fp->eth_q_stats.tx_queue_xoff++;
5600             }
5601
5602             /* stop looking for more work */
5603             break;
5604         }
5605
5606         /* the frame was enqueued successfully */
5607         tx_count++;
5608
5609         /* send a copy of the frame to any BPF listeners. */
5610         BPF_MTAP(ifp, m);
5611
5612         tx_bd_avail = bxe_tx_avail(sc, fp);
5613
5614         /* handle any completions if we're running low */
5615         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5616             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5617             bxe_txeof(sc, fp);
5618             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5619                 break;
5620             }
5621         }
5622     }
5623
5624     /* all TX packets were dequeued and/or the tx ring is full */
5625     if (tx_count > 0) {
5626         /* reset the TX watchdog timeout timer */
5627         fp->watchdog_timer = BXE_TX_TIMEOUT;
5628     }
5629 }
5630
5631 /* Legacy (non-RSS) dispatch routine */
5632 static void
5633 bxe_tx_start(struct ifnet *ifp)
5634 {
5635     struct bxe_softc *sc;
5636     struct bxe_fastpath *fp;
5637
5638     sc = ifp->if_softc;
5639
5640     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5641         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5642         return;
5643     }
5644
5645     if (!sc->link_vars.link_up) {
5646         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5647         return;
5648     }
5649
5650     fp = &sc->fp[0];
5651
5652     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5653         fp->eth_q_stats.tx_queue_full_return++;
5654         return;
5655     }
5656
5657     BXE_FP_TX_LOCK(fp);
5658     bxe_tx_start_locked(sc, ifp, fp);
5659     BXE_FP_TX_UNLOCK(fp);
5660 }
5661
5662 #if __FreeBSD_version >= 901504
5663
5664 static int
5665 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5666                        struct ifnet        *ifp,
5667                        struct bxe_fastpath *fp,
5668                        struct mbuf         *m)
5669 {
5670     struct buf_ring *tx_br = fp->tx_br;
5671     struct mbuf *next;
5672     int depth, rc, tx_count;
5673     uint16_t tx_bd_avail;
5674
5675     rc = tx_count = 0;
5676
5677     BXE_FP_TX_LOCK_ASSERT(fp);
5678
5679     if (sc->state != BXE_STATE_OPEN)  {
5680         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5681         return ENETDOWN;
5682     }
5683
5684     if (!tx_br) {
5685         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5686         return (EINVAL);
5687     }
5688
5689     if (m != NULL) {
5690         rc = drbr_enqueue(ifp, tx_br, m);
5691         if (rc != 0) {
5692             fp->eth_q_stats.tx_soft_errors++;
5693             goto bxe_tx_mq_start_locked_exit;
5694         }
5695     }
5696
5697     if (!sc->link_vars.link_up || !(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5698         fp->eth_q_stats.tx_request_link_down_failures++;
5699         goto bxe_tx_mq_start_locked_exit;
5700     }
5701
5702     /* fetch the depth of the driver queue */
5703     depth = drbr_inuse(ifp, tx_br);
5704     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5705         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5706     }
5707
5708     /* keep adding entries while there are frames to send */
5709     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5710         /* handle any completions if we're running low */
5711         tx_bd_avail = bxe_tx_avail(sc, fp);
5712         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5713             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5714             bxe_txeof(sc, fp);
5715             tx_bd_avail = bxe_tx_avail(sc, fp);
5716             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5717                 fp->eth_q_stats.bd_avail_too_less_failures++;
5718                 m_freem(next);
5719                 drbr_advance(ifp, tx_br);
5720                 rc = ENOBUFS;
5721                 break;
5722             }
5723         }
5724
5725         /* the mbuf now belongs to us */
5726         fp->eth_q_stats.mbuf_alloc_tx++;
5727
5728         /*
5729          * Put the frame into the transmit ring. If we don't have room,
5730          * place the mbuf back at the head of the TX queue, set the
5731          * OACTIVE flag, and wait for the NIC to drain the chain.
5732          */
5733         rc = bxe_tx_encap(fp, &next);
5734         if (__predict_false(rc != 0)) {
5735             fp->eth_q_stats.tx_encap_failures++;
5736             if (next != NULL) {
5737                 /* mark the TX queue as full and save the frame */
5738                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5739                 drbr_putback(ifp, tx_br, next);
5740                 fp->eth_q_stats.mbuf_alloc_tx--;
5741                 fp->eth_q_stats.tx_frames_deferred++;
5742             } else
5743                 drbr_advance(ifp, tx_br);
5744
5745             /* stop looking for more work */
5746             break;
5747         }
5748
5749         /* the transmit frame was enqueued successfully */
5750         tx_count++;
5751
5752         /* send a copy of the frame to any BPF listeners */
5753         BPF_MTAP(ifp, next);
5754
5755         drbr_advance(ifp, tx_br);
5756     }
5757
5758     /* all TX packets were dequeued and/or the tx ring is full */
5759     if (tx_count > 0) {
5760         /* reset the TX watchdog timeout timer */
5761         fp->watchdog_timer = BXE_TX_TIMEOUT;
5762     }
5763
5764 bxe_tx_mq_start_locked_exit:
5765     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5766     if (!drbr_empty(ifp, tx_br)) {
5767         fp->eth_q_stats.tx_mq_not_empty++;
5768         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5769     }
5770
5771     return (rc);
5772 }
5773
5774 static void
5775 bxe_tx_mq_start_deferred(void *arg,
5776                          int pending)
5777 {
5778     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5779     struct bxe_softc *sc = fp->sc;
5780     struct ifnet *ifp = sc->ifnet;
5781
5782     BXE_FP_TX_LOCK(fp);
5783     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5784     BXE_FP_TX_UNLOCK(fp);
5785 }
5786
5787 /* Multiqueue (TSS) dispatch routine. */
5788 static int
5789 bxe_tx_mq_start(struct ifnet *ifp,
5790                 struct mbuf  *m)
5791 {
5792     struct bxe_softc *sc = ifp->if_softc;
5793     struct bxe_fastpath *fp;
5794     int fp_index, rc;
5795
5796     fp_index = 0; /* default is the first queue */
5797
5798     /* check if flowid is set */
5799
5800     if (BXE_VALID_FLOWID(m))
5801         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5802
5803     fp = &sc->fp[fp_index];
5804
5805     if (sc->state != BXE_STATE_OPEN)  {
5806         fp->eth_q_stats.bxe_tx_mq_sc_state_failures++;
5807         return ENETDOWN;
5808     }
5809
5810     if (BXE_FP_TX_TRYLOCK(fp)) {
5811         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5812         BXE_FP_TX_UNLOCK(fp);
5813     } else {
5814         rc = drbr_enqueue(ifp, fp->tx_br, m);
5815         taskqueue_enqueue(fp->tq, &fp->tx_task);
5816     }
5817
5818     return (rc);
5819 }
5820
5821 static void
5822 bxe_mq_flush(struct ifnet *ifp)
5823 {
5824     struct bxe_softc *sc = ifp->if_softc;
5825     struct bxe_fastpath *fp;
5826     struct mbuf *m;
5827     int i;
5828
5829     for (i = 0; i < sc->num_queues; i++) {
5830         fp = &sc->fp[i];
5831
5832         if (fp->state != BXE_FP_STATE_IRQ) {
5833             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5834                   fp->index, fp->state);
5835             continue;
5836         }
5837
5838         if (fp->tx_br != NULL) {
5839             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5840             BXE_FP_TX_LOCK(fp);
5841             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5842                 m_freem(m);
5843             }
5844             BXE_FP_TX_UNLOCK(fp);
5845         }
5846     }
5847
5848     if_qflush(ifp);
5849 }
5850
5851 #endif /* FreeBSD_version >= 901504 */
5852
5853 static uint16_t
5854 bxe_cid_ilt_lines(struct bxe_softc *sc)
5855 {
5856     if (IS_SRIOV(sc)) {
5857         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5858     }
5859     return (L2_ILT_LINES(sc));
5860 }
5861
5862 static void
5863 bxe_ilt_set_info(struct bxe_softc *sc)
5864 {
5865     struct ilt_client_info *ilt_client;
5866     struct ecore_ilt *ilt = sc->ilt;
5867     uint16_t line = 0;
5868
5869     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5870     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5871
5872     /* CDU */
5873     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5874     ilt_client->client_num = ILT_CLIENT_CDU;
5875     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5876     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5877     ilt_client->start = line;
5878     line += bxe_cid_ilt_lines(sc);
5879
5880     if (CNIC_SUPPORT(sc)) {
5881         line += CNIC_ILT_LINES;
5882     }
5883
5884     ilt_client->end = (line - 1);
5885
5886     BLOGD(sc, DBG_LOAD,
5887           "ilt client[CDU]: start %d, end %d, "
5888           "psz 0x%x, flags 0x%x, hw psz %d\n",
5889           ilt_client->start, ilt_client->end,
5890           ilt_client->page_size,
5891           ilt_client->flags,
5892           ilog2(ilt_client->page_size >> 12));
5893
5894     /* QM */
5895     if (QM_INIT(sc->qm_cid_count)) {
5896         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5897         ilt_client->client_num = ILT_CLIENT_QM;
5898         ilt_client->page_size = QM_ILT_PAGE_SZ;
5899         ilt_client->flags = 0;
5900         ilt_client->start = line;
5901
5902         /* 4 bytes for each cid */
5903         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5904                              QM_ILT_PAGE_SZ);
5905
5906         ilt_client->end = (line - 1);
5907
5908         BLOGD(sc, DBG_LOAD,
5909               "ilt client[QM]: start %d, end %d, "
5910               "psz 0x%x, flags 0x%x, hw psz %d\n",
5911               ilt_client->start, ilt_client->end,
5912               ilt_client->page_size, ilt_client->flags,
5913               ilog2(ilt_client->page_size >> 12));
5914     }
5915
5916     if (CNIC_SUPPORT(sc)) {
5917         /* SRC */
5918         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5919         ilt_client->client_num = ILT_CLIENT_SRC;
5920         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5921         ilt_client->flags = 0;
5922         ilt_client->start = line;
5923         line += SRC_ILT_LINES;
5924         ilt_client->end = (line - 1);
5925
5926         BLOGD(sc, DBG_LOAD,
5927               "ilt client[SRC]: start %d, end %d, "
5928               "psz 0x%x, flags 0x%x, hw psz %d\n",
5929               ilt_client->start, ilt_client->end,
5930               ilt_client->page_size, ilt_client->flags,
5931               ilog2(ilt_client->page_size >> 12));
5932
5933         /* TM */
5934         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5935         ilt_client->client_num = ILT_CLIENT_TM;
5936         ilt_client->page_size = TM_ILT_PAGE_SZ;
5937         ilt_client->flags = 0;
5938         ilt_client->start = line;
5939         line += TM_ILT_LINES;
5940         ilt_client->end = (line - 1);
5941
5942         BLOGD(sc, DBG_LOAD,
5943               "ilt client[TM]: start %d, end %d, "
5944               "psz 0x%x, flags 0x%x, hw psz %d\n",
5945               ilt_client->start, ilt_client->end,
5946               ilt_client->page_size, ilt_client->flags,
5947               ilog2(ilt_client->page_size >> 12));
5948     }
5949
5950     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5951 }
5952
5953 static void
5954 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5955 {
5956     int i;
5957     uint32_t rx_buf_size;
5958
5959     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5960
5961     for (i = 0; i < sc->num_queues; i++) {
5962         if(rx_buf_size <= MCLBYTES){
5963             sc->fp[i].rx_buf_size = rx_buf_size;
5964             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5965         }else if (rx_buf_size <= MJUMPAGESIZE){
5966             sc->fp[i].rx_buf_size = rx_buf_size;
5967             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5968         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5969             sc->fp[i].rx_buf_size = MCLBYTES;
5970             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5971         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5972             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5973             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5974         }else {
5975             sc->fp[i].rx_buf_size = MCLBYTES;
5976             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5977         }
5978     }
5979 }
5980
5981 static int
5982 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5983 {
5984     int rc = 0;
5985
5986     if ((sc->ilt =
5987          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5988                                     M_BXE_ILT,
5989                                     (M_NOWAIT | M_ZERO))) == NULL) {
5990         rc = 1;
5991     }
5992
5993     return (rc);
5994 }
5995
5996 static int
5997 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5998 {
5999     int rc = 0;
6000
6001     if ((sc->ilt->lines =
6002          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6003                                     M_BXE_ILT,
6004                                     (M_NOWAIT | M_ZERO))) == NULL) {
6005         rc = 1;
6006     }
6007
6008     return (rc);
6009 }
6010
6011 static void
6012 bxe_free_ilt_mem(struct bxe_softc *sc)
6013 {
6014     if (sc->ilt != NULL) {
6015         free(sc->ilt, M_BXE_ILT);
6016         sc->ilt = NULL;
6017     }
6018 }
6019
6020 static void
6021 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6022 {
6023     if (sc->ilt->lines != NULL) {
6024         free(sc->ilt->lines, M_BXE_ILT);
6025         sc->ilt->lines = NULL;
6026     }
6027 }
6028
6029 static void
6030 bxe_free_mem(struct bxe_softc *sc)
6031 {
6032     int i;
6033
6034     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6035         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6036         sc->context[i].vcxt = NULL;
6037         sc->context[i].size = 0;
6038     }
6039
6040     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6041
6042     bxe_free_ilt_lines_mem(sc);
6043
6044 }
6045
6046 static int
6047 bxe_alloc_mem(struct bxe_softc *sc)
6048 {
6049
6050     int context_size;
6051     int allocated;
6052     int i;
6053
6054     /*
6055      * Allocate memory for CDU context:
6056      * This memory is allocated separately and not in the generic ILT
6057      * functions because CDU differs in few aspects:
6058      * 1. There can be multiple entities allocating memory for context -
6059      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6060      * its own ILT lines.
6061      * 2. Since CDU page-size is not a single 4KB page (which is the case
6062      * for the other ILT clients), to be efficient we want to support
6063      * allocation of sub-page-size in the last entry.
6064      * 3. Context pointers are used by the driver to pass to FW / update
6065      * the context (for the other ILT clients the pointers are used just to
6066      * free the memory during unload).
6067      */
6068     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6069     for (i = 0, allocated = 0; allocated < context_size; i++) {
6070         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6071                                   (context_size - allocated));
6072
6073         if (bxe_dma_alloc(sc, sc->context[i].size,
6074                           &sc->context[i].vcxt_dma,
6075                           "cdu context") != 0) {
6076             bxe_free_mem(sc);
6077             return (-1);
6078         }
6079
6080         sc->context[i].vcxt =
6081             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6082
6083         allocated += sc->context[i].size;
6084     }
6085
6086     bxe_alloc_ilt_lines_mem(sc);
6087
6088     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6089           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6090     {
6091         for (i = 0; i < 4; i++) {
6092             BLOGD(sc, DBG_LOAD,
6093                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6094                   i,
6095                   sc->ilt->clients[i].page_size,
6096                   sc->ilt->clients[i].start,
6097                   sc->ilt->clients[i].end,
6098                   sc->ilt->clients[i].client_num,
6099                   sc->ilt->clients[i].flags);
6100         }
6101     }
6102     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6103         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6104         bxe_free_mem(sc);
6105         return (-1);
6106     }
6107
6108     return (0);
6109 }
6110
6111 static void
6112 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6113 {
6114     struct bxe_softc *sc;
6115     int i;
6116
6117     sc = fp->sc;
6118
6119     if (fp->rx_mbuf_tag == NULL) {
6120         return;
6121     }
6122
6123     /* free all mbufs and unload all maps */
6124     for (i = 0; i < RX_BD_TOTAL; i++) {
6125         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6126             bus_dmamap_sync(fp->rx_mbuf_tag,
6127                             fp->rx_mbuf_chain[i].m_map,
6128                             BUS_DMASYNC_POSTREAD);
6129             bus_dmamap_unload(fp->rx_mbuf_tag,
6130                               fp->rx_mbuf_chain[i].m_map);
6131         }
6132
6133         if (fp->rx_mbuf_chain[i].m != NULL) {
6134             m_freem(fp->rx_mbuf_chain[i].m);
6135             fp->rx_mbuf_chain[i].m = NULL;
6136             fp->eth_q_stats.mbuf_alloc_rx--;
6137         }
6138     }
6139 }
6140
6141 static void
6142 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6143 {
6144     struct bxe_softc *sc;
6145     int i, max_agg_queues;
6146
6147     sc = fp->sc;
6148
6149     if (fp->rx_mbuf_tag == NULL) {
6150         return;
6151     }
6152
6153     max_agg_queues = MAX_AGG_QS(sc);
6154
6155     /* release all mbufs and unload all DMA maps in the TPA pool */
6156     for (i = 0; i < max_agg_queues; i++) {
6157         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6158             bus_dmamap_sync(fp->rx_mbuf_tag,
6159                             fp->rx_tpa_info[i].bd.m_map,
6160                             BUS_DMASYNC_POSTREAD);
6161             bus_dmamap_unload(fp->rx_mbuf_tag,
6162                               fp->rx_tpa_info[i].bd.m_map);
6163         }
6164
6165         if (fp->rx_tpa_info[i].bd.m != NULL) {
6166             m_freem(fp->rx_tpa_info[i].bd.m);
6167             fp->rx_tpa_info[i].bd.m = NULL;
6168             fp->eth_q_stats.mbuf_alloc_tpa--;
6169         }
6170     }
6171 }
6172
6173 static void
6174 bxe_free_sge_chain(struct bxe_fastpath *fp)
6175 {
6176     struct bxe_softc *sc;
6177     int i;
6178
6179     sc = fp->sc;
6180
6181     if (fp->rx_sge_mbuf_tag == NULL) {
6182         return;
6183     }
6184
6185     /* rree all mbufs and unload all maps */
6186     for (i = 0; i < RX_SGE_TOTAL; i++) {
6187         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6188             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6189                             fp->rx_sge_mbuf_chain[i].m_map,
6190                             BUS_DMASYNC_POSTREAD);
6191             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6192                               fp->rx_sge_mbuf_chain[i].m_map);
6193         }
6194
6195         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6196             m_freem(fp->rx_sge_mbuf_chain[i].m);
6197             fp->rx_sge_mbuf_chain[i].m = NULL;
6198             fp->eth_q_stats.mbuf_alloc_sge--;
6199         }
6200     }
6201 }
6202
6203 static void
6204 bxe_free_fp_buffers(struct bxe_softc *sc)
6205 {
6206     struct bxe_fastpath *fp;
6207     int i;
6208
6209     for (i = 0; i < sc->num_queues; i++) {
6210         fp = &sc->fp[i];
6211
6212 #if __FreeBSD_version >= 901504
6213         if (fp->tx_br != NULL) {
6214             /* just in case bxe_mq_flush() wasn't called */
6215             if (mtx_initialized(&fp->tx_mtx)) {
6216                 struct mbuf *m;
6217
6218                 BXE_FP_TX_LOCK(fp);
6219                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6220                     m_freem(m);
6221                 BXE_FP_TX_UNLOCK(fp);
6222             }
6223         }
6224 #endif
6225
6226         /* free all RX buffers */
6227         bxe_free_rx_bd_chain(fp);
6228         bxe_free_tpa_pool(fp);
6229         bxe_free_sge_chain(fp);
6230
6231         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6232             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6233                   fp->eth_q_stats.mbuf_alloc_rx);
6234         }
6235
6236         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6237             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6238                   fp->eth_q_stats.mbuf_alloc_sge);
6239         }
6240
6241         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6242             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6243                   fp->eth_q_stats.mbuf_alloc_tpa);
6244         }
6245
6246         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6247             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6248                   fp->eth_q_stats.mbuf_alloc_tx);
6249         }
6250
6251         /* XXX verify all mbufs were reclaimed */
6252     }
6253 }
6254
6255 static int
6256 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6257                      uint16_t            prev_index,
6258                      uint16_t            index)
6259 {
6260     struct bxe_sw_rx_bd *rx_buf;
6261     struct eth_rx_bd *rx_bd;
6262     bus_dma_segment_t segs[1];
6263     bus_dmamap_t map;
6264     struct mbuf *m;
6265     int nsegs, rc;
6266
6267     rc = 0;
6268
6269     /* allocate the new RX BD mbuf */
6270     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6271     if (__predict_false(m == NULL)) {
6272         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6273         return (ENOBUFS);
6274     }
6275
6276     fp->eth_q_stats.mbuf_alloc_rx++;
6277
6278     /* initialize the mbuf buffer length */
6279     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6280
6281     /* map the mbuf into non-paged pool */
6282     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6283                                  fp->rx_mbuf_spare_map,
6284                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6285     if (__predict_false(rc != 0)) {
6286         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6287         m_freem(m);
6288         fp->eth_q_stats.mbuf_alloc_rx--;
6289         return (rc);
6290     }
6291
6292     /* all mbufs must map to a single segment */
6293     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6294
6295     /* release any existing RX BD mbuf mappings */
6296
6297     if (prev_index != index) {
6298         rx_buf = &fp->rx_mbuf_chain[prev_index];
6299
6300         if (rx_buf->m_map != NULL) {
6301             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6302                             BUS_DMASYNC_POSTREAD);
6303             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6304         }
6305
6306         /*
6307          * We only get here from bxe_rxeof() when the maximum number
6308          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6309          * holds the mbuf in the prev_index so it's OK to NULL it out
6310          * here without concern of a memory leak.
6311          */
6312         fp->rx_mbuf_chain[prev_index].m = NULL;
6313     }
6314
6315     rx_buf = &fp->rx_mbuf_chain[index];
6316
6317     if (rx_buf->m_map != NULL) {
6318         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6319                         BUS_DMASYNC_POSTREAD);
6320         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6321     }
6322
6323     /* save the mbuf and mapping info for a future packet */
6324     map = (prev_index != index) ?
6325               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6326     rx_buf->m_map = fp->rx_mbuf_spare_map;
6327     fp->rx_mbuf_spare_map = map;
6328     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6329                     BUS_DMASYNC_PREREAD);
6330     rx_buf->m = m;
6331
6332     rx_bd = &fp->rx_chain[index];
6333     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6334     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6335
6336     return (rc);
6337 }
6338
6339 static int
6340 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6341                       int                 queue)
6342 {
6343     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6344     bus_dma_segment_t segs[1];
6345     bus_dmamap_t map;
6346     struct mbuf *m;
6347     int nsegs;
6348     int rc = 0;
6349
6350     /* allocate the new TPA mbuf */
6351     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6352     if (__predict_false(m == NULL)) {
6353         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6354         return (ENOBUFS);
6355     }
6356
6357     fp->eth_q_stats.mbuf_alloc_tpa++;
6358
6359     /* initialize the mbuf buffer length */
6360     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6361
6362     /* map the mbuf into non-paged pool */
6363     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6364                                  fp->rx_tpa_info_mbuf_spare_map,
6365                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6366     if (__predict_false(rc != 0)) {
6367         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6368         m_free(m);
6369         fp->eth_q_stats.mbuf_alloc_tpa--;
6370         return (rc);
6371     }
6372
6373     /* all mbufs must map to a single segment */
6374     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6375
6376     /* release any existing TPA mbuf mapping */
6377     if (tpa_info->bd.m_map != NULL) {
6378         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6379                         BUS_DMASYNC_POSTREAD);
6380         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6381     }
6382
6383     /* save the mbuf and mapping info for the TPA mbuf */
6384     map = tpa_info->bd.m_map;
6385     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6386     fp->rx_tpa_info_mbuf_spare_map = map;
6387     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6388                     BUS_DMASYNC_PREREAD);
6389     tpa_info->bd.m = m;
6390     tpa_info->seg = segs[0];
6391
6392     return (rc);
6393 }
6394
6395 /*
6396  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6397  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6398  * chain.
6399  */
6400 static int
6401 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6402                       uint16_t            index)
6403 {
6404     struct bxe_sw_rx_bd *sge_buf;
6405     struct eth_rx_sge *sge;
6406     bus_dma_segment_t segs[1];
6407     bus_dmamap_t map;
6408     struct mbuf *m;
6409     int nsegs;
6410     int rc = 0;
6411
6412     /* allocate a new SGE mbuf */
6413     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6414     if (__predict_false(m == NULL)) {
6415         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6416         return (ENOMEM);
6417     }
6418
6419     fp->eth_q_stats.mbuf_alloc_sge++;
6420
6421     /* initialize the mbuf buffer length */
6422     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6423
6424     /* map the SGE mbuf into non-paged pool */
6425     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6426                                  fp->rx_sge_mbuf_spare_map,
6427                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6428     if (__predict_false(rc != 0)) {
6429         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6430         m_freem(m);
6431         fp->eth_q_stats.mbuf_alloc_sge--;
6432         return (rc);
6433     }
6434
6435     /* all mbufs must map to a single segment */
6436     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6437
6438     sge_buf = &fp->rx_sge_mbuf_chain[index];
6439
6440     /* release any existing SGE mbuf mapping */
6441     if (sge_buf->m_map != NULL) {
6442         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6443                         BUS_DMASYNC_POSTREAD);
6444         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6445     }
6446
6447     /* save the mbuf and mapping info for a future packet */
6448     map = sge_buf->m_map;
6449     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6450     fp->rx_sge_mbuf_spare_map = map;
6451     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6452                     BUS_DMASYNC_PREREAD);
6453     sge_buf->m = m;
6454
6455     sge = &fp->rx_sge_chain[index];
6456     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6457     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6458
6459     return (rc);
6460 }
6461
6462 static __noinline int
6463 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6464 {
6465     struct bxe_fastpath *fp;
6466     int i, j, rc = 0;
6467     int ring_prod, cqe_ring_prod;
6468     int max_agg_queues;
6469
6470     for (i = 0; i < sc->num_queues; i++) {
6471         fp = &sc->fp[i];
6472
6473         ring_prod = cqe_ring_prod = 0;
6474         fp->rx_bd_cons = 0;
6475         fp->rx_cq_cons = 0;
6476
6477         /* allocate buffers for the RX BDs in RX BD chain */
6478         for (j = 0; j < sc->max_rx_bufs; j++) {
6479             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6480             if (rc != 0) {
6481                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6482                       i, rc);
6483                 goto bxe_alloc_fp_buffers_error;
6484             }
6485
6486             ring_prod     = RX_BD_NEXT(ring_prod);
6487             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6488         }
6489
6490         fp->rx_bd_prod = ring_prod;
6491         fp->rx_cq_prod = cqe_ring_prod;
6492         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6493
6494         max_agg_queues = MAX_AGG_QS(sc);
6495
6496         fp->tpa_enable = TRUE;
6497
6498         /* fill the TPA pool */
6499         for (j = 0; j < max_agg_queues; j++) {
6500             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6501             if (rc != 0) {
6502                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6503                           i, j);
6504                 fp->tpa_enable = FALSE;
6505                 goto bxe_alloc_fp_buffers_error;
6506             }
6507
6508             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6509         }
6510
6511         if (fp->tpa_enable) {
6512             /* fill the RX SGE chain */
6513             ring_prod = 0;
6514             for (j = 0; j < RX_SGE_USABLE; j++) {
6515                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6516                 if (rc != 0) {
6517                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6518                               i, ring_prod);
6519                     fp->tpa_enable = FALSE;
6520                     ring_prod = 0;
6521                     goto bxe_alloc_fp_buffers_error;
6522                 }
6523
6524                 ring_prod = RX_SGE_NEXT(ring_prod);
6525             }
6526
6527             fp->rx_sge_prod = ring_prod;
6528         }
6529     }
6530
6531     return (0);
6532
6533 bxe_alloc_fp_buffers_error:
6534
6535     /* unwind what was already allocated */
6536     bxe_free_rx_bd_chain(fp);
6537     bxe_free_tpa_pool(fp);
6538     bxe_free_sge_chain(fp);
6539
6540     return (ENOBUFS);
6541 }
6542
6543 static void
6544 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6545 {
6546     bxe_dma_free(sc, &sc->fw_stats_dma);
6547
6548     sc->fw_stats_num = 0;
6549
6550     sc->fw_stats_req_size = 0;
6551     sc->fw_stats_req = NULL;
6552     sc->fw_stats_req_mapping = 0;
6553
6554     sc->fw_stats_data_size = 0;
6555     sc->fw_stats_data = NULL;
6556     sc->fw_stats_data_mapping = 0;
6557 }
6558
6559 static int
6560 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6561 {
6562     uint8_t num_queue_stats;
6563     int num_groups;
6564
6565     /* number of queues for statistics is number of eth queues */
6566     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6567
6568     /*
6569      * Total number of FW statistics requests =
6570      *   1 for port stats + 1 for PF stats + num of queues
6571      */
6572     sc->fw_stats_num = (2 + num_queue_stats);
6573
6574     /*
6575      * Request is built from stats_query_header and an array of
6576      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6577      * rules. The real number or requests is configured in the
6578      * stats_query_header.
6579      */
6580     num_groups =
6581         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6582          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6583
6584     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6585           sc->fw_stats_num, num_groups);
6586
6587     sc->fw_stats_req_size =
6588         (sizeof(struct stats_query_header) +
6589          (num_groups * sizeof(struct stats_query_cmd_group)));
6590
6591     /*
6592      * Data for statistics requests + stats_counter.
6593      * stats_counter holds per-STORM counters that are incremented when
6594      * STORM has finished with the current request. Memory for FCoE
6595      * offloaded statistics are counted anyway, even if they will not be sent.
6596      * VF stats are not accounted for here as the data of VF stats is stored
6597      * in memory allocated by the VF, not here.
6598      */
6599     sc->fw_stats_data_size =
6600         (sizeof(struct stats_counter) +
6601          sizeof(struct per_port_stats) +
6602          sizeof(struct per_pf_stats) +
6603          /* sizeof(struct fcoe_statistics_params) + */
6604          (sizeof(struct per_queue_stats) * num_queue_stats));
6605
6606     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6607                       &sc->fw_stats_dma, "fw stats") != 0) {
6608         bxe_free_fw_stats_mem(sc);
6609         return (-1);
6610     }
6611
6612     /* set up the shortcuts */
6613
6614     sc->fw_stats_req =
6615         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6616     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6617
6618     sc->fw_stats_data =
6619         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6620                                      sc->fw_stats_req_size);
6621     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6622                                  sc->fw_stats_req_size);
6623
6624     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6625           (uintmax_t)sc->fw_stats_req_mapping);
6626
6627     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6628           (uintmax_t)sc->fw_stats_data_mapping);
6629
6630     return (0);
6631 }
6632
6633 /*
6634  * Bits map:
6635  * 0-7  - Engine0 load counter.
6636  * 8-15 - Engine1 load counter.
6637  * 16   - Engine0 RESET_IN_PROGRESS bit.
6638  * 17   - Engine1 RESET_IN_PROGRESS bit.
6639  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6640  *        function on the engine
6641  * 19   - Engine1 ONE_IS_LOADED.
6642  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6643  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6644  *        for just the one belonging to its engine).
6645  */
6646 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6647 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6648 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6649 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6650 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6651 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6652 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6653 #define BXE_GLOBAL_RESET_BIT      0x00040000
6654
6655 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6656 static void
6657 bxe_set_reset_global(struct bxe_softc *sc)
6658 {
6659     uint32_t val;
6660     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6661     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6662     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6663     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6664 }
6665
6666 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6667 static void
6668 bxe_clear_reset_global(struct bxe_softc *sc)
6669 {
6670     uint32_t val;
6671     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6672     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6673     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6674     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6675 }
6676
6677 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6678 static uint8_t
6679 bxe_reset_is_global(struct bxe_softc *sc)
6680 {
6681     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6682     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6683     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6684 }
6685
6686 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6687 static void
6688 bxe_set_reset_done(struct bxe_softc *sc)
6689 {
6690     uint32_t val;
6691     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6692                                  BXE_PATH0_RST_IN_PROG_BIT;
6693
6694     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6695
6696     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6697     /* Clear the bit */
6698     val &= ~bit;
6699     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6700
6701     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6702 }
6703
6704 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6705 static void
6706 bxe_set_reset_in_progress(struct bxe_softc *sc)
6707 {
6708     uint32_t val;
6709     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6710                                  BXE_PATH0_RST_IN_PROG_BIT;
6711
6712     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6713
6714     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6715     /* Set the bit */
6716     val |= bit;
6717     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6718
6719     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6720 }
6721
6722 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6723 static uint8_t
6724 bxe_reset_is_done(struct bxe_softc *sc,
6725                   int              engine)
6726 {
6727     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6728     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6729                             BXE_PATH0_RST_IN_PROG_BIT;
6730
6731     /* return false if bit is set */
6732     return (val & bit) ? FALSE : TRUE;
6733 }
6734
6735 /* get the load status for an engine, should be run under rtnl lock */
6736 static uint8_t
6737 bxe_get_load_status(struct bxe_softc *sc,
6738                     int              engine)
6739 {
6740     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6741                              BXE_PATH0_LOAD_CNT_MASK;
6742     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6743                               BXE_PATH0_LOAD_CNT_SHIFT;
6744     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6745
6746     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6747
6748     val = ((val & mask) >> shift);
6749
6750     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6751
6752     return (val != 0);
6753 }
6754
6755 /* set pf load mark */
6756 /* XXX needs to be under rtnl lock */
6757 static void
6758 bxe_set_pf_load(struct bxe_softc *sc)
6759 {
6760     uint32_t val;
6761     uint32_t val1;
6762     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6763                                   BXE_PATH0_LOAD_CNT_MASK;
6764     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6765                                    BXE_PATH0_LOAD_CNT_SHIFT;
6766
6767     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6768
6769     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6770     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6771
6772     /* get the current counter value */
6773     val1 = ((val & mask) >> shift);
6774
6775     /* set bit of this PF */
6776     val1 |= (1 << SC_ABS_FUNC(sc));
6777
6778     /* clear the old value */
6779     val &= ~mask;
6780
6781     /* set the new one */
6782     val |= ((val1 << shift) & mask);
6783
6784     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6785
6786     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6787 }
6788
6789 /* clear pf load mark */
6790 /* XXX needs to be under rtnl lock */
6791 static uint8_t
6792 bxe_clear_pf_load(struct bxe_softc *sc)
6793 {
6794     uint32_t val1, val;
6795     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6796                                   BXE_PATH0_LOAD_CNT_MASK;
6797     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6798                                    BXE_PATH0_LOAD_CNT_SHIFT;
6799
6800     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6801     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6802     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6803
6804     /* get the current counter value */
6805     val1 = (val & mask) >> shift;
6806
6807     /* clear bit of that PF */
6808     val1 &= ~(1 << SC_ABS_FUNC(sc));
6809
6810     /* clear the old value */
6811     val &= ~mask;
6812
6813     /* set the new one */
6814     val |= ((val1 << shift) & mask);
6815
6816     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6817     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6818     return (val1 != 0);
6819 }
6820
6821 /* send load requrest to mcp and analyze response */
6822 static int
6823 bxe_nic_load_request(struct bxe_softc *sc,
6824                      uint32_t         *load_code)
6825 {
6826     /* init fw_seq */
6827     sc->fw_seq =
6828         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6829          DRV_MSG_SEQ_NUMBER_MASK);
6830
6831     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6832
6833     /* get the current FW pulse sequence */
6834     sc->fw_drv_pulse_wr_seq =
6835         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6836          DRV_PULSE_SEQ_MASK);
6837
6838     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6839           sc->fw_drv_pulse_wr_seq);
6840
6841     /* load request */
6842     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6843                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6844
6845     /* if the MCP fails to respond we must abort */
6846     if (!(*load_code)) {
6847         BLOGE(sc, "MCP response failure!\n");
6848         return (-1);
6849     }
6850
6851     /* if MCP refused then must abort */
6852     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6853         BLOGE(sc, "MCP refused load request\n");
6854         return (-1);
6855     }
6856
6857     return (0);
6858 }
6859
6860 /*
6861  * Check whether another PF has already loaded FW to chip. In virtualized
6862  * environments a pf from anoth VM may have already initialized the device
6863  * including loading FW.
6864  */
6865 static int
6866 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6867                          uint32_t         load_code)
6868 {
6869     uint32_t my_fw, loaded_fw;
6870
6871     /* is another pf loaded on this engine? */
6872     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6873         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6874         /* build my FW version dword */
6875         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6876                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6877                  (BCM_5710_FW_REVISION_VERSION << 16) +
6878                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6879
6880         /* read loaded FW from chip */
6881         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6882         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6883               loaded_fw, my_fw);
6884
6885         /* abort nic load if version mismatch */
6886         if (my_fw != loaded_fw) {
6887             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6888                   loaded_fw, my_fw);
6889             return (-1);
6890         }
6891     }
6892
6893     return (0);
6894 }
6895
6896 /* mark PMF if applicable */
6897 static void
6898 bxe_nic_load_pmf(struct bxe_softc *sc,
6899                  uint32_t         load_code)
6900 {
6901     uint32_t ncsi_oem_data_addr;
6902
6903     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6904         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6905         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6906         /*
6907          * Barrier here for ordering between the writing to sc->port.pmf here
6908          * and reading it from the periodic task.
6909          */
6910         sc->port.pmf = 1;
6911         mb();
6912     } else {
6913         sc->port.pmf = 0;
6914     }
6915
6916     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6917
6918     /* XXX needed? */
6919     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6920         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6921             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6922             if (ncsi_oem_data_addr) {
6923                 REG_WR(sc,
6924                        (ncsi_oem_data_addr +
6925                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6926                        0);
6927             }
6928         }
6929     }
6930 }
6931
6932 static void
6933 bxe_read_mf_cfg(struct bxe_softc *sc)
6934 {
6935     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6936     int abs_func;
6937     int vn;
6938
6939     if (BXE_NOMCP(sc)) {
6940         return; /* what should be the default bvalue in this case */
6941     }
6942
6943     /*
6944      * The formula for computing the absolute function number is...
6945      * For 2 port configuration (4 functions per port):
6946      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6947      * For 4 port configuration (2 functions per port):
6948      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6949      */
6950     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6951         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6952         if (abs_func >= E1H_FUNC_MAX) {
6953             break;
6954         }
6955         sc->devinfo.mf_info.mf_config[vn] =
6956             MFCFG_RD(sc, func_mf_config[abs_func].config);
6957     }
6958
6959     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6960         FUNC_MF_CFG_FUNC_DISABLED) {
6961         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6962         sc->flags |= BXE_MF_FUNC_DIS;
6963     } else {
6964         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6965         sc->flags &= ~BXE_MF_FUNC_DIS;
6966     }
6967 }
6968
6969 /* acquire split MCP access lock register */
6970 static int bxe_acquire_alr(struct bxe_softc *sc)
6971 {
6972     uint32_t j, val;
6973
6974     for (j = 0; j < 1000; j++) {
6975         val = (1UL << 31);
6976         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6977         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6978         if (val & (1L << 31))
6979             break;
6980
6981         DELAY(5000);
6982     }
6983
6984     if (!(val & (1L << 31))) {
6985         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6986         return (-1);
6987     }
6988
6989     return (0);
6990 }
6991
6992 /* release split MCP access lock register */
6993 static void bxe_release_alr(struct bxe_softc *sc)
6994 {
6995     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6996 }
6997
6998 static void
6999 bxe_fan_failure(struct bxe_softc *sc)
7000 {
7001     int port = SC_PORT(sc);
7002     uint32_t ext_phy_config;
7003
7004     /* mark the failure */
7005     ext_phy_config =
7006         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7007
7008     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7009     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7010     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7011              ext_phy_config);
7012
7013     /* log the failure */
7014     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7015               "the card to prevent permanent damage. "
7016               "Please contact OEM Support for assistance\n");
7017
7018     /* XXX */
7019 #if 1
7020     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7021 #else
7022     /*
7023      * Schedule device reset (unload)
7024      * This is due to some boards consuming sufficient power when driver is
7025      * up to overheat if fan fails.
7026      */
7027     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7028     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7029 #endif
7030 }
7031
7032 /* this function is called upon a link interrupt */
7033 static void
7034 bxe_link_attn(struct bxe_softc *sc)
7035 {
7036     uint32_t pause_enabled = 0;
7037     struct host_port_stats *pstats;
7038     int cmng_fns;
7039     struct bxe_fastpath *fp;
7040     int i;
7041
7042     /* Make sure that we are synced with the current statistics */
7043     bxe_stats_handle(sc, STATS_EVENT_STOP);
7044         BLOGI(sc, "link_vars phy_flags : %x\n", sc->link_vars.phy_flags);
7045     elink_link_update(&sc->link_params, &sc->link_vars);
7046
7047     if (sc->link_vars.link_up) {
7048
7049         /* dropless flow control */
7050         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7051             pause_enabled = 0;
7052
7053             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7054                 pause_enabled = 1;
7055             }
7056
7057             REG_WR(sc,
7058                    (BAR_USTRORM_INTMEM +
7059                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7060                    pause_enabled);
7061         }
7062
7063         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7064             pstats = BXE_SP(sc, port_stats);
7065             /* reset old mac stats */
7066             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7067         }
7068
7069         if (sc->state == BXE_STATE_OPEN) {
7070             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7071         }
7072
7073         /* Restart tx when the link comes back. */
7074         FOR_EACH_ETH_QUEUE(sc, i) {
7075             fp = &sc->fp[i];
7076             taskqueue_enqueue(fp->tq, &fp->tx_task);
7077         }
7078     }
7079
7080     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7081         cmng_fns = bxe_get_cmng_fns_mode(sc);
7082
7083         if (cmng_fns != CMNG_FNS_NONE) {
7084             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7085             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7086         } else {
7087             /* rate shaping and fairness are disabled */
7088             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7089         }
7090     }
7091
7092     bxe_link_report_locked(sc);
7093
7094     if (IS_MF(sc)) {
7095         ; // XXX bxe_link_sync_notify(sc);
7096     }
7097 }
7098
7099 static void
7100 bxe_attn_int_asserted(struct bxe_softc *sc,
7101                       uint32_t         asserted)
7102 {
7103     int port = SC_PORT(sc);
7104     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7105                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7106     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7107                                         NIG_REG_MASK_INTERRUPT_PORT0;
7108     uint32_t aeu_mask;
7109     uint32_t nig_mask = 0;
7110     uint32_t reg_addr;
7111     uint32_t igu_acked;
7112     uint32_t cnt;
7113
7114     if (sc->attn_state & asserted) {
7115         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7116     }
7117
7118     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7119
7120     aeu_mask = REG_RD(sc, aeu_addr);
7121
7122     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7123           aeu_mask, asserted);
7124
7125     aeu_mask &= ~(asserted & 0x3ff);
7126
7127     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7128
7129     REG_WR(sc, aeu_addr, aeu_mask);
7130
7131     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7132
7133     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7134     sc->attn_state |= asserted;
7135     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7136
7137     if (asserted & ATTN_HARD_WIRED_MASK) {
7138         if (asserted & ATTN_NIG_FOR_FUNC) {
7139
7140             bxe_acquire_phy_lock(sc);
7141             /* save nig interrupt mask */
7142             nig_mask = REG_RD(sc, nig_int_mask_addr);
7143
7144             /* If nig_mask is not set, no need to call the update function */
7145             if (nig_mask) {
7146                 REG_WR(sc, nig_int_mask_addr, 0);
7147
7148                 bxe_link_attn(sc);
7149             }
7150
7151             /* handle unicore attn? */
7152         }
7153
7154         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7155             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7156         }
7157
7158         if (asserted & GPIO_2_FUNC) {
7159             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7160         }
7161
7162         if (asserted & GPIO_3_FUNC) {
7163             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7164         }
7165
7166         if (asserted & GPIO_4_FUNC) {
7167             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7168         }
7169
7170         if (port == 0) {
7171             if (asserted & ATTN_GENERAL_ATTN_1) {
7172                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7173                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7174             }
7175             if (asserted & ATTN_GENERAL_ATTN_2) {
7176                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7177                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7178             }
7179             if (asserted & ATTN_GENERAL_ATTN_3) {
7180                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7181                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7182             }
7183         } else {
7184             if (asserted & ATTN_GENERAL_ATTN_4) {
7185                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7186                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7187             }
7188             if (asserted & ATTN_GENERAL_ATTN_5) {
7189                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7190                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7191             }
7192             if (asserted & ATTN_GENERAL_ATTN_6) {
7193                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7194                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7195             }
7196         }
7197     } /* hardwired */
7198
7199     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7200         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7201     } else {
7202         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7203     }
7204
7205     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7206           asserted,
7207           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7208     REG_WR(sc, reg_addr, asserted);
7209
7210     /* now set back the mask */
7211     if (asserted & ATTN_NIG_FOR_FUNC) {
7212         /*
7213          * Verify that IGU ack through BAR was written before restoring
7214          * NIG mask. This loop should exit after 2-3 iterations max.
7215          */
7216         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7217             cnt = 0;
7218
7219             do {
7220                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7221             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7222                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7223
7224             if (!igu_acked) {
7225                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7226             }
7227
7228             mb();
7229         }
7230
7231         REG_WR(sc, nig_int_mask_addr, nig_mask);
7232
7233         bxe_release_phy_lock(sc);
7234     }
7235 }
7236
7237 static void
7238 bxe_print_next_block(struct bxe_softc *sc,
7239                      int              idx,
7240                      const char       *blk)
7241 {
7242     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7243 }
7244
7245 static int
7246 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7247                               uint32_t         sig,
7248                               int              par_num,
7249                               uint8_t          print)
7250 {
7251     uint32_t cur_bit = 0;
7252     int i = 0;
7253
7254     for (i = 0; sig; i++) {
7255         cur_bit = ((uint32_t)0x1 << i);
7256         if (sig & cur_bit) {
7257             switch (cur_bit) {
7258             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7259                 if (print)
7260                     bxe_print_next_block(sc, par_num++, "BRB");
7261                 break;
7262             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7263                 if (print)
7264                     bxe_print_next_block(sc, par_num++, "PARSER");
7265                 break;
7266             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7267                 if (print)
7268                     bxe_print_next_block(sc, par_num++, "TSDM");
7269                 break;
7270             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7271                 if (print)
7272                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7273                 break;
7274             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7275                 if (print)
7276                     bxe_print_next_block(sc, par_num++, "TCM");
7277                 break;
7278             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7279                 if (print)
7280                     bxe_print_next_block(sc, par_num++, "TSEMI");
7281                 break;
7282             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7283                 if (print)
7284                     bxe_print_next_block(sc, par_num++, "XPB");
7285                 break;
7286             }
7287
7288             /* Clear the bit */
7289             sig &= ~cur_bit;
7290         }
7291     }
7292
7293     return (par_num);
7294 }
7295
7296 static int
7297 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7298                               uint32_t         sig,
7299                               int              par_num,
7300                               uint8_t          *global,
7301                               uint8_t          print)
7302 {
7303     int i = 0;
7304     uint32_t cur_bit = 0;
7305     for (i = 0; sig; i++) {
7306         cur_bit = ((uint32_t)0x1 << i);
7307         if (sig & cur_bit) {
7308             switch (cur_bit) {
7309             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7310                 if (print)
7311                     bxe_print_next_block(sc, par_num++, "PBF");
7312                 break;
7313             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7314                 if (print)
7315                     bxe_print_next_block(sc, par_num++, "QM");
7316                 break;
7317             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7318                 if (print)
7319                     bxe_print_next_block(sc, par_num++, "TM");
7320                 break;
7321             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7322                 if (print)
7323                     bxe_print_next_block(sc, par_num++, "XSDM");
7324                 break;
7325             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7326                 if (print)
7327                     bxe_print_next_block(sc, par_num++, "XCM");
7328                 break;
7329             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7330                 if (print)
7331                     bxe_print_next_block(sc, par_num++, "XSEMI");
7332                 break;
7333             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7334                 if (print)
7335                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7336                 break;
7337             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7338                 if (print)
7339                     bxe_print_next_block(sc, par_num++, "NIG");
7340                 break;
7341             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7342                 if (print)
7343                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7344                 *global = TRUE;
7345                 break;
7346             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7347                 if (print)
7348                     bxe_print_next_block(sc, par_num++, "DEBUG");
7349                 break;
7350             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7351                 if (print)
7352                     bxe_print_next_block(sc, par_num++, "USDM");
7353                 break;
7354             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7355                 if (print)
7356                     bxe_print_next_block(sc, par_num++, "UCM");
7357                 break;
7358             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7359                 if (print)
7360                     bxe_print_next_block(sc, par_num++, "USEMI");
7361                 break;
7362             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7363                 if (print)
7364                     bxe_print_next_block(sc, par_num++, "UPB");
7365                 break;
7366             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7367                 if (print)
7368                     bxe_print_next_block(sc, par_num++, "CSDM");
7369                 break;
7370             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7371                 if (print)
7372                     bxe_print_next_block(sc, par_num++, "CCM");
7373                 break;
7374             }
7375
7376             /* Clear the bit */
7377             sig &= ~cur_bit;
7378         }
7379     }
7380
7381     return (par_num);
7382 }
7383
7384 static int
7385 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7386                               uint32_t         sig,
7387                               int              par_num,
7388                               uint8_t          print)
7389 {
7390     uint32_t cur_bit = 0;
7391     int i = 0;
7392
7393     for (i = 0; sig; i++) {
7394         cur_bit = ((uint32_t)0x1 << i);
7395         if (sig & cur_bit) {
7396             switch (cur_bit) {
7397             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7398                 if (print)
7399                     bxe_print_next_block(sc, par_num++, "CSEMI");
7400                 break;
7401             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7402                 if (print)
7403                     bxe_print_next_block(sc, par_num++, "PXP");
7404                 break;
7405             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7406                 if (print)
7407                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7408                 break;
7409             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7410                 if (print)
7411                     bxe_print_next_block(sc, par_num++, "CFC");
7412                 break;
7413             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7414                 if (print)
7415                     bxe_print_next_block(sc, par_num++, "CDU");
7416                 break;
7417             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7418                 if (print)
7419                     bxe_print_next_block(sc, par_num++, "DMAE");
7420                 break;
7421             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7422                 if (print)
7423                     bxe_print_next_block(sc, par_num++, "IGU");
7424                 break;
7425             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7426                 if (print)
7427                     bxe_print_next_block(sc, par_num++, "MISC");
7428                 break;
7429             }
7430
7431             /* Clear the bit */
7432             sig &= ~cur_bit;
7433         }
7434     }
7435
7436     return (par_num);
7437 }
7438
7439 static int
7440 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7441                               uint32_t         sig,
7442                               int              par_num,
7443                               uint8_t          *global,
7444                               uint8_t          print)
7445 {
7446     uint32_t cur_bit = 0;
7447     int i = 0;
7448
7449     for (i = 0; sig; i++) {
7450         cur_bit = ((uint32_t)0x1 << i);
7451         if (sig & cur_bit) {
7452             switch (cur_bit) {
7453             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7454                 if (print)
7455                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7456                 *global = TRUE;
7457                 break;
7458             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7459                 if (print)
7460                     bxe_print_next_block(sc, par_num++,
7461                               "MCP UMP RX");
7462                 *global = TRUE;
7463                 break;
7464             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7465                 if (print)
7466                     bxe_print_next_block(sc, par_num++,
7467                               "MCP UMP TX");
7468                 *global = TRUE;
7469                 break;
7470             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7471                 if (print)
7472                     bxe_print_next_block(sc, par_num++,
7473                               "MCP SCPAD");
7474                 *global = TRUE;
7475                 break;
7476             }
7477
7478             /* Clear the bit */
7479             sig &= ~cur_bit;
7480         }
7481     }
7482
7483     return (par_num);
7484 }
7485
7486 static int
7487 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7488                               uint32_t         sig,
7489                               int              par_num,
7490                               uint8_t          print)
7491 {
7492     uint32_t cur_bit = 0;
7493     int i = 0;
7494
7495     for (i = 0; sig; i++) {
7496         cur_bit = ((uint32_t)0x1 << i);
7497         if (sig & cur_bit) {
7498             switch (cur_bit) {
7499             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7500                 if (print)
7501                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7502                 break;
7503             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7504                 if (print)
7505                     bxe_print_next_block(sc, par_num++, "ATC");
7506                 break;
7507             }
7508
7509             /* Clear the bit */
7510             sig &= ~cur_bit;
7511         }
7512     }
7513
7514     return (par_num);
7515 }
7516
7517 static uint8_t
7518 bxe_parity_attn(struct bxe_softc *sc,
7519                 uint8_t          *global,
7520                 uint8_t          print,
7521                 uint32_t         *sig)
7522 {
7523     int par_num = 0;
7524
7525     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7526         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7527         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7528         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7529         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7530         BLOGE(sc, "Parity error: HW block parity attention:\n"
7531                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7532               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7533               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7534               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7535               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7536               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7537
7538         if (print)
7539             BLOGI(sc, "Parity errors detected in blocks: ");
7540
7541         par_num =
7542             bxe_check_blocks_with_parity0(sc, sig[0] &
7543                                           HW_PRTY_ASSERT_SET_0,
7544                                           par_num, print);
7545         par_num =
7546             bxe_check_blocks_with_parity1(sc, sig[1] &
7547                                           HW_PRTY_ASSERT_SET_1,
7548                                           par_num, global, print);
7549         par_num =
7550             bxe_check_blocks_with_parity2(sc, sig[2] &
7551                                           HW_PRTY_ASSERT_SET_2,
7552                                           par_num, print);
7553         par_num =
7554             bxe_check_blocks_with_parity3(sc, sig[3] &
7555                                           HW_PRTY_ASSERT_SET_3,
7556                                           par_num, global, print);
7557         par_num =
7558             bxe_check_blocks_with_parity4(sc, sig[4] &
7559                                           HW_PRTY_ASSERT_SET_4,
7560                                           par_num, print);
7561
7562         if (print)
7563             BLOGI(sc, "\n");
7564
7565         return (TRUE);
7566     }
7567
7568     return (FALSE);
7569 }
7570
7571 static uint8_t
7572 bxe_chk_parity_attn(struct bxe_softc *sc,
7573                     uint8_t          *global,
7574                     uint8_t          print)
7575 {
7576     struct attn_route attn = { {0} };
7577     int port = SC_PORT(sc);
7578
7579     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7580     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7581     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7582     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7583
7584     /*
7585      * Since MCP attentions can't be disabled inside the block, we need to
7586      * read AEU registers to see whether they're currently disabled
7587      */
7588     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7589                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7590                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7591                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7592
7593
7594     if (!CHIP_IS_E1x(sc))
7595         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7596
7597     return (bxe_parity_attn(sc, global, print, attn.sig));
7598 }
7599
7600 static void
7601 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7602                          uint32_t         attn)
7603 {
7604     uint32_t val;
7605
7606     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7607         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7608         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7609         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7610             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7611         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7612             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7613         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7614             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7615         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7616             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7617         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7618             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7619         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7620             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7621         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7622             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7623         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7624             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7625         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7626             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7627     }
7628
7629     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7630         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7631         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7632         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7633             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7634         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7635             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7636         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7637             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7638         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7639             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7640         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7641             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7642         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7643             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7644     }
7645
7646     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7647                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7648         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7649               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7650                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7651     }
7652 }
7653
7654 static void
7655 bxe_e1h_disable(struct bxe_softc *sc)
7656 {
7657     int port = SC_PORT(sc);
7658
7659     bxe_tx_disable(sc);
7660
7661     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7662 }
7663
7664 static void
7665 bxe_e1h_enable(struct bxe_softc *sc)
7666 {
7667     int port = SC_PORT(sc);
7668
7669     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7670
7671     // XXX bxe_tx_enable(sc);
7672 }
7673
7674 /*
7675  * called due to MCP event (on pmf):
7676  *   reread new bandwidth configuration
7677  *   configure FW
7678  *   notify others function about the change
7679  */
7680 static void
7681 bxe_config_mf_bw(struct bxe_softc *sc)
7682 {
7683     if (sc->link_vars.link_up) {
7684         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7685         // XXX bxe_link_sync_notify(sc);
7686     }
7687
7688     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7689 }
7690
7691 static void
7692 bxe_set_mf_bw(struct bxe_softc *sc)
7693 {
7694     bxe_config_mf_bw(sc);
7695     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7696 }
7697
7698 static void
7699 bxe_handle_eee_event(struct bxe_softc *sc)
7700 {
7701     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7702     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7703 }
7704
7705 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7706
7707 static void
7708 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7709 {
7710     struct eth_stats_info *ether_stat =
7711         &sc->sp->drv_info_to_mcp.ether_stat;
7712
7713     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7714             ETH_STAT_INFO_VERSION_LEN);
7715
7716     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7717     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7718                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7719                                           ether_stat->mac_local + MAC_PAD,
7720                                           MAC_PAD, ETH_ALEN);
7721
7722     ether_stat->mtu_size = sc->mtu;
7723
7724     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7725     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7726         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7727     }
7728
7729     // XXX ether_stat->feature_flags |= ???;
7730
7731     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7732
7733     ether_stat->txq_size = sc->tx_ring_size;
7734     ether_stat->rxq_size = sc->rx_ring_size;
7735 }
7736
7737 static void
7738 bxe_handle_drv_info_req(struct bxe_softc *sc)
7739 {
7740     enum drv_info_opcode op_code;
7741     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7742
7743     /* if drv_info version supported by MFW doesn't match - send NACK */
7744     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7745         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7746         return;
7747     }
7748
7749     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7750                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7751
7752     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7753
7754     switch (op_code) {
7755     case ETH_STATS_OPCODE:
7756         bxe_drv_info_ether_stat(sc);
7757         break;
7758     case FCOE_STATS_OPCODE:
7759     case ISCSI_STATS_OPCODE:
7760     default:
7761         /* if op code isn't supported - send NACK */
7762         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7763         return;
7764     }
7765
7766     /*
7767      * If we got drv_info attn from MFW then these fields are defined in
7768      * shmem2 for sure
7769      */
7770     SHMEM2_WR(sc, drv_info_host_addr_lo,
7771               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7772     SHMEM2_WR(sc, drv_info_host_addr_hi,
7773               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7774
7775     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7776 }
7777
7778 static void
7779 bxe_dcc_event(struct bxe_softc *sc,
7780               uint32_t         dcc_event)
7781 {
7782     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7783
7784     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7785         /*
7786          * This is the only place besides the function initialization
7787          * where the sc->flags can change so it is done without any
7788          * locks
7789          */
7790         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7791             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7792             sc->flags |= BXE_MF_FUNC_DIS;
7793             bxe_e1h_disable(sc);
7794         } else {
7795             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7796             sc->flags &= ~BXE_MF_FUNC_DIS;
7797             bxe_e1h_enable(sc);
7798         }
7799         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7800     }
7801
7802     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7803         bxe_config_mf_bw(sc);
7804         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7805     }
7806
7807     /* Report results to MCP */
7808     if (dcc_event)
7809         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7810     else
7811         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7812 }
7813
7814 static void
7815 bxe_pmf_update(struct bxe_softc *sc)
7816 {
7817     int port = SC_PORT(sc);
7818     uint32_t val;
7819
7820     sc->port.pmf = 1;
7821     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7822
7823     /*
7824      * We need the mb() to ensure the ordering between the writing to
7825      * sc->port.pmf here and reading it from the bxe_periodic_task().
7826      */
7827     mb();
7828
7829     /* queue a periodic task */
7830     // XXX schedule task...
7831
7832     // XXX bxe_dcbx_pmf_update(sc);
7833
7834     /* enable nig attention */
7835     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7836     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7837         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7838         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7839     } else if (!CHIP_IS_E1x(sc)) {
7840         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7841         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7842     }
7843
7844     bxe_stats_handle(sc, STATS_EVENT_PMF);
7845 }
7846
7847 static int
7848 bxe_mc_assert(struct bxe_softc *sc)
7849 {
7850     char last_idx;
7851     int i, rc = 0;
7852     uint32_t row0, row1, row2, row3;
7853
7854     /* XSTORM */
7855     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7856     if (last_idx)
7857         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7858
7859     /* print the asserts */
7860     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7861
7862         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7863         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7864         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7865         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7866
7867         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7868             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7869                   i, row3, row2, row1, row0);
7870             rc++;
7871         } else {
7872             break;
7873         }
7874     }
7875
7876     /* TSTORM */
7877     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7878     if (last_idx) {
7879         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7880     }
7881
7882     /* print the asserts */
7883     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7884
7885         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7886         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7887         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7888         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7889
7890         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7891             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7892                   i, row3, row2, row1, row0);
7893             rc++;
7894         } else {
7895             break;
7896         }
7897     }
7898
7899     /* CSTORM */
7900     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7901     if (last_idx) {
7902         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7903     }
7904
7905     /* print the asserts */
7906     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7907
7908         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7909         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7910         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7911         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7912
7913         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7914             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7915                   i, row3, row2, row1, row0);
7916             rc++;
7917         } else {
7918             break;
7919         }
7920     }
7921
7922     /* USTORM */
7923     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7924     if (last_idx) {
7925         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7926     }
7927
7928     /* print the asserts */
7929     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7930
7931         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7932         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7933         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7934         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7935
7936         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7937             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7938                   i, row3, row2, row1, row0);
7939             rc++;
7940         } else {
7941             break;
7942         }
7943     }
7944
7945     return (rc);
7946 }
7947
7948 static void
7949 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7950                          uint32_t         attn)
7951 {
7952     int func = SC_FUNC(sc);
7953     uint32_t val;
7954
7955     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7956
7957         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7958
7959             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7960             bxe_read_mf_cfg(sc);
7961             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7962                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7963             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7964
7965             if (val & DRV_STATUS_DCC_EVENT_MASK)
7966                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7967
7968             if (val & DRV_STATUS_SET_MF_BW)
7969                 bxe_set_mf_bw(sc);
7970
7971             if (val & DRV_STATUS_DRV_INFO_REQ)
7972                 bxe_handle_drv_info_req(sc);
7973
7974             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7975                 bxe_pmf_update(sc);
7976
7977             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7978                 bxe_handle_eee_event(sc);
7979
7980             if (sc->link_vars.periodic_flags &
7981                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7982                 /* sync with link */
7983                 bxe_acquire_phy_lock(sc);
7984                 sc->link_vars.periodic_flags &=
7985                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7986                 bxe_release_phy_lock(sc);
7987                 if (IS_MF(sc))
7988                     ; // XXX bxe_link_sync_notify(sc);
7989                 bxe_link_report(sc);
7990             }
7991
7992             /*
7993              * Always call it here: bxe_link_report() will
7994              * prevent the link indication duplication.
7995              */
7996             bxe_link_status_update(sc);
7997
7998         } else if (attn & BXE_MC_ASSERT_BITS) {
7999
8000             BLOGE(sc, "MC assert!\n");
8001             bxe_mc_assert(sc);
8002             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8003             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8004             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8005             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8006             bxe_panic(sc, ("MC assert!\n"));
8007
8008         } else if (attn & BXE_MCP_ASSERT) {
8009
8010             BLOGE(sc, "MCP assert!\n");
8011             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8012             // XXX bxe_fw_dump(sc);
8013
8014         } else {
8015             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8016         }
8017     }
8018
8019     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8020         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8021         if (attn & BXE_GRC_TIMEOUT) {
8022             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8023             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8024         }
8025         if (attn & BXE_GRC_RSV) {
8026             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8027             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8028         }
8029         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8030     }
8031 }
8032
8033 static void
8034 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8035                          uint32_t         attn)
8036 {
8037     int port = SC_PORT(sc);
8038     int reg_offset;
8039     uint32_t val0, mask0, val1, mask1;
8040     uint32_t val;
8041
8042     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8043         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8044         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8045         /* CFC error attention */
8046         if (val & 0x2) {
8047             BLOGE(sc, "FATAL error from CFC\n");
8048         }
8049     }
8050
8051     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8052         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8053         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8054         /* RQ_USDMDP_FIFO_OVERFLOW */
8055         if (val & 0x18000) {
8056             BLOGE(sc, "FATAL error from PXP\n");
8057         }
8058
8059         if (!CHIP_IS_E1x(sc)) {
8060             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8061             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8062         }
8063     }
8064
8065 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8066 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8067
8068     if (attn & AEU_PXP2_HW_INT_BIT) {
8069         /*  CQ47854 workaround do not panic on
8070          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8071          */
8072         if (!CHIP_IS_E1x(sc)) {
8073             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8074             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8075             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8076             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8077             /*
8078              * If the olny PXP2_EOP_ERROR_BIT is set in
8079              * STS0 and STS1 - clear it
8080              *
8081              * probably we lose additional attentions between
8082              * STS0 and STS_CLR0, in this case user will not
8083              * be notified about them
8084              */
8085             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8086                 !(val1 & mask1))
8087                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8088
8089             /* print the register, since no one can restore it */
8090             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8091
8092             /*
8093              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8094              * then notify
8095              */
8096             if (val0 & PXP2_EOP_ERROR_BIT) {
8097                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8098
8099                 /*
8100                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8101                  * set then clear attention from PXP2 block without panic
8102                  */
8103                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8104                     ((val1 & mask1) == 0))
8105                     attn &= ~AEU_PXP2_HW_INT_BIT;
8106             }
8107         }
8108     }
8109
8110     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8111         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8112                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8113
8114         val = REG_RD(sc, reg_offset);
8115         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8116         REG_WR(sc, reg_offset, val);
8117
8118         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8119               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8120         bxe_panic(sc, ("HW block attention set2\n"));
8121     }
8122 }
8123
8124 static void
8125 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8126                          uint32_t         attn)
8127 {
8128     int port = SC_PORT(sc);
8129     int reg_offset;
8130     uint32_t val;
8131
8132     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8133         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8134         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8135         /* DORQ discard attention */
8136         if (val & 0x2) {
8137             BLOGE(sc, "FATAL error from DORQ\n");
8138         }
8139     }
8140
8141     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8142         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8143                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8144
8145         val = REG_RD(sc, reg_offset);
8146         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8147         REG_WR(sc, reg_offset, val);
8148
8149         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8150               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8151         bxe_panic(sc, ("HW block attention set1\n"));
8152     }
8153 }
8154
8155 static void
8156 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8157                          uint32_t         attn)
8158 {
8159     int port = SC_PORT(sc);
8160     int reg_offset;
8161     uint32_t val;
8162
8163     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8164                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8165
8166     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8167         val = REG_RD(sc, reg_offset);
8168         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8169         REG_WR(sc, reg_offset, val);
8170
8171         BLOGW(sc, "SPIO5 hw attention\n");
8172
8173         /* Fan failure attention */
8174         elink_hw_reset_phy(&sc->link_params);
8175         bxe_fan_failure(sc);
8176     }
8177
8178     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8179         bxe_acquire_phy_lock(sc);
8180         elink_handle_module_detect_int(&sc->link_params);
8181         bxe_release_phy_lock(sc);
8182     }
8183
8184     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8185         val = REG_RD(sc, reg_offset);
8186         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8187         REG_WR(sc, reg_offset, val);
8188
8189         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8190                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8191     }
8192 }
8193
8194 static void
8195 bxe_attn_int_deasserted(struct bxe_softc *sc,
8196                         uint32_t         deasserted)
8197 {
8198     struct attn_route attn;
8199     struct attn_route *group_mask;
8200     int port = SC_PORT(sc);
8201     int index;
8202     uint32_t reg_addr;
8203     uint32_t val;
8204     uint32_t aeu_mask;
8205     uint8_t global = FALSE;
8206
8207     /*
8208      * Need to take HW lock because MCP or other port might also
8209      * try to handle this event.
8210      */
8211     bxe_acquire_alr(sc);
8212
8213     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8214         /* XXX
8215          * In case of parity errors don't handle attentions so that
8216          * other function would "see" parity errors.
8217          */
8218         sc->recovery_state = BXE_RECOVERY_INIT;
8219         // XXX schedule a recovery task...
8220         /* disable HW interrupts */
8221         bxe_int_disable(sc);
8222         bxe_release_alr(sc);
8223         return;
8224     }
8225
8226     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8227     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8228     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8229     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8230     if (!CHIP_IS_E1x(sc)) {
8231         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8232     } else {
8233         attn.sig[4] = 0;
8234     }
8235
8236     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8237           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8238
8239     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8240         if (deasserted & (1 << index)) {
8241             group_mask = &sc->attn_group[index];
8242
8243             BLOGD(sc, DBG_INTR,
8244                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8245                   group_mask->sig[0], group_mask->sig[1],
8246                   group_mask->sig[2], group_mask->sig[3],
8247                   group_mask->sig[4]);
8248
8249             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8250             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8251             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8252             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8253             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8254         }
8255     }
8256
8257     bxe_release_alr(sc);
8258
8259     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8260         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8261                     COMMAND_REG_ATTN_BITS_CLR);
8262     } else {
8263         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8264     }
8265
8266     val = ~deasserted;
8267     BLOGD(sc, DBG_INTR,
8268           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8269           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8270     REG_WR(sc, reg_addr, val);
8271
8272     if (~sc->attn_state & deasserted) {
8273         BLOGE(sc, "IGU error\n");
8274     }
8275
8276     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8277                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8278
8279     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8280
8281     aeu_mask = REG_RD(sc, reg_addr);
8282
8283     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8284           aeu_mask, deasserted);
8285     aeu_mask |= (deasserted & 0x3ff);
8286     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8287
8288     REG_WR(sc, reg_addr, aeu_mask);
8289     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8290
8291     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8292     sc->attn_state &= ~deasserted;
8293     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8294 }
8295
8296 static void
8297 bxe_attn_int(struct bxe_softc *sc)
8298 {
8299     /* read local copy of bits */
8300     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8301     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8302     uint32_t attn_state = sc->attn_state;
8303
8304     /* look for changed bits */
8305     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8306     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8307
8308     BLOGD(sc, DBG_INTR,
8309           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8310           attn_bits, attn_ack, asserted, deasserted);
8311
8312     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8313         BLOGE(sc, "BAD attention state\n");
8314     }
8315
8316     /* handle bits that were raised */
8317     if (asserted) {
8318         bxe_attn_int_asserted(sc, asserted);
8319     }
8320
8321     if (deasserted) {
8322         bxe_attn_int_deasserted(sc, deasserted);
8323     }
8324 }
8325
8326 static uint16_t
8327 bxe_update_dsb_idx(struct bxe_softc *sc)
8328 {
8329     struct host_sp_status_block *def_sb = sc->def_sb;
8330     uint16_t rc = 0;
8331
8332     mb(); /* status block is written to by the chip */
8333
8334     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8335         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8336         rc |= BXE_DEF_SB_ATT_IDX;
8337     }
8338
8339     if (sc->def_idx != def_sb->sp_sb.running_index) {
8340         sc->def_idx = def_sb->sp_sb.running_index;
8341         rc |= BXE_DEF_SB_IDX;
8342     }
8343
8344     mb();
8345
8346     return (rc);
8347 }
8348
8349 static inline struct ecore_queue_sp_obj *
8350 bxe_cid_to_q_obj(struct bxe_softc *sc,
8351                  uint32_t         cid)
8352 {
8353     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8354     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8355 }
8356
8357 static void
8358 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8359 {
8360     struct ecore_mcast_ramrod_params rparam;
8361     int rc;
8362
8363     memset(&rparam, 0, sizeof(rparam));
8364
8365     rparam.mcast_obj = &sc->mcast_obj;
8366
8367     BXE_MCAST_LOCK(sc);
8368
8369     /* clear pending state for the last command */
8370     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8371
8372     /* if there are pending mcast commands - send them */
8373     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8374         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8375         if (rc < 0) {
8376             BLOGD(sc, DBG_SP,
8377                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8378         }
8379     }
8380
8381     BXE_MCAST_UNLOCK(sc);
8382 }
8383
8384 static void
8385 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8386                               union event_ring_elem *elem)
8387 {
8388     unsigned long ramrod_flags = 0;
8389     int rc = 0;
8390     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8391     struct ecore_vlan_mac_obj *vlan_mac_obj;
8392
8393     /* always push next commands out, don't wait here */
8394     bit_set(&ramrod_flags, RAMROD_CONT);
8395
8396     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8397     case ECORE_FILTER_MAC_PENDING:
8398         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8399         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8400         break;
8401
8402     case ECORE_FILTER_MCAST_PENDING:
8403         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8404         /*
8405          * This is only relevant for 57710 where multicast MACs are
8406          * configured as unicast MACs using the same ramrod.
8407          */
8408         bxe_handle_mcast_eqe(sc);
8409         return;
8410
8411     default:
8412         BLOGE(sc, "Unsupported classification command: %d\n",
8413               elem->message.data.eth_event.echo);
8414         return;
8415     }
8416
8417     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8418
8419     if (rc < 0) {
8420         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8421     } else if (rc > 0) {
8422         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8423     }
8424 }
8425
8426 static void
8427 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8428                        union event_ring_elem *elem)
8429 {
8430     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8431
8432     /* send rx_mode command again if was requested */
8433     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8434                                &sc->sp_state)) {
8435         bxe_set_storm_rx_mode(sc);
8436     }
8437 }
8438
8439 static void
8440 bxe_update_eq_prod(struct bxe_softc *sc,
8441                    uint16_t         prod)
8442 {
8443     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8444     wmb(); /* keep prod updates ordered */
8445 }
8446
8447 static void
8448 bxe_eq_int(struct bxe_softc *sc)
8449 {
8450     uint16_t hw_cons, sw_cons, sw_prod;
8451     union event_ring_elem *elem;
8452     uint8_t echo;
8453     uint32_t cid;
8454     uint8_t opcode;
8455     int spqe_cnt = 0;
8456     struct ecore_queue_sp_obj *q_obj;
8457     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8458     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8459
8460     hw_cons = le16toh(*sc->eq_cons_sb);
8461
8462     /*
8463      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8464      * when we get to the next-page we need to adjust so the loop
8465      * condition below will be met. The next element is the size of a
8466      * regular element and hence incrementing by 1
8467      */
8468     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8469         hw_cons++;
8470     }
8471
8472     /*
8473      * This function may never run in parallel with itself for a
8474      * specific sc and no need for a read memory barrier here.
8475      */
8476     sw_cons = sc->eq_cons;
8477     sw_prod = sc->eq_prod;
8478
8479     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8480           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8481
8482     for (;
8483          sw_cons != hw_cons;
8484          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8485
8486         elem = &sc->eq[EQ_DESC(sw_cons)];
8487
8488         /* elem CID originates from FW, actually LE */
8489         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8490         opcode = elem->message.opcode;
8491
8492         /* handle eq element */
8493         switch (opcode) {
8494
8495         case EVENT_RING_OPCODE_STAT_QUERY:
8496             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8497                   sc->stats_comp++);
8498             /* nothing to do with stats comp */
8499             goto next_spqe;
8500
8501         case EVENT_RING_OPCODE_CFC_DEL:
8502             /* handle according to cid range */
8503             /* we may want to verify here that the sc state is HALTING */
8504             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8505             q_obj = bxe_cid_to_q_obj(sc, cid);
8506             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8507                 break;
8508             }
8509             goto next_spqe;
8510
8511         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8512             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8513             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8514                 break;
8515             }
8516             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8517             goto next_spqe;
8518
8519         case EVENT_RING_OPCODE_START_TRAFFIC:
8520             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8521             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8522                 break;
8523             }
8524             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8525             goto next_spqe;
8526
8527         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8528             echo = elem->message.data.function_update_event.echo;
8529             if (echo == SWITCH_UPDATE) {
8530                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8531                 if (f_obj->complete_cmd(sc, f_obj,
8532                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8533                     break;
8534                 }
8535             }
8536             else {
8537                 BLOGD(sc, DBG_SP,
8538                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8539             }
8540             goto next_spqe;
8541
8542         case EVENT_RING_OPCODE_FORWARD_SETUP:
8543             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8544             if (q_obj->complete_cmd(sc, q_obj,
8545                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8546                 break;
8547             }
8548             goto next_spqe;
8549
8550         case EVENT_RING_OPCODE_FUNCTION_START:
8551             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8552             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8553                 break;
8554             }
8555             goto next_spqe;
8556
8557         case EVENT_RING_OPCODE_FUNCTION_STOP:
8558             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8559             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8560                 break;
8561             }
8562             goto next_spqe;
8563         }
8564
8565         switch (opcode | sc->state) {
8566         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8567         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8568             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8569             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8570             rss_raw->clear_pending(rss_raw);
8571             break;
8572
8573         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8574         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8575         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8576         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8577         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8578         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8579             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8580             bxe_handle_classification_eqe(sc, elem);
8581             break;
8582
8583         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8584         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8585         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8586             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8587             bxe_handle_mcast_eqe(sc);
8588             break;
8589
8590         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8591         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8592         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8593             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8594             bxe_handle_rx_mode_eqe(sc, elem);
8595             break;
8596
8597         default:
8598             /* unknown event log error and continue */
8599             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8600                   elem->message.opcode, sc->state);
8601         }
8602
8603 next_spqe:
8604         spqe_cnt++;
8605     } /* for */
8606
8607     mb();
8608     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8609
8610     sc->eq_cons = sw_cons;
8611     sc->eq_prod = sw_prod;
8612
8613     /* make sure that above mem writes were issued towards the memory */
8614     wmb();
8615
8616     /* update producer */
8617     bxe_update_eq_prod(sc, sc->eq_prod);
8618 }
8619
8620 static void
8621 bxe_handle_sp_tq(void *context,
8622                  int  pending)
8623 {
8624     struct bxe_softc *sc = (struct bxe_softc *)context;
8625     uint16_t status;
8626
8627     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8628
8629     /* what work needs to be performed? */
8630     status = bxe_update_dsb_idx(sc);
8631
8632     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8633
8634     /* HW attentions */
8635     if (status & BXE_DEF_SB_ATT_IDX) {
8636         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8637         bxe_attn_int(sc);
8638         status &= ~BXE_DEF_SB_ATT_IDX;
8639     }
8640
8641     /* SP events: STAT_QUERY and others */
8642     if (status & BXE_DEF_SB_IDX) {
8643         /* handle EQ completions */
8644         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8645         bxe_eq_int(sc);
8646         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8647                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8648         status &= ~BXE_DEF_SB_IDX;
8649     }
8650
8651     /* if status is non zero then something went wrong */
8652     if (__predict_false(status)) {
8653         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8654     }
8655
8656     /* ack status block only if something was actually handled */
8657     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8658                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8659
8660     /*
8661      * Must be called after the EQ processing (since eq leads to sriov
8662      * ramrod completion flows).
8663      * This flow may have been scheduled by the arrival of a ramrod
8664      * completion, or by the sriov code rescheduling itself.
8665      */
8666     // XXX bxe_iov_sp_task(sc);
8667
8668 }
8669
8670 static void
8671 bxe_handle_fp_tq(void *context,
8672                  int  pending)
8673 {
8674     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8675     struct bxe_softc *sc = fp->sc;
8676     uint8_t more_tx = FALSE;
8677     uint8_t more_rx = FALSE;
8678
8679     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8680
8681     /* XXX
8682      * IFF_DRV_RUNNING state can't be checked here since we process
8683      * slowpath events on a client queue during setup. Instead
8684      * we need to add a "process/continue" flag here that the driver
8685      * can use to tell the task here not to do anything.
8686      */
8687 #if 0
8688     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8689         return;
8690     }
8691 #endif
8692
8693     /* update the fastpath index */
8694     bxe_update_fp_sb_idx(fp);
8695
8696     /* XXX add loop here if ever support multiple tx CoS */
8697     /* fp->txdata[cos] */
8698     if (bxe_has_tx_work(fp)) {
8699         BXE_FP_TX_LOCK(fp);
8700         more_tx = bxe_txeof(sc, fp);
8701         BXE_FP_TX_UNLOCK(fp);
8702     }
8703
8704     if (bxe_has_rx_work(fp)) {
8705         more_rx = bxe_rxeof(sc, fp);
8706     }
8707
8708     if (more_rx /*|| more_tx*/) {
8709         /* still more work to do */
8710         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8711         return;
8712     }
8713
8714     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8715                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8716 }
8717
8718 static void
8719 bxe_task_fp(struct bxe_fastpath *fp)
8720 {
8721     struct bxe_softc *sc = fp->sc;
8722     uint8_t more_tx = FALSE;
8723     uint8_t more_rx = FALSE;
8724
8725     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8726
8727     /* update the fastpath index */
8728     bxe_update_fp_sb_idx(fp);
8729
8730     /* XXX add loop here if ever support multiple tx CoS */
8731     /* fp->txdata[cos] */
8732     if (bxe_has_tx_work(fp)) {
8733         BXE_FP_TX_LOCK(fp);
8734         more_tx = bxe_txeof(sc, fp);
8735         BXE_FP_TX_UNLOCK(fp);
8736     }
8737
8738     if (bxe_has_rx_work(fp)) {
8739         more_rx = bxe_rxeof(sc, fp);
8740     }
8741
8742     if (more_rx /*|| more_tx*/) {
8743         /* still more work to do, bail out if this ISR and process later */
8744         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8745         return;
8746     }
8747
8748     /*
8749      * Here we write the fastpath index taken before doing any tx or rx work.
8750      * It is very well possible other hw events occurred up to this point and
8751      * they were actually processed accordingly above. Since we're going to
8752      * write an older fastpath index, an interrupt is coming which we might
8753      * not do any work in.
8754      */
8755     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8756                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8757 }
8758
8759 /*
8760  * Legacy interrupt entry point.
8761  *
8762  * Verifies that the controller generated the interrupt and
8763  * then calls a separate routine to handle the various
8764  * interrupt causes: link, RX, and TX.
8765  */
8766 static void
8767 bxe_intr_legacy(void *xsc)
8768 {
8769     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8770     struct bxe_fastpath *fp;
8771     uint16_t status, mask;
8772     int i;
8773
8774     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8775
8776     /*
8777      * 0 for ustorm, 1 for cstorm
8778      * the bits returned from ack_int() are 0-15
8779      * bit 0 = attention status block
8780      * bit 1 = fast path status block
8781      * a mask of 0x2 or more = tx/rx event
8782      * a mask of 1 = slow path event
8783      */
8784
8785     status = bxe_ack_int(sc);
8786
8787     /* the interrupt is not for us */
8788     if (__predict_false(status == 0)) {
8789         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8790         return;
8791     }
8792
8793     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8794
8795     FOR_EACH_ETH_QUEUE(sc, i) {
8796         fp = &sc->fp[i];
8797         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8798         if (status & mask) {
8799             /* acknowledge and disable further fastpath interrupts */
8800             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8801             bxe_task_fp(fp);
8802             status &= ~mask;
8803         }
8804     }
8805
8806     if (__predict_false(status & 0x1)) {
8807         /* acknowledge and disable further slowpath interrupts */
8808         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8809
8810         /* schedule slowpath handler */
8811         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8812
8813         status &= ~0x1;
8814     }
8815
8816     if (__predict_false(status)) {
8817         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8818     }
8819 }
8820
8821 /* slowpath interrupt entry point */
8822 static void
8823 bxe_intr_sp(void *xsc)
8824 {
8825     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8826
8827     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8828
8829     /* acknowledge and disable further slowpath interrupts */
8830     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8831
8832     /* schedule slowpath handler */
8833     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8834 }
8835
8836 /* fastpath interrupt entry point */
8837 static void
8838 bxe_intr_fp(void *xfp)
8839 {
8840     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8841     struct bxe_softc *sc = fp->sc;
8842
8843     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8844
8845     BLOGD(sc, DBG_INTR,
8846           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8847           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8848
8849     /* acknowledge and disable further fastpath interrupts */
8850     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8851
8852     bxe_task_fp(fp);
8853 }
8854
8855 /* Release all interrupts allocated by the driver. */
8856 static void
8857 bxe_interrupt_free(struct bxe_softc *sc)
8858 {
8859     int i;
8860
8861     switch (sc->interrupt_mode) {
8862     case INTR_MODE_INTX:
8863         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8864         if (sc->intr[0].resource != NULL) {
8865             bus_release_resource(sc->dev,
8866                                  SYS_RES_IRQ,
8867                                  sc->intr[0].rid,
8868                                  sc->intr[0].resource);
8869         }
8870         break;
8871     case INTR_MODE_MSI:
8872         for (i = 0; i < sc->intr_count; i++) {
8873             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8874             if (sc->intr[i].resource && sc->intr[i].rid) {
8875                 bus_release_resource(sc->dev,
8876                                      SYS_RES_IRQ,
8877                                      sc->intr[i].rid,
8878                                      sc->intr[i].resource);
8879             }
8880         }
8881         pci_release_msi(sc->dev);
8882         break;
8883     case INTR_MODE_MSIX:
8884         for (i = 0; i < sc->intr_count; i++) {
8885             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8886             if (sc->intr[i].resource && sc->intr[i].rid) {
8887                 bus_release_resource(sc->dev,
8888                                      SYS_RES_IRQ,
8889                                      sc->intr[i].rid,
8890                                      sc->intr[i].resource);
8891             }
8892         }
8893         pci_release_msi(sc->dev);
8894         break;
8895     default:
8896         /* nothing to do as initial allocation failed */
8897         break;
8898     }
8899 }
8900
8901 /*
8902  * This function determines and allocates the appropriate
8903  * interrupt based on system capabilites and user request.
8904  *
8905  * The user may force a particular interrupt mode, specify
8906  * the number of receive queues, specify the method for
8907  * distribuitng received frames to receive queues, or use
8908  * the default settings which will automatically select the
8909  * best supported combination.  In addition, the OS may or
8910  * may not support certain combinations of these settings.
8911  * This routine attempts to reconcile the settings requested
8912  * by the user with the capabilites available from the system
8913  * to select the optimal combination of features.
8914  *
8915  * Returns:
8916  *   0 = Success, !0 = Failure.
8917  */
8918 static int
8919 bxe_interrupt_alloc(struct bxe_softc *sc)
8920 {
8921     int msix_count = 0;
8922     int msi_count = 0;
8923     int num_requested = 0;
8924     int num_allocated = 0;
8925     int rid, i, j;
8926     int rc;
8927
8928     /* get the number of available MSI/MSI-X interrupts from the OS */
8929     if (sc->interrupt_mode > 0) {
8930         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8931             msix_count = pci_msix_count(sc->dev);
8932         }
8933
8934         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8935             msi_count = pci_msi_count(sc->dev);
8936         }
8937
8938         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8939               msi_count, msix_count);
8940     }
8941
8942     do { /* try allocating MSI-X interrupt resources (at least 2) */
8943         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8944             break;
8945         }
8946
8947         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8948             (msix_count < 2)) {
8949             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8950             break;
8951         }
8952
8953         /* ask for the necessary number of MSI-X vectors */
8954         num_requested = min((sc->num_queues + 1), msix_count);
8955
8956         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8957
8958         num_allocated = num_requested;
8959         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8960             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8961             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8962             break;
8963         }
8964
8965         if (num_allocated < 2) { /* possible? */
8966             BLOGE(sc, "MSI-X allocation less than 2!\n");
8967             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8968             pci_release_msi(sc->dev);
8969             break;
8970         }
8971
8972         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8973               num_requested, num_allocated);
8974
8975         /* best effort so use the number of vectors allocated to us */
8976         sc->intr_count = num_allocated;
8977         sc->num_queues = num_allocated - 1;
8978
8979         rid = 1; /* initial resource identifier */
8980
8981         /* allocate the MSI-X vectors */
8982         for (i = 0; i < num_allocated; i++) {
8983             sc->intr[i].rid = (rid + i);
8984
8985             if ((sc->intr[i].resource =
8986                  bus_alloc_resource_any(sc->dev,
8987                                         SYS_RES_IRQ,
8988                                         &sc->intr[i].rid,
8989                                         RF_ACTIVE)) == NULL) {
8990                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8991                       i, (rid + i));
8992
8993                 for (j = (i - 1); j >= 0; j--) {
8994                     bus_release_resource(sc->dev,
8995                                          SYS_RES_IRQ,
8996                                          sc->intr[j].rid,
8997                                          sc->intr[j].resource);
8998                 }
8999
9000                 sc->intr_count = 0;
9001                 sc->num_queues = 0;
9002                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9003                 pci_release_msi(sc->dev);
9004                 break;
9005             }
9006
9007             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9008         }
9009     } while (0);
9010
9011     do { /* try allocating MSI vector resources (at least 2) */
9012         if (sc->interrupt_mode != INTR_MODE_MSI) {
9013             break;
9014         }
9015
9016         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9017             (msi_count < 1)) {
9018             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9019             break;
9020         }
9021
9022         /* ask for a single MSI vector */
9023         num_requested = 1;
9024
9025         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9026
9027         num_allocated = num_requested;
9028         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9029             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9030             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9031             break;
9032         }
9033
9034         if (num_allocated != 1) { /* possible? */
9035             BLOGE(sc, "MSI allocation is not 1!\n");
9036             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9037             pci_release_msi(sc->dev);
9038             break;
9039         }
9040
9041         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9042               num_requested, num_allocated);
9043
9044         /* best effort so use the number of vectors allocated to us */
9045         sc->intr_count = num_allocated;
9046         sc->num_queues = num_allocated;
9047
9048         rid = 1; /* initial resource identifier */
9049
9050         sc->intr[0].rid = rid;
9051
9052         if ((sc->intr[0].resource =
9053              bus_alloc_resource_any(sc->dev,
9054                                     SYS_RES_IRQ,
9055                                     &sc->intr[0].rid,
9056                                     RF_ACTIVE)) == NULL) {
9057             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9058             sc->intr_count = 0;
9059             sc->num_queues = 0;
9060             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9061             pci_release_msi(sc->dev);
9062             break;
9063         }
9064
9065         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9066     } while (0);
9067
9068     do { /* try allocating INTx vector resources */
9069         if (sc->interrupt_mode != INTR_MODE_INTX) {
9070             break;
9071         }
9072
9073         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9074
9075         /* only one vector for INTx */
9076         sc->intr_count = 1;
9077         sc->num_queues = 1;
9078
9079         rid = 0; /* initial resource identifier */
9080
9081         sc->intr[0].rid = rid;
9082
9083         if ((sc->intr[0].resource =
9084              bus_alloc_resource_any(sc->dev,
9085                                     SYS_RES_IRQ,
9086                                     &sc->intr[0].rid,
9087                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9088             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9089             sc->intr_count = 0;
9090             sc->num_queues = 0;
9091             sc->interrupt_mode = -1; /* Failed! */
9092             break;
9093         }
9094
9095         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9096     } while (0);
9097
9098     if (sc->interrupt_mode == -1) {
9099         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9100         rc = 1;
9101     } else {
9102         BLOGD(sc, DBG_LOAD,
9103               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9104               sc->interrupt_mode, sc->num_queues);
9105         rc = 0;
9106     }
9107
9108     return (rc);
9109 }
9110
9111 static void
9112 bxe_interrupt_detach(struct bxe_softc *sc)
9113 {
9114     struct bxe_fastpath *fp;
9115     int i;
9116
9117     /* release interrupt resources */
9118     for (i = 0; i < sc->intr_count; i++) {
9119         if (sc->intr[i].resource && sc->intr[i].tag) {
9120             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9121             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9122         }
9123     }
9124
9125     for (i = 0; i < sc->num_queues; i++) {
9126         fp = &sc->fp[i];
9127         if (fp->tq) {
9128             taskqueue_drain(fp->tq, &fp->tq_task);
9129             taskqueue_drain(fp->tq, &fp->tx_task);
9130             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9131                 NULL))
9132                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9133             taskqueue_free(fp->tq);
9134             fp->tq = NULL;
9135         }
9136     }
9137
9138
9139     if (sc->sp_tq) {
9140         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9141         taskqueue_free(sc->sp_tq);
9142         sc->sp_tq = NULL;
9143     }
9144 }
9145
9146 /*
9147  * Enables interrupts and attach to the ISR.
9148  *
9149  * When using multiple MSI/MSI-X vectors the first vector
9150  * is used for slowpath operations while all remaining
9151  * vectors are used for fastpath operations.  If only a
9152  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9153  * ISR must look for both slowpath and fastpath completions.
9154  */
9155 static int
9156 bxe_interrupt_attach(struct bxe_softc *sc)
9157 {
9158     struct bxe_fastpath *fp;
9159     int rc = 0;
9160     int i;
9161
9162     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9163              "bxe%d_sp_tq", sc->unit);
9164     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9165     sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9166                                  taskqueue_thread_enqueue,
9167                                  &sc->sp_tq);
9168     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9169                             "%s", sc->sp_tq_name);
9170
9171
9172     for (i = 0; i < sc->num_queues; i++) {
9173         fp = &sc->fp[i];
9174         snprintf(fp->tq_name, sizeof(fp->tq_name),
9175                  "bxe%d_fp%d_tq", sc->unit, i);
9176         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9177         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9178         fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9179                                   taskqueue_thread_enqueue,
9180                                   &fp->tq);
9181         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9182                           bxe_tx_mq_start_deferred, fp);
9183         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9184                                 "%s", fp->tq_name);
9185     }
9186
9187     /* setup interrupt handlers */
9188     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9189         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9190
9191         /*
9192          * Setup the interrupt handler. Note that we pass the driver instance
9193          * to the interrupt handler for the slowpath.
9194          */
9195         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9196                                  (INTR_TYPE_NET | INTR_MPSAFE),
9197                                  NULL, bxe_intr_sp, sc,
9198                                  &sc->intr[0].tag)) != 0) {
9199             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9200             goto bxe_interrupt_attach_exit;
9201         }
9202
9203         bus_describe_intr(sc->dev, sc->intr[0].resource,
9204                           sc->intr[0].tag, "sp");
9205
9206         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9207
9208         /* initialize the fastpath vectors (note the first was used for sp) */
9209         for (i = 0; i < sc->num_queues; i++) {
9210             fp = &sc->fp[i];
9211             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9212
9213             /*
9214              * Setup the interrupt handler. Note that we pass the
9215              * fastpath context to the interrupt handler in this
9216              * case.
9217              */
9218             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9219                                      (INTR_TYPE_NET | INTR_MPSAFE),
9220                                      NULL, bxe_intr_fp, fp,
9221                                      &sc->intr[i + 1].tag)) != 0) {
9222                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9223                       (i + 1), rc);
9224                 goto bxe_interrupt_attach_exit;
9225             }
9226
9227             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9228                               sc->intr[i + 1].tag, "fp%02d", i);
9229
9230             /* bind the fastpath instance to a cpu */
9231             if (sc->num_queues > 1) {
9232                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9233             }
9234
9235             fp->state = BXE_FP_STATE_IRQ;
9236         }
9237     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9238         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9239
9240         /*
9241          * Setup the interrupt handler. Note that we pass the
9242          * driver instance to the interrupt handler which
9243          * will handle both the slowpath and fastpath.
9244          */
9245         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9246                                  (INTR_TYPE_NET | INTR_MPSAFE),
9247                                  NULL, bxe_intr_legacy, sc,
9248                                  &sc->intr[0].tag)) != 0) {
9249             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9250             goto bxe_interrupt_attach_exit;
9251         }
9252
9253     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9254         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9255
9256         /*
9257          * Setup the interrupt handler. Note that we pass the
9258          * driver instance to the interrupt handler which
9259          * will handle both the slowpath and fastpath.
9260          */
9261         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9262                                  (INTR_TYPE_NET | INTR_MPSAFE),
9263                                  NULL, bxe_intr_legacy, sc,
9264                                  &sc->intr[0].tag)) != 0) {
9265             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9266             goto bxe_interrupt_attach_exit;
9267         }
9268     }
9269
9270 bxe_interrupt_attach_exit:
9271
9272     return (rc);
9273 }
9274
9275 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9276 static int  bxe_init_hw_common(struct bxe_softc *sc);
9277 static int  bxe_init_hw_port(struct bxe_softc *sc);
9278 static int  bxe_init_hw_func(struct bxe_softc *sc);
9279 static void bxe_reset_common(struct bxe_softc *sc);
9280 static void bxe_reset_port(struct bxe_softc *sc);
9281 static void bxe_reset_func(struct bxe_softc *sc);
9282 static int  bxe_gunzip_init(struct bxe_softc *sc);
9283 static void bxe_gunzip_end(struct bxe_softc *sc);
9284 static int  bxe_init_firmware(struct bxe_softc *sc);
9285 static void bxe_release_firmware(struct bxe_softc *sc);
9286
9287 static struct
9288 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9289     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9290     .init_hw_cmn      = bxe_init_hw_common,
9291     .init_hw_port     = bxe_init_hw_port,
9292     .init_hw_func     = bxe_init_hw_func,
9293
9294     .reset_hw_cmn     = bxe_reset_common,
9295     .reset_hw_port    = bxe_reset_port,
9296     .reset_hw_func    = bxe_reset_func,
9297
9298     .gunzip_init      = bxe_gunzip_init,
9299     .gunzip_end       = bxe_gunzip_end,
9300
9301     .init_fw          = bxe_init_firmware,
9302     .release_fw       = bxe_release_firmware,
9303 };
9304
9305 static void
9306 bxe_init_func_obj(struct bxe_softc *sc)
9307 {
9308     sc->dmae_ready = 0;
9309
9310     ecore_init_func_obj(sc,
9311                         &sc->func_obj,
9312                         BXE_SP(sc, func_rdata),
9313                         BXE_SP_MAPPING(sc, func_rdata),
9314                         BXE_SP(sc, func_afex_rdata),
9315                         BXE_SP_MAPPING(sc, func_afex_rdata),
9316                         &bxe_func_sp_drv);
9317 }
9318
9319 static int
9320 bxe_init_hw(struct bxe_softc *sc,
9321             uint32_t         load_code)
9322 {
9323     struct ecore_func_state_params func_params = { NULL };
9324     int rc;
9325
9326     /* prepare the parameters for function state transitions */
9327     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9328
9329     func_params.f_obj = &sc->func_obj;
9330     func_params.cmd = ECORE_F_CMD_HW_INIT;
9331
9332     func_params.params.hw_init.load_phase = load_code;
9333
9334     /*
9335      * Via a plethora of function pointers, we will eventually reach
9336      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9337      */
9338     rc = ecore_func_state_change(sc, &func_params);
9339
9340     return (rc);
9341 }
9342
9343 static void
9344 bxe_fill(struct bxe_softc *sc,
9345          uint32_t         addr,
9346          int              fill,
9347          uint32_t         len)
9348 {
9349     uint32_t i;
9350
9351     if (!(len % 4) && !(addr % 4)) {
9352         for (i = 0; i < len; i += 4) {
9353             REG_WR(sc, (addr + i), fill);
9354         }
9355     } else {
9356         for (i = 0; i < len; i++) {
9357             REG_WR8(sc, (addr + i), fill);
9358         }
9359     }
9360 }
9361
9362 /* writes FP SP data to FW - data_size in dwords */
9363 static void
9364 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9365                   int              fw_sb_id,
9366                   uint32_t         *sb_data_p,
9367                   uint32_t         data_size)
9368 {
9369     int index;
9370
9371     for (index = 0; index < data_size; index++) {
9372         REG_WR(sc,
9373                (BAR_CSTRORM_INTMEM +
9374                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9375                 (sizeof(uint32_t) * index)),
9376                *(sb_data_p + index));
9377     }
9378 }
9379
9380 static void
9381 bxe_zero_fp_sb(struct bxe_softc *sc,
9382                int              fw_sb_id)
9383 {
9384     struct hc_status_block_data_e2 sb_data_e2;
9385     struct hc_status_block_data_e1x sb_data_e1x;
9386     uint32_t *sb_data_p;
9387     uint32_t data_size = 0;
9388
9389     if (!CHIP_IS_E1x(sc)) {
9390         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9391         sb_data_e2.common.state = SB_DISABLED;
9392         sb_data_e2.common.p_func.vf_valid = FALSE;
9393         sb_data_p = (uint32_t *)&sb_data_e2;
9394         data_size = (sizeof(struct hc_status_block_data_e2) /
9395                      sizeof(uint32_t));
9396     } else {
9397         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9398         sb_data_e1x.common.state = SB_DISABLED;
9399         sb_data_e1x.common.p_func.vf_valid = FALSE;
9400         sb_data_p = (uint32_t *)&sb_data_e1x;
9401         data_size = (sizeof(struct hc_status_block_data_e1x) /
9402                      sizeof(uint32_t));
9403     }
9404
9405     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9406
9407     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9408              0, CSTORM_STATUS_BLOCK_SIZE);
9409     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9410              0, CSTORM_SYNC_BLOCK_SIZE);
9411 }
9412
9413 static void
9414 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9415                   struct hc_sp_status_block_data *sp_sb_data)
9416 {
9417     int i;
9418
9419     for (i = 0;
9420          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9421          i++) {
9422         REG_WR(sc,
9423                (BAR_CSTRORM_INTMEM +
9424                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9425                 (i * sizeof(uint32_t))),
9426                *((uint32_t *)sp_sb_data + i));
9427     }
9428 }
9429
9430 static void
9431 bxe_zero_sp_sb(struct bxe_softc *sc)
9432 {
9433     struct hc_sp_status_block_data sp_sb_data;
9434
9435     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9436
9437     sp_sb_data.state           = SB_DISABLED;
9438     sp_sb_data.p_func.vf_valid = FALSE;
9439
9440     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9441
9442     bxe_fill(sc,
9443              (BAR_CSTRORM_INTMEM +
9444               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9445               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9446     bxe_fill(sc,
9447              (BAR_CSTRORM_INTMEM +
9448               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9449               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9450 }
9451
9452 static void
9453 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9454                              int                       igu_sb_id,
9455                              int                       igu_seg_id)
9456 {
9457     hc_sm->igu_sb_id      = igu_sb_id;
9458     hc_sm->igu_seg_id     = igu_seg_id;
9459     hc_sm->timer_value    = 0xFF;
9460     hc_sm->time_to_expire = 0xFFFFFFFF;
9461 }
9462
9463 static void
9464 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9465 {
9466     /* zero out state machine indices */
9467
9468     /* rx indices */
9469     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9470
9471     /* tx indices */
9472     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9473     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9474     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9475     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9476
9477     /* map indices */
9478
9479     /* rx indices */
9480     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9481         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9482
9483     /* tx indices */
9484     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9485         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9486     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9487         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9488     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9489         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9490     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9491         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9492 }
9493
9494 static void
9495 bxe_init_sb(struct bxe_softc *sc,
9496             bus_addr_t       busaddr,
9497             int              vfid,
9498             uint8_t          vf_valid,
9499             int              fw_sb_id,
9500             int              igu_sb_id)
9501 {
9502     struct hc_status_block_data_e2  sb_data_e2;
9503     struct hc_status_block_data_e1x sb_data_e1x;
9504     struct hc_status_block_sm       *hc_sm_p;
9505     uint32_t *sb_data_p;
9506     int igu_seg_id;
9507     int data_size;
9508
9509     if (CHIP_INT_MODE_IS_BC(sc)) {
9510         igu_seg_id = HC_SEG_ACCESS_NORM;
9511     } else {
9512         igu_seg_id = IGU_SEG_ACCESS_NORM;
9513     }
9514
9515     bxe_zero_fp_sb(sc, fw_sb_id);
9516
9517     if (!CHIP_IS_E1x(sc)) {
9518         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9519         sb_data_e2.common.state = SB_ENABLED;
9520         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9521         sb_data_e2.common.p_func.vf_id = vfid;
9522         sb_data_e2.common.p_func.vf_valid = vf_valid;
9523         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9524         sb_data_e2.common.same_igu_sb_1b = TRUE;
9525         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9526         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9527         hc_sm_p = sb_data_e2.common.state_machine;
9528         sb_data_p = (uint32_t *)&sb_data_e2;
9529         data_size = (sizeof(struct hc_status_block_data_e2) /
9530                      sizeof(uint32_t));
9531         bxe_map_sb_state_machines(sb_data_e2.index_data);
9532     } else {
9533         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9534         sb_data_e1x.common.state = SB_ENABLED;
9535         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9536         sb_data_e1x.common.p_func.vf_id = 0xff;
9537         sb_data_e1x.common.p_func.vf_valid = FALSE;
9538         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9539         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9540         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9541         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9542         hc_sm_p = sb_data_e1x.common.state_machine;
9543         sb_data_p = (uint32_t *)&sb_data_e1x;
9544         data_size = (sizeof(struct hc_status_block_data_e1x) /
9545                      sizeof(uint32_t));
9546         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9547     }
9548
9549     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9550     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9551
9552     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9553
9554     /* write indices to HW - PCI guarantees endianity of regpairs */
9555     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9556 }
9557
9558 static inline uint8_t
9559 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9560 {
9561     if (CHIP_IS_E1x(fp->sc)) {
9562         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9563     } else {
9564         return (fp->cl_id);
9565     }
9566 }
9567
9568 static inline uint32_t
9569 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9570                            struct bxe_fastpath *fp)
9571 {
9572     uint32_t offset = BAR_USTRORM_INTMEM;
9573
9574     if (!CHIP_IS_E1x(sc)) {
9575         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9576     } else {
9577         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9578     }
9579
9580     return (offset);
9581 }
9582
9583 static void
9584 bxe_init_eth_fp(struct bxe_softc *sc,
9585                 int              idx)
9586 {
9587     struct bxe_fastpath *fp = &sc->fp[idx];
9588     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9589     unsigned long q_type = 0;
9590     int cos;
9591
9592     fp->sc    = sc;
9593     fp->index = idx;
9594
9595     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9596     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9597
9598     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9599                     (SC_L_ID(sc) + idx) :
9600                     /* want client ID same as IGU SB ID for non-E1 */
9601                     fp->igu_sb_id;
9602     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9603
9604     /* setup sb indices */
9605     if (!CHIP_IS_E1x(sc)) {
9606         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9607         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9608     } else {
9609         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9610         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9611     }
9612
9613     /* init shortcut */
9614     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9615
9616     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9617
9618     /*
9619      * XXX If multiple CoS is ever supported then each fastpath structure
9620      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9621      */
9622     for (cos = 0; cos < sc->max_cos; cos++) {
9623         cids[cos] = idx;
9624     }
9625     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9626
9627     /* nothing more for a VF to do */
9628     if (IS_VF(sc)) {
9629         return;
9630     }
9631
9632     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9633                 fp->fw_sb_id, fp->igu_sb_id);
9634
9635     bxe_update_fp_sb_idx(fp);
9636
9637     /* Configure Queue State object */
9638     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9639     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9640
9641     ecore_init_queue_obj(sc,
9642                          &sc->sp_objs[idx].q_obj,
9643                          fp->cl_id,
9644                          cids,
9645                          sc->max_cos,
9646                          SC_FUNC(sc),
9647                          BXE_SP(sc, q_rdata),
9648                          BXE_SP_MAPPING(sc, q_rdata),
9649                          q_type);
9650
9651     /* configure classification DBs */
9652     ecore_init_mac_obj(sc,
9653                        &sc->sp_objs[idx].mac_obj,
9654                        fp->cl_id,
9655                        idx,
9656                        SC_FUNC(sc),
9657                        BXE_SP(sc, mac_rdata),
9658                        BXE_SP_MAPPING(sc, mac_rdata),
9659                        ECORE_FILTER_MAC_PENDING,
9660                        &sc->sp_state,
9661                        ECORE_OBJ_TYPE_RX_TX,
9662                        &sc->macs_pool);
9663
9664     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9665           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9666 }
9667
9668 static inline void
9669 bxe_update_rx_prod(struct bxe_softc    *sc,
9670                    struct bxe_fastpath *fp,
9671                    uint16_t            rx_bd_prod,
9672                    uint16_t            rx_cq_prod,
9673                    uint16_t            rx_sge_prod)
9674 {
9675     struct ustorm_eth_rx_producers rx_prods = { 0 };
9676     uint32_t i;
9677
9678     /* update producers */
9679     rx_prods.bd_prod  = rx_bd_prod;
9680     rx_prods.cqe_prod = rx_cq_prod;
9681     rx_prods.sge_prod = rx_sge_prod;
9682
9683     /*
9684      * Make sure that the BD and SGE data is updated before updating the
9685      * producers since FW might read the BD/SGE right after the producer
9686      * is updated.
9687      * This is only applicable for weak-ordered memory model archs such
9688      * as IA-64. The following barrier is also mandatory since FW will
9689      * assumes BDs must have buffers.
9690      */
9691     wmb();
9692
9693     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9694         REG_WR(sc,
9695                (fp->ustorm_rx_prods_offset + (i * 4)),
9696                ((uint32_t *)&rx_prods)[i]);
9697     }
9698
9699     wmb(); /* keep prod updates ordered */
9700
9701     BLOGD(sc, DBG_RX,
9702           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9703           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9704 }
9705
9706 static void
9707 bxe_init_rx_rings(struct bxe_softc *sc)
9708 {
9709     struct bxe_fastpath *fp;
9710     int i;
9711
9712     for (i = 0; i < sc->num_queues; i++) {
9713         fp = &sc->fp[i];
9714
9715         fp->rx_bd_cons = 0;
9716
9717         /*
9718          * Activate the BD ring...
9719          * Warning, this will generate an interrupt (to the TSTORM)
9720          * so this can only be done after the chip is initialized
9721          */
9722         bxe_update_rx_prod(sc, fp,
9723                            fp->rx_bd_prod,
9724                            fp->rx_cq_prod,
9725                            fp->rx_sge_prod);
9726
9727         if (i != 0) {
9728             continue;
9729         }
9730
9731         if (CHIP_IS_E1(sc)) {
9732             REG_WR(sc,
9733                    (BAR_USTRORM_INTMEM +
9734                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9735                    U64_LO(fp->rcq_dma.paddr));
9736             REG_WR(sc,
9737                    (BAR_USTRORM_INTMEM +
9738                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9739                    U64_HI(fp->rcq_dma.paddr));
9740         }
9741     }
9742 }
9743
9744 static void
9745 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9746 {
9747     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9748     fp->tx_db.data.zero_fill1 = 0;
9749     fp->tx_db.data.prod = 0;
9750
9751     fp->tx_pkt_prod = 0;
9752     fp->tx_pkt_cons = 0;
9753     fp->tx_bd_prod = 0;
9754     fp->tx_bd_cons = 0;
9755     fp->eth_q_stats.tx_pkts = 0;
9756 }
9757
9758 static inline void
9759 bxe_init_tx_rings(struct bxe_softc *sc)
9760 {
9761     int i;
9762
9763     for (i = 0; i < sc->num_queues; i++) {
9764         bxe_init_tx_ring_one(&sc->fp[i]);
9765     }
9766 }
9767
9768 static void
9769 bxe_init_def_sb(struct bxe_softc *sc)
9770 {
9771     struct host_sp_status_block *def_sb = sc->def_sb;
9772     bus_addr_t mapping = sc->def_sb_dma.paddr;
9773     int igu_sp_sb_index;
9774     int igu_seg_id;
9775     int port = SC_PORT(sc);
9776     int func = SC_FUNC(sc);
9777     int reg_offset, reg_offset_en5;
9778     uint64_t section;
9779     int index, sindex;
9780     struct hc_sp_status_block_data sp_sb_data;
9781
9782     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9783
9784     if (CHIP_INT_MODE_IS_BC(sc)) {
9785         igu_sp_sb_index = DEF_SB_IGU_ID;
9786         igu_seg_id = HC_SEG_ACCESS_DEF;
9787     } else {
9788         igu_sp_sb_index = sc->igu_dsb_id;
9789         igu_seg_id = IGU_SEG_ACCESS_DEF;
9790     }
9791
9792     /* attentions */
9793     section = ((uint64_t)mapping +
9794                offsetof(struct host_sp_status_block, atten_status_block));
9795     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9796     sc->attn_state = 0;
9797
9798     reg_offset = (port) ?
9799                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9800                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9801     reg_offset_en5 = (port) ?
9802                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9803                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9804
9805     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9806         /* take care of sig[0]..sig[4] */
9807         for (sindex = 0; sindex < 4; sindex++) {
9808             sc->attn_group[index].sig[sindex] =
9809                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9810         }
9811
9812         if (!CHIP_IS_E1x(sc)) {
9813             /*
9814              * enable5 is separate from the rest of the registers,
9815              * and the address skip is 4 and not 16 between the
9816              * different groups
9817              */
9818             sc->attn_group[index].sig[4] =
9819                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9820         } else {
9821             sc->attn_group[index].sig[4] = 0;
9822         }
9823     }
9824
9825     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9826         reg_offset = (port) ?
9827                          HC_REG_ATTN_MSG1_ADDR_L :
9828                          HC_REG_ATTN_MSG0_ADDR_L;
9829         REG_WR(sc, reg_offset, U64_LO(section));
9830         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9831     } else if (!CHIP_IS_E1x(sc)) {
9832         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9833         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9834     }
9835
9836     section = ((uint64_t)mapping +
9837                offsetof(struct host_sp_status_block, sp_sb));
9838
9839     bxe_zero_sp_sb(sc);
9840
9841     /* PCI guarantees endianity of regpair */
9842     sp_sb_data.state           = SB_ENABLED;
9843     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9844     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9845     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9846     sp_sb_data.igu_seg_id      = igu_seg_id;
9847     sp_sb_data.p_func.pf_id    = func;
9848     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9849     sp_sb_data.p_func.vf_id    = 0xff;
9850
9851     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9852
9853     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9854 }
9855
9856 static void
9857 bxe_init_sp_ring(struct bxe_softc *sc)
9858 {
9859     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9860     sc->spq_prod_idx = 0;
9861     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9862     sc->spq_prod_bd = sc->spq;
9863     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9864 }
9865
9866 static void
9867 bxe_init_eq_ring(struct bxe_softc *sc)
9868 {
9869     union event_ring_elem *elem;
9870     int i;
9871
9872     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9873         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9874
9875         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9876                                                  BCM_PAGE_SIZE *
9877                                                  (i % NUM_EQ_PAGES)));
9878         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9879                                                  BCM_PAGE_SIZE *
9880                                                  (i % NUM_EQ_PAGES)));
9881     }
9882
9883     sc->eq_cons    = 0;
9884     sc->eq_prod    = NUM_EQ_DESC;
9885     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9886
9887     atomic_store_rel_long(&sc->eq_spq_left,
9888                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9889                                NUM_EQ_DESC) - 1));
9890 }
9891
9892 static void
9893 bxe_init_internal_common(struct bxe_softc *sc)
9894 {
9895     int i;
9896
9897     /*
9898      * Zero this manually as its initialization is currently missing
9899      * in the initTool.
9900      */
9901     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9902         REG_WR(sc,
9903                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9904                0);
9905     }
9906
9907     if (!CHIP_IS_E1x(sc)) {
9908         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9909                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9910     }
9911 }
9912
9913 static void
9914 bxe_init_internal(struct bxe_softc *sc,
9915                   uint32_t         load_code)
9916 {
9917     switch (load_code) {
9918     case FW_MSG_CODE_DRV_LOAD_COMMON:
9919     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9920         bxe_init_internal_common(sc);
9921         /* no break */
9922
9923     case FW_MSG_CODE_DRV_LOAD_PORT:
9924         /* nothing to do */
9925         /* no break */
9926
9927     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9928         /* internal memory per function is initialized inside bxe_pf_init */
9929         break;
9930
9931     default:
9932         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9933         break;
9934     }
9935 }
9936
9937 static void
9938 storm_memset_func_cfg(struct bxe_softc                         *sc,
9939                       struct tstorm_eth_function_common_config *tcfg,
9940                       uint16_t                                  abs_fid)
9941 {
9942     uint32_t addr;
9943     size_t size;
9944
9945     addr = (BAR_TSTRORM_INTMEM +
9946             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9947     size = sizeof(struct tstorm_eth_function_common_config);
9948     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9949 }
9950
9951 static void
9952 bxe_func_init(struct bxe_softc            *sc,
9953               struct bxe_func_init_params *p)
9954 {
9955     struct tstorm_eth_function_common_config tcfg = { 0 };
9956
9957     if (CHIP_IS_E1x(sc)) {
9958         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9959     }
9960
9961     /* Enable the function in the FW */
9962     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9963     storm_memset_func_en(sc, p->func_id, 1);
9964
9965     /* spq */
9966     if (p->func_flgs & FUNC_FLG_SPQ) {
9967         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9968         REG_WR(sc,
9969                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9970                p->spq_prod);
9971     }
9972 }
9973
9974 /*
9975  * Calculates the sum of vn_min_rates.
9976  * It's needed for further normalizing of the min_rates.
9977  * Returns:
9978  *   sum of vn_min_rates.
9979  *     or
9980  *   0 - if all the min_rates are 0.
9981  * In the later case fainess algorithm should be deactivated.
9982  * If all min rates are not zero then those that are zeroes will be set to 1.
9983  */
9984 static void
9985 bxe_calc_vn_min(struct bxe_softc       *sc,
9986                 struct cmng_init_input *input)
9987 {
9988     uint32_t vn_cfg;
9989     uint32_t vn_min_rate;
9990     int all_zero = 1;
9991     int vn;
9992
9993     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9994         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9995         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9996                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9997
9998         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9999             /* skip hidden VNs */
10000             vn_min_rate = 0;
10001         } else if (!vn_min_rate) {
10002             /* If min rate is zero - set it to 100 */
10003             vn_min_rate = DEF_MIN_RATE;
10004         } else {
10005             all_zero = 0;
10006         }
10007
10008         input->vnic_min_rate[vn] = vn_min_rate;
10009     }
10010
10011     /* if ETS or all min rates are zeros - disable fairness */
10012     if (BXE_IS_ETS_ENABLED(sc)) {
10013         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10014         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10015     } else if (all_zero) {
10016         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10017         BLOGD(sc, DBG_LOAD,
10018               "Fariness disabled (all MIN values are zeroes)\n");
10019     } else {
10020         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10021     }
10022 }
10023
10024 static inline uint16_t
10025 bxe_extract_max_cfg(struct bxe_softc *sc,
10026                     uint32_t         mf_cfg)
10027 {
10028     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10029                         FUNC_MF_CFG_MAX_BW_SHIFT);
10030
10031     if (!max_cfg) {
10032         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10033         max_cfg = 100;
10034     }
10035
10036     return (max_cfg);
10037 }
10038
10039 static void
10040 bxe_calc_vn_max(struct bxe_softc       *sc,
10041                 int                    vn,
10042                 struct cmng_init_input *input)
10043 {
10044     uint16_t vn_max_rate;
10045     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10046     uint32_t max_cfg;
10047
10048     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10049         vn_max_rate = 0;
10050     } else {
10051         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10052
10053         if (IS_MF_SI(sc)) {
10054             /* max_cfg in percents of linkspeed */
10055             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10056         } else { /* SD modes */
10057             /* max_cfg is absolute in 100Mb units */
10058             vn_max_rate = (max_cfg * 100);
10059         }
10060     }
10061
10062     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10063
10064     input->vnic_max_rate[vn] = vn_max_rate;
10065 }
10066
10067 static void
10068 bxe_cmng_fns_init(struct bxe_softc *sc,
10069                   uint8_t          read_cfg,
10070                   uint8_t          cmng_type)
10071 {
10072     struct cmng_init_input input;
10073     int vn;
10074
10075     memset(&input, 0, sizeof(struct cmng_init_input));
10076
10077     input.port_rate = sc->link_vars.line_speed;
10078
10079     if (cmng_type == CMNG_FNS_MINMAX) {
10080         /* read mf conf from shmem */
10081         if (read_cfg) {
10082             bxe_read_mf_cfg(sc);
10083         }
10084
10085         /* get VN min rate and enable fairness if not 0 */
10086         bxe_calc_vn_min(sc, &input);
10087
10088         /* get VN max rate */
10089         if (sc->port.pmf) {
10090             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10091                 bxe_calc_vn_max(sc, vn, &input);
10092             }
10093         }
10094
10095         /* always enable rate shaping and fairness */
10096         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10097
10098         ecore_init_cmng(&input, &sc->cmng);
10099         return;
10100     }
10101
10102     /* rate shaping and fairness are disabled */
10103     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10104 }
10105
10106 static int
10107 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10108 {
10109     if (CHIP_REV_IS_SLOW(sc)) {
10110         return (CMNG_FNS_NONE);
10111     }
10112
10113     if (IS_MF(sc)) {
10114         return (CMNG_FNS_MINMAX);
10115     }
10116
10117     return (CMNG_FNS_NONE);
10118 }
10119
10120 static void
10121 storm_memset_cmng(struct bxe_softc *sc,
10122                   struct cmng_init *cmng,
10123                   uint8_t          port)
10124 {
10125     int vn;
10126     int func;
10127     uint32_t addr;
10128     size_t size;
10129
10130     addr = (BAR_XSTRORM_INTMEM +
10131             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10132     size = sizeof(struct cmng_struct_per_port);
10133     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10134
10135     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10136         func = func_by_vn(sc, vn);
10137
10138         addr = (BAR_XSTRORM_INTMEM +
10139                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10140         size = sizeof(struct rate_shaping_vars_per_vn);
10141         ecore_storm_memset_struct(sc, addr, size,
10142                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10143
10144         addr = (BAR_XSTRORM_INTMEM +
10145                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10146         size = sizeof(struct fairness_vars_per_vn);
10147         ecore_storm_memset_struct(sc, addr, size,
10148                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10149     }
10150 }
10151
10152 static void
10153 bxe_pf_init(struct bxe_softc *sc)
10154 {
10155     struct bxe_func_init_params func_init = { 0 };
10156     struct event_ring_data eq_data = { { 0 } };
10157     uint16_t flags;
10158
10159     if (!CHIP_IS_E1x(sc)) {
10160         /* reset IGU PF statistics: MSIX + ATTN */
10161         /* PF */
10162         REG_WR(sc,
10163                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10164                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10165                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10166                0);
10167         /* ATTN */
10168         REG_WR(sc,
10169                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10170                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10171                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10172                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10173                0);
10174     }
10175
10176     /* function setup flags */
10177     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10178
10179     /*
10180      * This flag is relevant for E1x only.
10181      * E2 doesn't have a TPA configuration in a function level.
10182      */
10183     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10184
10185     func_init.func_flgs = flags;
10186     func_init.pf_id     = SC_FUNC(sc);
10187     func_init.func_id   = SC_FUNC(sc);
10188     func_init.spq_map   = sc->spq_dma.paddr;
10189     func_init.spq_prod  = sc->spq_prod_idx;
10190
10191     bxe_func_init(sc, &func_init);
10192
10193     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10194
10195     /*
10196      * Congestion management values depend on the link rate.
10197      * There is no active link so initial link rate is set to 10Gbps.
10198      * When the link comes up the congestion management values are
10199      * re-calculated according to the actual link rate.
10200      */
10201     sc->link_vars.line_speed = SPEED_10000;
10202     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10203
10204     /* Only the PMF sets the HW */
10205     if (sc->port.pmf) {
10206         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10207     }
10208
10209     /* init Event Queue - PCI bus guarantees correct endainity */
10210     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10211     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10212     eq_data.producer     = sc->eq_prod;
10213     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10214     eq_data.sb_id        = DEF_SB_ID;
10215     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10216 }
10217
10218 static void
10219 bxe_hc_int_enable(struct bxe_softc *sc)
10220 {
10221     int port = SC_PORT(sc);
10222     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10223     uint32_t val = REG_RD(sc, addr);
10224     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10225     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10226                            (sc->intr_count == 1)) ? TRUE : FALSE;
10227     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10228
10229     if (msix) {
10230         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10231                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10232         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10233                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10234         if (single_msix) {
10235             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10236         }
10237     } else if (msi) {
10238         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10239         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10240                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10241                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10242     } else {
10243         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10244                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10245                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10246                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10247
10248         if (!CHIP_IS_E1(sc)) {
10249             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10250                   val, port, addr);
10251
10252             REG_WR(sc, addr, val);
10253
10254             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10255         }
10256     }
10257
10258     if (CHIP_IS_E1(sc)) {
10259         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10260     }
10261
10262     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10263           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10264
10265     REG_WR(sc, addr, val);
10266
10267     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10268     mb();
10269
10270     if (!CHIP_IS_E1(sc)) {
10271         /* init leading/trailing edge */
10272         if (IS_MF(sc)) {
10273             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10274             if (sc->port.pmf) {
10275                 /* enable nig and gpio3 attention */
10276                 val |= 0x1100;
10277             }
10278         } else {
10279             val = 0xffff;
10280         }
10281
10282         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10283         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10284     }
10285
10286     /* make sure that interrupts are indeed enabled from here on */
10287     mb();
10288 }
10289
10290 static void
10291 bxe_igu_int_enable(struct bxe_softc *sc)
10292 {
10293     uint32_t val;
10294     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10295     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10296                            (sc->intr_count == 1)) ? TRUE : FALSE;
10297     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10298
10299     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10300
10301     if (msix) {
10302         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10303                  IGU_PF_CONF_SINGLE_ISR_EN);
10304         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10305                 IGU_PF_CONF_ATTN_BIT_EN);
10306         if (single_msix) {
10307             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10308         }
10309     } else if (msi) {
10310         val &= ~IGU_PF_CONF_INT_LINE_EN;
10311         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10312                 IGU_PF_CONF_ATTN_BIT_EN |
10313                 IGU_PF_CONF_SINGLE_ISR_EN);
10314     } else {
10315         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10316         val |= (IGU_PF_CONF_INT_LINE_EN |
10317                 IGU_PF_CONF_ATTN_BIT_EN |
10318                 IGU_PF_CONF_SINGLE_ISR_EN);
10319     }
10320
10321     /* clean previous status - need to configure igu prior to ack*/
10322     if ((!msix) || single_msix) {
10323         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10324         bxe_ack_int(sc);
10325     }
10326
10327     val |= IGU_PF_CONF_FUNC_EN;
10328
10329     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10330           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10331
10332     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10333
10334     mb();
10335
10336     /* init leading/trailing edge */
10337     if (IS_MF(sc)) {
10338         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10339         if (sc->port.pmf) {
10340             /* enable nig and gpio3 attention */
10341             val |= 0x1100;
10342         }
10343     } else {
10344         val = 0xffff;
10345     }
10346
10347     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10348     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10349
10350     /* make sure that interrupts are indeed enabled from here on */
10351     mb();
10352 }
10353
10354 static void
10355 bxe_int_enable(struct bxe_softc *sc)
10356 {
10357     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10358         bxe_hc_int_enable(sc);
10359     } else {
10360         bxe_igu_int_enable(sc);
10361     }
10362 }
10363
10364 static void
10365 bxe_hc_int_disable(struct bxe_softc *sc)
10366 {
10367     int port = SC_PORT(sc);
10368     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10369     uint32_t val = REG_RD(sc, addr);
10370
10371     /*
10372      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10373      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10374      * block
10375      */
10376     if (CHIP_IS_E1(sc)) {
10377         /*
10378          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10379          * to prevent from HC sending interrupts after we exit the function
10380          */
10381         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10382
10383         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10384                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10385                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10386     } else {
10387         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10388                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10389                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10390                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10391     }
10392
10393     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10394
10395     /* flush all outstanding writes */
10396     mb();
10397
10398     REG_WR(sc, addr, val);
10399     if (REG_RD(sc, addr) != val) {
10400         BLOGE(sc, "proper val not read from HC IGU!\n");
10401     }
10402 }
10403
10404 static void
10405 bxe_igu_int_disable(struct bxe_softc *sc)
10406 {
10407     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10408
10409     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10410              IGU_PF_CONF_INT_LINE_EN |
10411              IGU_PF_CONF_ATTN_BIT_EN);
10412
10413     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10414
10415     /* flush all outstanding writes */
10416     mb();
10417
10418     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10419     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10420         BLOGE(sc, "proper val not read from IGU!\n");
10421     }
10422 }
10423
10424 static void
10425 bxe_int_disable(struct bxe_softc *sc)
10426 {
10427     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10428         bxe_hc_int_disable(sc);
10429     } else {
10430         bxe_igu_int_disable(sc);
10431     }
10432 }
10433
10434 static void
10435 bxe_nic_init(struct bxe_softc *sc,
10436              int              load_code)
10437 {
10438     int i;
10439
10440     for (i = 0; i < sc->num_queues; i++) {
10441         bxe_init_eth_fp(sc, i);
10442     }
10443
10444     rmb(); /* ensure status block indices were read */
10445
10446     bxe_init_rx_rings(sc);
10447     bxe_init_tx_rings(sc);
10448
10449     if (IS_VF(sc)) {
10450         return;
10451     }
10452
10453     /* initialize MOD_ABS interrupts */
10454     elink_init_mod_abs_int(sc, &sc->link_vars,
10455                            sc->devinfo.chip_id,
10456                            sc->devinfo.shmem_base,
10457                            sc->devinfo.shmem2_base,
10458                            SC_PORT(sc));
10459
10460     bxe_init_def_sb(sc);
10461     bxe_update_dsb_idx(sc);
10462     bxe_init_sp_ring(sc);
10463     bxe_init_eq_ring(sc);
10464     bxe_init_internal(sc, load_code);
10465     bxe_pf_init(sc);
10466     bxe_stats_init(sc);
10467
10468     /* flush all before enabling interrupts */
10469     mb();
10470
10471     bxe_int_enable(sc);
10472
10473     /* check for SPIO5 */
10474     bxe_attn_int_deasserted0(sc,
10475                              REG_RD(sc,
10476                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10477                                      SC_PORT(sc)*4)) &
10478                              AEU_INPUTS_ATTN_BITS_SPIO5);
10479 }
10480
10481 static inline void
10482 bxe_init_objs(struct bxe_softc *sc)
10483 {
10484     /* mcast rules must be added to tx if tx switching is enabled */
10485     ecore_obj_type o_type =
10486         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10487                                          ECORE_OBJ_TYPE_RX;
10488
10489     /* RX_MODE controlling object */
10490     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10491
10492     /* multicast configuration controlling object */
10493     ecore_init_mcast_obj(sc,
10494                          &sc->mcast_obj,
10495                          sc->fp[0].cl_id,
10496                          sc->fp[0].index,
10497                          SC_FUNC(sc),
10498                          SC_FUNC(sc),
10499                          BXE_SP(sc, mcast_rdata),
10500                          BXE_SP_MAPPING(sc, mcast_rdata),
10501                          ECORE_FILTER_MCAST_PENDING,
10502                          &sc->sp_state,
10503                          o_type);
10504
10505     /* Setup CAM credit pools */
10506     ecore_init_mac_credit_pool(sc,
10507                                &sc->macs_pool,
10508                                SC_FUNC(sc),
10509                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10510                                                  VNICS_PER_PATH(sc));
10511
10512     ecore_init_vlan_credit_pool(sc,
10513                                 &sc->vlans_pool,
10514                                 SC_ABS_FUNC(sc) >> 1,
10515                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10516                                                   VNICS_PER_PATH(sc));
10517
10518     /* RSS configuration object */
10519     ecore_init_rss_config_obj(sc,
10520                               &sc->rss_conf_obj,
10521                               sc->fp[0].cl_id,
10522                               sc->fp[0].index,
10523                               SC_FUNC(sc),
10524                               SC_FUNC(sc),
10525                               BXE_SP(sc, rss_rdata),
10526                               BXE_SP_MAPPING(sc, rss_rdata),
10527                               ECORE_FILTER_RSS_CONF_PENDING,
10528                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10529 }
10530
10531 /*
10532  * Initialize the function. This must be called before sending CLIENT_SETUP
10533  * for the first client.
10534  */
10535 static inline int
10536 bxe_func_start(struct bxe_softc *sc)
10537 {
10538     struct ecore_func_state_params func_params = { NULL };
10539     struct ecore_func_start_params *start_params = &func_params.params.start;
10540
10541     /* Prepare parameters for function state transitions */
10542     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10543
10544     func_params.f_obj = &sc->func_obj;
10545     func_params.cmd = ECORE_F_CMD_START;
10546
10547     /* Function parameters */
10548     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10549     start_params->sd_vlan_tag = OVLAN(sc);
10550
10551     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10552         start_params->network_cos_mode = STATIC_COS;
10553     } else { /* CHIP_IS_E1X */
10554         start_params->network_cos_mode = FW_WRR;
10555     }
10556
10557     //start_params->gre_tunnel_mode = 0;
10558     //start_params->gre_tunnel_rss  = 0;
10559
10560     return (ecore_func_state_change(sc, &func_params));
10561 }
10562
10563 static int
10564 bxe_set_power_state(struct bxe_softc *sc,
10565                     uint8_t          state)
10566 {
10567     uint16_t pmcsr;
10568
10569     /* If there is no power capability, silently succeed */
10570     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10571         BLOGW(sc, "No power capability\n");
10572         return (0);
10573     }
10574
10575     pmcsr = pci_read_config(sc->dev,
10576                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10577                             2);
10578
10579     switch (state) {
10580     case PCI_PM_D0:
10581         pci_write_config(sc->dev,
10582                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10583                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10584
10585         if (pmcsr & PCIM_PSTAT_DMASK) {
10586             /* delay required during transition out of D3hot */
10587             DELAY(20000);
10588         }
10589
10590         break;
10591
10592     case PCI_PM_D3hot:
10593         /* XXX if there are other clients above don't shut down the power */
10594
10595         /* don't shut down the power for emulation and FPGA */
10596         if (CHIP_REV_IS_SLOW(sc)) {
10597             return (0);
10598         }
10599
10600         pmcsr &= ~PCIM_PSTAT_DMASK;
10601         pmcsr |= PCIM_PSTAT_D3;
10602
10603         if (sc->wol) {
10604             pmcsr |= PCIM_PSTAT_PMEENABLE;
10605         }
10606
10607         pci_write_config(sc->dev,
10608                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10609                          pmcsr, 4);
10610
10611         /*
10612          * No more memory access after this point until device is brought back
10613          * to D0 state.
10614          */
10615         break;
10616
10617     default:
10618         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10619             state, pmcsr);
10620         return (-1);
10621     }
10622
10623     return (0);
10624 }
10625
10626
10627 /* return true if succeeded to acquire the lock */
10628 static uint8_t
10629 bxe_trylock_hw_lock(struct bxe_softc *sc,
10630                     uint32_t         resource)
10631 {
10632     uint32_t lock_status;
10633     uint32_t resource_bit = (1 << resource);
10634     int func = SC_FUNC(sc);
10635     uint32_t hw_lock_control_reg;
10636
10637     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10638
10639     /* Validating that the resource is within range */
10640     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10641         BLOGD(sc, DBG_LOAD,
10642               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10643               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10644         return (FALSE);
10645     }
10646
10647     if (func <= 5) {
10648         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10649     } else {
10650         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10651     }
10652
10653     /* try to acquire the lock */
10654     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10655     lock_status = REG_RD(sc, hw_lock_control_reg);
10656     if (lock_status & resource_bit) {
10657         return (TRUE);
10658     }
10659
10660     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10661         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10662         lock_status, resource_bit);
10663
10664     return (FALSE);
10665 }
10666
10667 /*
10668  * Get the recovery leader resource id according to the engine this function
10669  * belongs to. Currently only only 2 engines is supported.
10670  */
10671 static int
10672 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10673 {
10674     if (SC_PATH(sc)) {
10675         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10676     } else {
10677         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10678     }
10679 }
10680
10681 /* try to acquire a leader lock for current engine */
10682 static uint8_t
10683 bxe_trylock_leader_lock(struct bxe_softc *sc)
10684 {
10685     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10686 }
10687
10688 static int
10689 bxe_release_leader_lock(struct bxe_softc *sc)
10690 {
10691     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10692 }
10693
10694 /* close gates #2, #3 and #4 */
10695 static void
10696 bxe_set_234_gates(struct bxe_softc *sc,
10697                   uint8_t          close)
10698 {
10699     uint32_t val;
10700
10701     /* gates #2 and #4a are closed/opened for "not E1" only */
10702     if (!CHIP_IS_E1(sc)) {
10703         /* #4 */
10704         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10705         /* #2 */
10706         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10707     }
10708
10709     /* #3 */
10710     if (CHIP_IS_E1x(sc)) {
10711         /* prevent interrupts from HC on both ports */
10712         val = REG_RD(sc, HC_REG_CONFIG_1);
10713         REG_WR(sc, HC_REG_CONFIG_1,
10714                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10715                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10716
10717         val = REG_RD(sc, HC_REG_CONFIG_0);
10718         REG_WR(sc, HC_REG_CONFIG_0,
10719                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10720                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10721     } else {
10722         /* Prevent incomming interrupts in IGU */
10723         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10724
10725         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10726                (!close) ?
10727                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10728                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10729     }
10730
10731     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10732           close ? "closing" : "opening");
10733
10734     wmb();
10735 }
10736
10737 /* poll for pending writes bit, it should get cleared in no more than 1s */
10738 static int
10739 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10740 {
10741     uint32_t cnt = 1000;
10742     uint32_t pend_bits = 0;
10743
10744     do {
10745         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10746
10747         if (pend_bits == 0) {
10748             break;
10749         }
10750
10751         DELAY(1000);
10752     } while (--cnt > 0);
10753
10754     if (cnt == 0) {
10755         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10756         return (-1);
10757     }
10758
10759     return (0);
10760 }
10761
10762 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10763
10764 static void
10765 bxe_clp_reset_prep(struct bxe_softc *sc,
10766                    uint32_t         *magic_val)
10767 {
10768     /* Do some magic... */
10769     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10770     *magic_val = val & SHARED_MF_CLP_MAGIC;
10771     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10772 }
10773
10774 /* restore the value of the 'magic' bit */
10775 static void
10776 bxe_clp_reset_done(struct bxe_softc *sc,
10777                    uint32_t         magic_val)
10778 {
10779     /* Restore the 'magic' bit value... */
10780     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10781     MFCFG_WR(sc, shared_mf_config.clp_mb,
10782               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10783 }
10784
10785 /* prepare for MCP reset, takes care of CLP configurations */
10786 static void
10787 bxe_reset_mcp_prep(struct bxe_softc *sc,
10788                    uint32_t         *magic_val)
10789 {
10790     uint32_t shmem;
10791     uint32_t validity_offset;
10792
10793     /* set `magic' bit in order to save MF config */
10794     if (!CHIP_IS_E1(sc)) {
10795         bxe_clp_reset_prep(sc, magic_val);
10796     }
10797
10798     /* get shmem offset */
10799     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10800     validity_offset =
10801         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10802
10803     /* Clear validity map flags */
10804     if (shmem > 0) {
10805         REG_WR(sc, shmem + validity_offset, 0);
10806     }
10807 }
10808
10809 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10810 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10811
10812 static void
10813 bxe_mcp_wait_one(struct bxe_softc *sc)
10814 {
10815     /* special handling for emulation and FPGA (10 times longer) */
10816     if (CHIP_REV_IS_SLOW(sc)) {
10817         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10818     } else {
10819         DELAY((MCP_ONE_TIMEOUT) * 1000);
10820     }
10821 }
10822
10823 /* initialize shmem_base and waits for validity signature to appear */
10824 static int
10825 bxe_init_shmem(struct bxe_softc *sc)
10826 {
10827     int cnt = 0;
10828     uint32_t val = 0;
10829
10830     do {
10831         sc->devinfo.shmem_base     =
10832         sc->link_params.shmem_base =
10833             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10834
10835         if (sc->devinfo.shmem_base) {
10836             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10837             if (val & SHR_MEM_VALIDITY_MB)
10838                 return (0);
10839         }
10840
10841         bxe_mcp_wait_one(sc);
10842
10843     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10844
10845     BLOGE(sc, "BAD MCP validity signature\n");
10846
10847     return (-1);
10848 }
10849
10850 static int
10851 bxe_reset_mcp_comp(struct bxe_softc *sc,
10852                    uint32_t         magic_val)
10853 {
10854     int rc = bxe_init_shmem(sc);
10855
10856     /* Restore the `magic' bit value */
10857     if (!CHIP_IS_E1(sc)) {
10858         bxe_clp_reset_done(sc, magic_val);
10859     }
10860
10861     return (rc);
10862 }
10863
10864 static void
10865 bxe_pxp_prep(struct bxe_softc *sc)
10866 {
10867     if (!CHIP_IS_E1(sc)) {
10868         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10869         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10870         wmb();
10871     }
10872 }
10873
10874 /*
10875  * Reset the whole chip except for:
10876  *      - PCIE core
10877  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10878  *      - IGU
10879  *      - MISC (including AEU)
10880  *      - GRC
10881  *      - RBCN, RBCP
10882  */
10883 static void
10884 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10885                             uint8_t          global)
10886 {
10887     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10888     uint32_t global_bits2, stay_reset2;
10889
10890     /*
10891      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10892      * (per chip) blocks.
10893      */
10894     global_bits2 =
10895         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10896         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10897
10898     /*
10899      * Don't reset the following blocks.
10900      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10901      *            reset, as in 4 port device they might still be owned
10902      *            by the MCP (there is only one leader per path).
10903      */
10904     not_reset_mask1 =
10905         MISC_REGISTERS_RESET_REG_1_RST_HC |
10906         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10907         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10908
10909     not_reset_mask2 =
10910         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10911         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10912         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10913         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10914         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10915         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10916         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10917         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10918         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10919         MISC_REGISTERS_RESET_REG_2_PGLC |
10920         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10921         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10922         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10923         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10924         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10925         MISC_REGISTERS_RESET_REG_2_UMAC1;
10926
10927     /*
10928      * Keep the following blocks in reset:
10929      *  - all xxMACs are handled by the elink code.
10930      */
10931     stay_reset2 =
10932         MISC_REGISTERS_RESET_REG_2_XMAC |
10933         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10934
10935     /* Full reset masks according to the chip */
10936     reset_mask1 = 0xffffffff;
10937
10938     if (CHIP_IS_E1(sc))
10939         reset_mask2 = 0xffff;
10940     else if (CHIP_IS_E1H(sc))
10941         reset_mask2 = 0x1ffff;
10942     else if (CHIP_IS_E2(sc))
10943         reset_mask2 = 0xfffff;
10944     else /* CHIP_IS_E3 */
10945         reset_mask2 = 0x3ffffff;
10946
10947     /* Don't reset global blocks unless we need to */
10948     if (!global)
10949         reset_mask2 &= ~global_bits2;
10950
10951     /*
10952      * In case of attention in the QM, we need to reset PXP
10953      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10954      * because otherwise QM reset would release 'close the gates' shortly
10955      * before resetting the PXP, then the PSWRQ would send a write
10956      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10957      * read the payload data from PSWWR, but PSWWR would not
10958      * respond. The write queue in PGLUE would stuck, dmae commands
10959      * would not return. Therefore it's important to reset the second
10960      * reset register (containing the
10961      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10962      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10963      * bit).
10964      */
10965     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10966            reset_mask2 & (~not_reset_mask2));
10967
10968     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10969            reset_mask1 & (~not_reset_mask1));
10970
10971     mb();
10972     wmb();
10973
10974     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10975            reset_mask2 & (~stay_reset2));
10976
10977     mb();
10978     wmb();
10979
10980     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10981     wmb();
10982 }
10983
10984 static int
10985 bxe_process_kill(struct bxe_softc *sc,
10986                  uint8_t          global)
10987 {
10988     int cnt = 1000;
10989     uint32_t val = 0;
10990     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10991     uint32_t tags_63_32 = 0;
10992
10993     /* Empty the Tetris buffer, wait for 1s */
10994     do {
10995         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10996         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10997         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10998         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10999         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11000         if (CHIP_IS_E3(sc)) {
11001             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11002         }
11003
11004         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11005             ((port_is_idle_0 & 0x1) == 0x1) &&
11006             ((port_is_idle_1 & 0x1) == 0x1) &&
11007             (pgl_exp_rom2 == 0xffffffff) &&
11008             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11009             break;
11010         DELAY(1000);
11011     } while (cnt-- > 0);
11012
11013     if (cnt <= 0) {
11014         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11015                   "are still outstanding read requests after 1s! "
11016                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11017                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11018               sr_cnt, blk_cnt, port_is_idle_0,
11019               port_is_idle_1, pgl_exp_rom2);
11020         return (-1);
11021     }
11022
11023     mb();
11024
11025     /* Close gates #2, #3 and #4 */
11026     bxe_set_234_gates(sc, TRUE);
11027
11028     /* Poll for IGU VQs for 57712 and newer chips */
11029     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11030         return (-1);
11031     }
11032
11033     /* XXX indicate that "process kill" is in progress to MCP */
11034
11035     /* clear "unprepared" bit */
11036     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11037     mb();
11038
11039     /* Make sure all is written to the chip before the reset */
11040     wmb();
11041
11042     /*
11043      * Wait for 1ms to empty GLUE and PCI-E core queues,
11044      * PSWHST, GRC and PSWRD Tetris buffer.
11045      */
11046     DELAY(1000);
11047
11048     /* Prepare to chip reset: */
11049     /* MCP */
11050     if (global) {
11051         bxe_reset_mcp_prep(sc, &val);
11052     }
11053
11054     /* PXP */
11055     bxe_pxp_prep(sc);
11056     mb();
11057
11058     /* reset the chip */
11059     bxe_process_kill_chip_reset(sc, global);
11060     mb();
11061
11062     /* clear errors in PGB */
11063     if (!CHIP_IS_E1(sc))
11064         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11065
11066     /* Recover after reset: */
11067     /* MCP */
11068     if (global && bxe_reset_mcp_comp(sc, val)) {
11069         return (-1);
11070     }
11071
11072     /* XXX add resetting the NO_MCP mode DB here */
11073
11074     /* Open the gates #2, #3 and #4 */
11075     bxe_set_234_gates(sc, FALSE);
11076
11077     /* XXX
11078      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11079      * re-enable attentions
11080      */
11081
11082     return (0);
11083 }
11084
11085 static int
11086 bxe_leader_reset(struct bxe_softc *sc)
11087 {
11088     int rc = 0;
11089     uint8_t global = bxe_reset_is_global(sc);
11090     uint32_t load_code;
11091
11092     /*
11093      * If not going to reset MCP, load "fake" driver to reset HW while
11094      * driver is owner of the HW.
11095      */
11096     if (!global && !BXE_NOMCP(sc)) {
11097         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11098                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11099         if (!load_code) {
11100             BLOGE(sc, "MCP response failure, aborting\n");
11101             rc = -1;
11102             goto exit_leader_reset;
11103         }
11104
11105         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11106             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11107             BLOGE(sc, "MCP unexpected response, aborting\n");
11108             rc = -1;
11109             goto exit_leader_reset2;
11110         }
11111
11112         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11113         if (!load_code) {
11114             BLOGE(sc, "MCP response failure, aborting\n");
11115             rc = -1;
11116             goto exit_leader_reset2;
11117         }
11118     }
11119
11120     /* try to recover after the failure */
11121     if (bxe_process_kill(sc, global)) {
11122         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11123         rc = -1;
11124         goto exit_leader_reset2;
11125     }
11126
11127     /*
11128      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11129      * state.
11130      */
11131     bxe_set_reset_done(sc);
11132     if (global) {
11133         bxe_clear_reset_global(sc);
11134     }
11135
11136 exit_leader_reset2:
11137
11138     /* unload "fake driver" if it was loaded */
11139     if (!global && !BXE_NOMCP(sc)) {
11140         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11141         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11142     }
11143
11144 exit_leader_reset:
11145
11146     sc->is_leader = 0;
11147     bxe_release_leader_lock(sc);
11148
11149     mb();
11150     return (rc);
11151 }
11152
11153 /*
11154  * prepare INIT transition, parameters configured:
11155  *   - HC configuration
11156  *   - Queue's CDU context
11157  */
11158 static void
11159 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11160                    struct bxe_fastpath            *fp,
11161                    struct ecore_queue_init_params *init_params)
11162 {
11163     uint8_t cos;
11164     int cxt_index, cxt_offset;
11165
11166     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11167     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11168
11169     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11170     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11171
11172     /* HC rate */
11173     init_params->rx.hc_rate =
11174         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11175     init_params->tx.hc_rate =
11176         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11177
11178     /* FW SB ID */
11179     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11180
11181     /* CQ index among the SB indices */
11182     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11183     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11184
11185     /* set maximum number of COSs supported by this queue */
11186     init_params->max_cos = sc->max_cos;
11187
11188     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11189           fp->index, init_params->max_cos);
11190
11191     /* set the context pointers queue object */
11192     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11193         /* XXX change index/cid here if ever support multiple tx CoS */
11194         /* fp->txdata[cos]->cid */
11195         cxt_index = fp->index / ILT_PAGE_CIDS;
11196         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11197         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11198     }
11199 }
11200
11201 /* set flags that are common for the Tx-only and not normal connections */
11202 static unsigned long
11203 bxe_get_common_flags(struct bxe_softc    *sc,
11204                      struct bxe_fastpath *fp,
11205                      uint8_t             zero_stats)
11206 {
11207     unsigned long flags = 0;
11208
11209     /* PF driver will always initialize the Queue to an ACTIVE state */
11210     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11211
11212     /*
11213      * tx only connections collect statistics (on the same index as the
11214      * parent connection). The statistics are zeroed when the parent
11215      * connection is initialized.
11216      */
11217
11218     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11219     if (zero_stats) {
11220         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11221     }
11222
11223     /*
11224      * tx only connections can support tx-switching, though their
11225      * CoS-ness doesn't survive the loopback
11226      */
11227     if (sc->flags & BXE_TX_SWITCHING) {
11228         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11229     }
11230
11231     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11232
11233     return (flags);
11234 }
11235
11236 static unsigned long
11237 bxe_get_q_flags(struct bxe_softc    *sc,
11238                 struct bxe_fastpath *fp,
11239                 uint8_t             leading)
11240 {
11241     unsigned long flags = 0;
11242
11243     if (IS_MF_SD(sc)) {
11244         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11245     }
11246
11247     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11248         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11249 #if __FreeBSD_version >= 800000
11250         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11251 #endif
11252     }
11253
11254     if (leading) {
11255         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11256         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11257     }
11258
11259     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11260
11261     /* merge with common flags */
11262     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11263 }
11264
11265 static void
11266 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11267                       struct bxe_fastpath               *fp,
11268                       struct ecore_general_setup_params *gen_init,
11269                       uint8_t                           cos)
11270 {
11271     gen_init->stat_id = bxe_stats_id(fp);
11272     gen_init->spcl_id = fp->cl_id;
11273     gen_init->mtu = sc->mtu;
11274     gen_init->cos = cos;
11275 }
11276
11277 static void
11278 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11279                  struct bxe_fastpath           *fp,
11280                  struct rxq_pause_params       *pause,
11281                  struct ecore_rxq_setup_params *rxq_init)
11282 {
11283     uint8_t max_sge = 0;
11284     uint16_t sge_sz = 0;
11285     uint16_t tpa_agg_size = 0;
11286
11287     pause->sge_th_lo = SGE_TH_LO(sc);
11288     pause->sge_th_hi = SGE_TH_HI(sc);
11289
11290     /* validate SGE ring has enough to cross high threshold */
11291     if (sc->dropless_fc &&
11292             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11293             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11294         BLOGW(sc, "sge ring threshold limit\n");
11295     }
11296
11297     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11298     tpa_agg_size = (2 * sc->mtu);
11299     if (tpa_agg_size < sc->max_aggregation_size) {
11300         tpa_agg_size = sc->max_aggregation_size;
11301     }
11302
11303     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11304     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11305                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11306     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11307
11308     /* pause - not for e1 */
11309     if (!CHIP_IS_E1(sc)) {
11310         pause->bd_th_lo = BD_TH_LO(sc);
11311         pause->bd_th_hi = BD_TH_HI(sc);
11312
11313         pause->rcq_th_lo = RCQ_TH_LO(sc);
11314         pause->rcq_th_hi = RCQ_TH_HI(sc);
11315
11316         /* validate rings have enough entries to cross high thresholds */
11317         if (sc->dropless_fc &&
11318             pause->bd_th_hi + FW_PREFETCH_CNT >
11319             sc->rx_ring_size) {
11320             BLOGW(sc, "rx bd ring threshold limit\n");
11321         }
11322
11323         if (sc->dropless_fc &&
11324             pause->rcq_th_hi + FW_PREFETCH_CNT >
11325             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11326             BLOGW(sc, "rcq ring threshold limit\n");
11327         }
11328
11329         pause->pri_map = 1;
11330     }
11331
11332     /* rxq setup */
11333     rxq_init->dscr_map   = fp->rx_dma.paddr;
11334     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11335     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11336     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11337
11338     /*
11339      * This should be a maximum number of data bytes that may be
11340      * placed on the BD (not including paddings).
11341      */
11342     rxq_init->buf_sz = (fp->rx_buf_size -
11343                         IP_HEADER_ALIGNMENT_PADDING);
11344
11345     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11346     rxq_init->tpa_agg_sz      = tpa_agg_size;
11347     rxq_init->sge_buf_sz      = sge_sz;
11348     rxq_init->max_sges_pkt    = max_sge;
11349     rxq_init->rss_engine_id   = SC_FUNC(sc);
11350     rxq_init->mcast_engine_id = SC_FUNC(sc);
11351
11352     /*
11353      * Maximum number or simultaneous TPA aggregation for this Queue.
11354      * For PF Clients it should be the maximum available number.
11355      * VF driver(s) may want to define it to a smaller value.
11356      */
11357     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11358
11359     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11360     rxq_init->fw_sb_id = fp->fw_sb_id;
11361
11362     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11363
11364     /*
11365      * configure silent vlan removal
11366      * if multi function mode is afex, then mask default vlan
11367      */
11368     if (IS_MF_AFEX(sc)) {
11369         rxq_init->silent_removal_value =
11370             sc->devinfo.mf_info.afex_def_vlan_tag;
11371         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11372     }
11373 }
11374
11375 static void
11376 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11377                  struct bxe_fastpath           *fp,
11378                  struct ecore_txq_setup_params *txq_init,
11379                  uint8_t                       cos)
11380 {
11381     /*
11382      * XXX If multiple CoS is ever supported then each fastpath structure
11383      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11384      * fp->txdata[cos]->tx_dma.paddr;
11385      */
11386     txq_init->dscr_map     = fp->tx_dma.paddr;
11387     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11388     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11389     txq_init->fw_sb_id     = fp->fw_sb_id;
11390
11391     /*
11392      * set the TSS leading client id for TX classfication to the
11393      * leading RSS client id
11394      */
11395     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11396 }
11397
11398 /*
11399  * This function performs 2 steps in a queue state machine:
11400  *   1) RESET->INIT
11401  *   2) INIT->SETUP
11402  */
11403 static int
11404 bxe_setup_queue(struct bxe_softc    *sc,
11405                 struct bxe_fastpath *fp,
11406                 uint8_t             leading)
11407 {
11408     struct ecore_queue_state_params q_params = { NULL };
11409     struct ecore_queue_setup_params *setup_params =
11410                         &q_params.params.setup;
11411     int rc;
11412
11413     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11414
11415     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11416
11417     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11418
11419     /* we want to wait for completion in this context */
11420     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11421
11422     /* prepare the INIT parameters */
11423     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11424
11425     /* Set the command */
11426     q_params.cmd = ECORE_Q_CMD_INIT;
11427
11428     /* Change the state to INIT */
11429     rc = ecore_queue_state_change(sc, &q_params);
11430     if (rc) {
11431         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11432         return (rc);
11433     }
11434
11435     BLOGD(sc, DBG_LOAD, "init complete\n");
11436
11437     /* now move the Queue to the SETUP state */
11438     memset(setup_params, 0, sizeof(*setup_params));
11439
11440     /* set Queue flags */
11441     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11442
11443     /* set general SETUP parameters */
11444     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11445                           FIRST_TX_COS_INDEX);
11446
11447     bxe_pf_rx_q_prep(sc, fp,
11448                      &setup_params->pause_params,
11449                      &setup_params->rxq_params);
11450
11451     bxe_pf_tx_q_prep(sc, fp,
11452                      &setup_params->txq_params,
11453                      FIRST_TX_COS_INDEX);
11454
11455     /* Set the command */
11456     q_params.cmd = ECORE_Q_CMD_SETUP;
11457
11458     /* change the state to SETUP */
11459     rc = ecore_queue_state_change(sc, &q_params);
11460     if (rc) {
11461         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11462         return (rc);
11463     }
11464
11465     return (rc);
11466 }
11467
11468 static int
11469 bxe_setup_leading(struct bxe_softc *sc)
11470 {
11471     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11472 }
11473
11474 static int
11475 bxe_config_rss_pf(struct bxe_softc            *sc,
11476                   struct ecore_rss_config_obj *rss_obj,
11477                   uint8_t                     config_hash)
11478 {
11479     struct ecore_config_rss_params params = { NULL };
11480     int i;
11481
11482     /*
11483      * Although RSS is meaningless when there is a single HW queue we
11484      * still need it enabled in order to have HW Rx hash generated.
11485      */
11486
11487     params.rss_obj = rss_obj;
11488
11489     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11490
11491     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11492
11493     /* RSS configuration */
11494     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11495     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11496     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11497     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11498     if (rss_obj->udp_rss_v4) {
11499         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11500     }
11501     if (rss_obj->udp_rss_v6) {
11502         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11503     }
11504
11505     /* Hash bits */
11506     params.rss_result_mask = MULTI_MASK;
11507
11508     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11509
11510     if (config_hash) {
11511         /* RSS keys */
11512         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11513             params.rss_key[i] = arc4random();
11514         }
11515
11516         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11517     }
11518
11519     return (ecore_config_rss(sc, &params));
11520 }
11521
11522 static int
11523 bxe_config_rss_eth(struct bxe_softc *sc,
11524                    uint8_t          config_hash)
11525 {
11526     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11527 }
11528
11529 static int
11530 bxe_init_rss_pf(struct bxe_softc *sc)
11531 {
11532     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11533     int i;
11534
11535     /*
11536      * Prepare the initial contents of the indirection table if
11537      * RSS is enabled
11538      */
11539     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11540         sc->rss_conf_obj.ind_table[i] =
11541             (sc->fp->cl_id + (i % num_eth_queues));
11542     }
11543
11544     if (sc->udp_rss) {
11545         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11546     }
11547
11548     /*
11549      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11550      * per-port, so if explicit configuration is needed, do it only
11551      * for a PMF.
11552      *
11553      * For 57712 and newer it's a per-function configuration.
11554      */
11555     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11556 }
11557
11558 static int
11559 bxe_set_mac_one(struct bxe_softc          *sc,
11560                 uint8_t                   *mac,
11561                 struct ecore_vlan_mac_obj *obj,
11562                 uint8_t                   set,
11563                 int                       mac_type,
11564                 unsigned long             *ramrod_flags)
11565 {
11566     struct ecore_vlan_mac_ramrod_params ramrod_param;
11567     int rc;
11568
11569     memset(&ramrod_param, 0, sizeof(ramrod_param));
11570
11571     /* fill in general parameters */
11572     ramrod_param.vlan_mac_obj = obj;
11573     ramrod_param.ramrod_flags = *ramrod_flags;
11574
11575     /* fill a user request section if needed */
11576     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11577         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11578
11579         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11580
11581         /* Set the command: ADD or DEL */
11582         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11583                                             ECORE_VLAN_MAC_DEL;
11584     }
11585
11586     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11587
11588     if (rc == ECORE_EXISTS) {
11589         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11590         /* do not treat adding same MAC as error */
11591         rc = 0;
11592     } else if (rc < 0) {
11593         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11594     }
11595
11596     return (rc);
11597 }
11598
11599 static int
11600 bxe_set_eth_mac(struct bxe_softc *sc,
11601                 uint8_t          set)
11602 {
11603     unsigned long ramrod_flags = 0;
11604
11605     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11606
11607     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11608
11609     /* Eth MAC is set on RSS leading client (fp[0]) */
11610     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11611                             &sc->sp_objs->mac_obj,
11612                             set, ECORE_ETH_MAC, &ramrod_flags));
11613 }
11614
11615 static int
11616 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11617 {
11618     uint32_t sel_phy_idx = 0;
11619
11620     if (sc->link_params.num_phys <= 1) {
11621         return (ELINK_INT_PHY);
11622     }
11623
11624     if (sc->link_vars.link_up) {
11625         sel_phy_idx = ELINK_EXT_PHY1;
11626         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11627         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11628             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11629              ELINK_SUPPORTED_FIBRE))
11630             sel_phy_idx = ELINK_EXT_PHY2;
11631     } else {
11632         switch (elink_phy_selection(&sc->link_params)) {
11633         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11634         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11635         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11636                sel_phy_idx = ELINK_EXT_PHY1;
11637                break;
11638         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11639         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11640                sel_phy_idx = ELINK_EXT_PHY2;
11641                break;
11642         }
11643     }
11644
11645     return (sel_phy_idx);
11646 }
11647
11648 static int
11649 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11650 {
11651     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11652
11653     /*
11654      * The selected activated PHY is always after swapping (in case PHY
11655      * swapping is enabled). So when swapping is enabled, we need to reverse
11656      * the configuration
11657      */
11658
11659     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11660         if (sel_phy_idx == ELINK_EXT_PHY1)
11661             sel_phy_idx = ELINK_EXT_PHY2;
11662         else if (sel_phy_idx == ELINK_EXT_PHY2)
11663             sel_phy_idx = ELINK_EXT_PHY1;
11664     }
11665
11666     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11667 }
11668
11669 static void
11670 bxe_set_requested_fc(struct bxe_softc *sc)
11671 {
11672     /*
11673      * Initialize link parameters structure variables
11674      * It is recommended to turn off RX FC for jumbo frames
11675      * for better performance
11676      */
11677     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11678         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11679     } else {
11680         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11681     }
11682 }
11683
11684 static void
11685 bxe_calc_fc_adv(struct bxe_softc *sc)
11686 {
11687     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11688
11689
11690     sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11691                                            ADVERTISED_Pause);
11692
11693     switch (sc->link_vars.ieee_fc &
11694             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11695
11696     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11697         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11698                                           ADVERTISED_Pause);
11699         break;
11700
11701     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11702         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11703         break;
11704
11705     default:
11706         break;
11707
11708     }
11709 }
11710
11711 static uint16_t
11712 bxe_get_mf_speed(struct bxe_softc *sc)
11713 {
11714     uint16_t line_speed = sc->link_vars.line_speed;
11715     if (IS_MF(sc)) {
11716         uint16_t maxCfg =
11717             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11718
11719         /* calculate the current MAX line speed limit for the MF devices */
11720         if (IS_MF_SI(sc)) {
11721             line_speed = (line_speed * maxCfg) / 100;
11722         } else { /* SD mode */
11723             uint16_t vn_max_rate = maxCfg * 100;
11724
11725             if (vn_max_rate < line_speed) {
11726                 line_speed = vn_max_rate;
11727             }
11728         }
11729     }
11730
11731     return (line_speed);
11732 }
11733
11734 static void
11735 bxe_fill_report_data(struct bxe_softc            *sc,
11736                      struct bxe_link_report_data *data)
11737 {
11738     uint16_t line_speed = bxe_get_mf_speed(sc);
11739
11740     memset(data, 0, sizeof(*data));
11741
11742     /* fill the report data with the effective line speed */
11743     data->line_speed = line_speed;
11744
11745     /* Link is down */
11746     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11747         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11748     }
11749
11750     /* Full DUPLEX */
11751     if (sc->link_vars.duplex == DUPLEX_FULL) {
11752         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11753     }
11754
11755     /* Rx Flow Control is ON */
11756     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11757         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11758     }
11759
11760     /* Tx Flow Control is ON */
11761     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11762         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11763     }
11764 }
11765
11766 /* report link status to OS, should be called under phy_lock */
11767 static void
11768 bxe_link_report_locked(struct bxe_softc *sc)
11769 {
11770     struct bxe_link_report_data cur_data;
11771
11772     /* reread mf_cfg */
11773     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11774         bxe_read_mf_cfg(sc);
11775     }
11776
11777     /* Read the current link report info */
11778     bxe_fill_report_data(sc, &cur_data);
11779
11780     /* Don't report link down or exactly the same link status twice */
11781     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11782         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11783                       &sc->last_reported_link.link_report_flags) &&
11784          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11785                       &cur_data.link_report_flags))) {
11786         return;
11787     }
11788
11789         ELINK_DEBUG_P2(sc, "Change in link status : cur_data = %x, last_reported_link = %x\n",
11790                                         cur_data.link_report_flags, sc->last_reported_link.link_report_flags);
11791     sc->link_cnt++;
11792
11793         ELINK_DEBUG_P1(sc, "link status change count = %x\n", sc->link_cnt);
11794     /* report new link params and remember the state for the next time */
11795     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11796
11797     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11798                      &cur_data.link_report_flags)) {
11799         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11800     } else {
11801         const char *duplex;
11802         const char *flow;
11803
11804         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11805                                    &cur_data.link_report_flags)) {
11806             duplex = "full";
11807                         ELINK_DEBUG_P0(sc, "link set to full duplex\n");
11808         } else {
11809             duplex = "half";
11810                         ELINK_DEBUG_P0(sc, "link set to half duplex\n");
11811         }
11812
11813         /*
11814          * Handle the FC at the end so that only these flags would be
11815          * possibly set. This way we may easily check if there is no FC
11816          * enabled.
11817          */
11818         if (cur_data.link_report_flags) {
11819             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11820                              &cur_data.link_report_flags) &&
11821                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11822                              &cur_data.link_report_flags)) {
11823                 flow = "ON - receive & transmit";
11824             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11825                                     &cur_data.link_report_flags) &&
11826                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11827                                      &cur_data.link_report_flags)) {
11828                 flow = "ON - receive";
11829             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11830                                      &cur_data.link_report_flags) &&
11831                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11832                                     &cur_data.link_report_flags)) {
11833                 flow = "ON - transmit";
11834             } else {
11835                 flow = "none"; /* possible? */
11836             }
11837         } else {
11838             flow = "none";
11839         }
11840
11841         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11842         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11843               cur_data.line_speed, duplex, flow);
11844     }
11845 }
11846
11847 static void
11848 bxe_link_report(struct bxe_softc *sc)
11849 {
11850     bxe_acquire_phy_lock(sc);
11851     bxe_link_report_locked(sc);
11852     bxe_release_phy_lock(sc);
11853 }
11854
11855 static void
11856 bxe_link_status_update(struct bxe_softc *sc)
11857 {
11858     if (sc->state != BXE_STATE_OPEN) {
11859         return;
11860     }
11861
11862     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11863         elink_link_status_update(&sc->link_params, &sc->link_vars);
11864     } else {
11865         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11866                                   ELINK_SUPPORTED_10baseT_Full |
11867                                   ELINK_SUPPORTED_100baseT_Half |
11868                                   ELINK_SUPPORTED_100baseT_Full |
11869                                   ELINK_SUPPORTED_1000baseT_Full |
11870                                   ELINK_SUPPORTED_2500baseX_Full |
11871                                   ELINK_SUPPORTED_10000baseT_Full |
11872                                   ELINK_SUPPORTED_TP |
11873                                   ELINK_SUPPORTED_FIBRE |
11874                                   ELINK_SUPPORTED_Autoneg |
11875                                   ELINK_SUPPORTED_Pause |
11876                                   ELINK_SUPPORTED_Asym_Pause);
11877         sc->port.advertising[0] = sc->port.supported[0];
11878
11879         sc->link_params.sc                = sc;
11880         sc->link_params.port              = SC_PORT(sc);
11881         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11882         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11883         sc->link_params.req_line_speed[0] = SPEED_10000;
11884         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11885         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11886
11887         if (CHIP_REV_IS_FPGA(sc)) {
11888             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11889             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11890             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11891                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11892         } else {
11893             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11894             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11895             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11896                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11897         }
11898
11899         sc->link_vars.link_up = 1;
11900
11901         sc->link_vars.duplex    = DUPLEX_FULL;
11902         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11903
11904         if (IS_PF(sc)) {
11905             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11906             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11907             bxe_link_report(sc);
11908         }
11909     }
11910
11911     if (IS_PF(sc)) {
11912         if (sc->link_vars.link_up) {
11913             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11914         } else {
11915             bxe_stats_handle(sc, STATS_EVENT_STOP);
11916         }
11917         bxe_link_report(sc);
11918     } else {
11919         bxe_link_report(sc);
11920         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11921     }
11922 }
11923
11924 static int
11925 bxe_initial_phy_init(struct bxe_softc *sc,
11926                      int              load_mode)
11927 {
11928     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11929     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11930     struct elink_params *lp = &sc->link_params;
11931
11932     bxe_set_requested_fc(sc);
11933
11934     if (CHIP_REV_IS_SLOW(sc)) {
11935         uint32_t bond = CHIP_BOND_ID(sc);
11936         uint32_t feat = 0;
11937
11938         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11939             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11940         } else if (bond & 0x4) {
11941             if (CHIP_IS_E3(sc)) {
11942                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11943             } else {
11944                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11945             }
11946         } else if (bond & 0x8) {
11947             if (CHIP_IS_E3(sc)) {
11948                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11949             } else {
11950                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11951             }
11952         }
11953
11954         /* disable EMAC for E3 and above */
11955         if (bond & 0x2) {
11956             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11957         }
11958
11959         sc->link_params.feature_config_flags |= feat;
11960     }
11961
11962     bxe_acquire_phy_lock(sc);
11963
11964     if (load_mode == LOAD_DIAG) {
11965         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11966         /* Prefer doing PHY loopback at 10G speed, if possible */
11967         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11968             if (lp->speed_cap_mask[cfg_idx] &
11969                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11970                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11971             } else {
11972                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11973             }
11974         }
11975     }
11976
11977     if (load_mode == LOAD_LOOPBACK_EXT) {
11978         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11979     }
11980
11981     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11982
11983     bxe_release_phy_lock(sc);
11984
11985     bxe_calc_fc_adv(sc);
11986
11987     if (sc->link_vars.link_up) {
11988         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11989         bxe_link_report(sc);
11990     }
11991
11992     if (!CHIP_REV_IS_SLOW(sc)) {
11993         bxe_periodic_start(sc);
11994     }
11995
11996     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11997     return (rc);
11998 }
11999
12000 /* must be called under IF_ADDR_LOCK */
12001 static int
12002 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12003                          struct ecore_mcast_ramrod_params *p)
12004 {
12005     struct ifnet *ifp = sc->ifnet;
12006     int mc_count = 0;
12007     struct ifmultiaddr *ifma;
12008     struct ecore_mcast_list_elem *mc_mac;
12009
12010     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12011         if (ifma->ifma_addr->sa_family != AF_LINK) {
12012             continue;
12013         }
12014
12015         mc_count++;
12016     }
12017
12018     ECORE_LIST_INIT(&p->mcast_list);
12019     p->mcast_list_len = 0;
12020
12021     if (!mc_count) {
12022         return (0);
12023     }
12024
12025     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12026                     (M_NOWAIT | M_ZERO));
12027     if (!mc_mac) {
12028         BLOGE(sc, "Failed to allocate temp mcast list\n");
12029         return (-1);
12030     }
12031     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12032
12033     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12034         if (ifma->ifma_addr->sa_family != AF_LINK) {
12035             continue;
12036         }
12037
12038         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12039         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12040
12041         BLOGD(sc, DBG_LOAD,
12042               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X and mc_count %d\n",
12043               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12044               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5], mc_count);
12045        mc_mac++;
12046     }
12047
12048     p->mcast_list_len = mc_count;
12049
12050     return (0);
12051 }
12052
12053 static void
12054 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12055 {
12056     struct ecore_mcast_list_elem *mc_mac =
12057         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12058                                struct ecore_mcast_list_elem,
12059                                link);
12060
12061     if (mc_mac) {
12062         /* only a single free as all mc_macs are in the same heap array */
12063         free(mc_mac, M_DEVBUF);
12064     }
12065 }
12066
12067 static int
12068 bxe_set_mc_list(struct bxe_softc *sc)
12069 {
12070     struct ecore_mcast_ramrod_params rparam = { NULL };
12071     int rc = 0;
12072
12073     rparam.mcast_obj = &sc->mcast_obj;
12074
12075     BXE_MCAST_LOCK(sc);
12076
12077     /* first, clear all configured multicast MACs */
12078     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12079     if (rc < 0) {
12080         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12081         /* Manual backport parts of FreeBSD upstream r284470. */
12082         BXE_MCAST_UNLOCK(sc);
12083         return (rc);
12084     }
12085
12086     /* configure a new MACs list */
12087     rc = bxe_init_mcast_macs_list(sc, &rparam);
12088     if (rc) {
12089         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12090         BXE_MCAST_UNLOCK(sc);
12091         return (rc);
12092     }
12093
12094     /* Now add the new MACs */
12095     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12096     if (rc < 0) {
12097         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12098     }
12099
12100     bxe_free_mcast_macs_list(&rparam);
12101
12102     BXE_MCAST_UNLOCK(sc);
12103
12104     return (rc);
12105 }
12106
12107 static int
12108 bxe_set_uc_list(struct bxe_softc *sc)
12109 {
12110     struct ifnet *ifp = sc->ifnet;
12111     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12112     struct ifaddr *ifa;
12113     unsigned long ramrod_flags = 0;
12114     int rc;
12115
12116 #if __FreeBSD_version < 800000
12117     IF_ADDR_LOCK(ifp);
12118 #else
12119     if_addr_rlock(ifp);
12120 #endif
12121
12122     /* first schedule a cleanup up of old configuration */
12123     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12124     if (rc < 0) {
12125         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12126 #if __FreeBSD_version < 800000
12127         IF_ADDR_UNLOCK(ifp);
12128 #else
12129         if_addr_runlock(ifp);
12130 #endif
12131         return (rc);
12132     }
12133
12134     ifa = ifp->if_addr;
12135     while (ifa) {
12136         if (ifa->ifa_addr->sa_family != AF_LINK) {
12137             ifa = TAILQ_NEXT(ifa, ifa_link);
12138             continue;
12139         }
12140
12141         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12142                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12143         if (rc == -EEXIST) {
12144             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12145             /* do not treat adding same MAC as an error */
12146             rc = 0;
12147         } else if (rc < 0) {
12148             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12149 #if __FreeBSD_version < 800000
12150             IF_ADDR_UNLOCK(ifp);
12151 #else
12152             if_addr_runlock(ifp);
12153 #endif
12154             return (rc);
12155         }
12156
12157         ifa = TAILQ_NEXT(ifa, ifa_link);
12158     }
12159
12160 #if __FreeBSD_version < 800000
12161     IF_ADDR_UNLOCK(ifp);
12162 #else
12163     if_addr_runlock(ifp);
12164 #endif
12165
12166     /* Execute the pending commands */
12167     bit_set(&ramrod_flags, RAMROD_CONT);
12168     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12169                             ECORE_UC_LIST_MAC, &ramrod_flags));
12170 }
12171
12172 static void
12173 bxe_set_rx_mode(struct bxe_softc *sc)
12174 {
12175     struct ifnet *ifp = sc->ifnet;
12176     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12177
12178     if (sc->state != BXE_STATE_OPEN) {
12179         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12180         return;
12181     }
12182
12183     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12184
12185     if (ifp->if_flags & IFF_PROMISC) {
12186         rx_mode = BXE_RX_MODE_PROMISC;
12187     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12188                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12189                 CHIP_IS_E1(sc))) {
12190         rx_mode = BXE_RX_MODE_ALLMULTI;
12191     } else {
12192         if (IS_PF(sc)) {
12193             /* some multicasts */
12194             if (bxe_set_mc_list(sc) < 0) {
12195                 rx_mode = BXE_RX_MODE_ALLMULTI;
12196             }
12197             if (bxe_set_uc_list(sc) < 0) {
12198                 rx_mode = BXE_RX_MODE_PROMISC;
12199             }
12200         }
12201     }
12202
12203     sc->rx_mode = rx_mode;
12204
12205     /* schedule the rx_mode command */
12206     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12207         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12208         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12209         return;
12210     }
12211
12212     if (IS_PF(sc)) {
12213         bxe_set_storm_rx_mode(sc);
12214     }
12215 }
12216
12217
12218 /* update flags in shmem */
12219 static void
12220 bxe_update_drv_flags(struct bxe_softc *sc,
12221                      uint32_t         flags,
12222                      uint32_t         set)
12223 {
12224     uint32_t drv_flags;
12225
12226     if (SHMEM2_HAS(sc, drv_flags)) {
12227         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12228         drv_flags = SHMEM2_RD(sc, drv_flags);
12229
12230         if (set) {
12231             SET_FLAGS(drv_flags, flags);
12232         } else {
12233             RESET_FLAGS(drv_flags, flags);
12234         }
12235
12236         SHMEM2_WR(sc, drv_flags, drv_flags);
12237         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12238
12239         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12240     }
12241 }
12242
12243 /* periodic timer callout routine, only runs when the interface is up */
12244
12245 static void
12246 bxe_periodic_callout_func(void *xsc)
12247 {
12248     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12249     int i;
12250
12251     if (!BXE_CORE_TRYLOCK(sc)) {
12252         /* just bail and try again next time */
12253
12254         if ((sc->state == BXE_STATE_OPEN) &&
12255             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12256             /* schedule the next periodic callout */
12257             callout_reset(&sc->periodic_callout, hz,
12258                           bxe_periodic_callout_func, sc);
12259         }
12260
12261         return;
12262     }
12263
12264     if ((sc->state != BXE_STATE_OPEN) ||
12265         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12266         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12267         BXE_CORE_UNLOCK(sc);
12268         return;
12269     }
12270
12271
12272     /* Check for TX timeouts on any fastpath. */
12273     FOR_EACH_QUEUE(sc, i) {
12274         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12275             /* Ruh-Roh, chip was reset! */
12276             break;
12277         }
12278     }
12279
12280     if (!CHIP_REV_IS_SLOW(sc)) {
12281         /*
12282          * This barrier is needed to ensure the ordering between the writing
12283          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12284          * the reading here.
12285          */
12286         mb();
12287         if (sc->port.pmf) {
12288             bxe_acquire_phy_lock(sc);
12289             elink_period_func(&sc->link_params, &sc->link_vars);
12290             bxe_release_phy_lock(sc);
12291         }
12292     }
12293
12294     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12295         int mb_idx = SC_FW_MB_IDX(sc);
12296         uint32_t drv_pulse;
12297         uint32_t mcp_pulse;
12298
12299         ++sc->fw_drv_pulse_wr_seq;
12300         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12301
12302         drv_pulse = sc->fw_drv_pulse_wr_seq;
12303         bxe_drv_pulse(sc);
12304
12305         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12306                      MCP_PULSE_SEQ_MASK);
12307
12308         /*
12309          * The delta between driver pulse and mcp response should
12310          * be 1 (before mcp response) or 0 (after mcp response).
12311          */
12312         if ((drv_pulse != mcp_pulse) &&
12313             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12314             /* someone lost a heartbeat... */
12315             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12316                   drv_pulse, mcp_pulse);
12317         }
12318     }
12319
12320     /* state is BXE_STATE_OPEN */
12321     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12322
12323     BXE_CORE_UNLOCK(sc);
12324
12325     if ((sc->state == BXE_STATE_OPEN) &&
12326         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12327         /* schedule the next periodic callout */
12328         callout_reset(&sc->periodic_callout, hz,
12329                       bxe_periodic_callout_func, sc);
12330     }
12331 }
12332
12333 static void
12334 bxe_periodic_start(struct bxe_softc *sc)
12335 {
12336     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12337     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12338 }
12339
12340 static void
12341 bxe_periodic_stop(struct bxe_softc *sc)
12342 {
12343     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12344     callout_drain(&sc->periodic_callout);
12345 }
12346
12347 /* start the controller */
12348 static __noinline int
12349 bxe_nic_load(struct bxe_softc *sc,
12350              int              load_mode)
12351 {
12352     uint32_t val;
12353     int load_code = 0;
12354     int i, rc = 0;
12355
12356     BXE_CORE_LOCK_ASSERT(sc);
12357
12358     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12359
12360     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12361
12362     if (IS_PF(sc)) {
12363         /* must be called before memory allocation and HW init */
12364         bxe_ilt_set_info(sc);
12365     }
12366
12367     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12368
12369     bxe_set_fp_rx_buf_size(sc);
12370
12371     if (bxe_alloc_fp_buffers(sc) != 0) {
12372         BLOGE(sc, "Failed to allocate fastpath memory\n");
12373         sc->state = BXE_STATE_CLOSED;
12374         rc = ENOMEM;
12375         goto bxe_nic_load_error0;
12376     }
12377
12378     if (bxe_alloc_mem(sc) != 0) {
12379         sc->state = BXE_STATE_CLOSED;
12380         rc = ENOMEM;
12381         goto bxe_nic_load_error0;
12382     }
12383
12384     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12385         sc->state = BXE_STATE_CLOSED;
12386         rc = ENOMEM;
12387         goto bxe_nic_load_error0;
12388     }
12389
12390     if (IS_PF(sc)) {
12391         /* set pf load just before approaching the MCP */
12392         bxe_set_pf_load(sc);
12393
12394         /* if MCP exists send load request and analyze response */
12395         if (!BXE_NOMCP(sc)) {
12396             /* attempt to load pf */
12397             if (bxe_nic_load_request(sc, &load_code) != 0) {
12398                 sc->state = BXE_STATE_CLOSED;
12399                 rc = ENXIO;
12400                 goto bxe_nic_load_error1;
12401             }
12402
12403             /* what did the MCP say? */
12404             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12405                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12406                 sc->state = BXE_STATE_CLOSED;
12407                 rc = ENXIO;
12408                 goto bxe_nic_load_error2;
12409             }
12410         } else {
12411             BLOGI(sc, "Device has no MCP!\n");
12412             load_code = bxe_nic_load_no_mcp(sc);
12413         }
12414
12415         /* mark PMF if applicable */
12416         bxe_nic_load_pmf(sc, load_code);
12417
12418         /* Init Function state controlling object */
12419         bxe_init_func_obj(sc);
12420
12421         /* Initialize HW */
12422         if (bxe_init_hw(sc, load_code) != 0) {
12423             BLOGE(sc, "HW init failed\n");
12424             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12425             sc->state = BXE_STATE_CLOSED;
12426             rc = ENXIO;
12427             goto bxe_nic_load_error2;
12428         }
12429     }
12430
12431     /* set ALWAYS_ALIVE bit in shmem */
12432     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12433     bxe_drv_pulse(sc);
12434     sc->flags |= BXE_NO_PULSE;
12435
12436     /* attach interrupts */
12437     if (bxe_interrupt_attach(sc) != 0) {
12438         sc->state = BXE_STATE_CLOSED;
12439         rc = ENXIO;
12440         goto bxe_nic_load_error2;
12441     }
12442
12443     bxe_nic_init(sc, load_code);
12444
12445     /* Init per-function objects */
12446     if (IS_PF(sc)) {
12447         bxe_init_objs(sc);
12448         // XXX bxe_iov_nic_init(sc);
12449
12450         /* set AFEX default VLAN tag to an invalid value */
12451         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12452         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12453
12454         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12455         rc = bxe_func_start(sc);
12456         if (rc) {
12457             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12458             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12459             sc->state = BXE_STATE_ERROR;
12460             goto bxe_nic_load_error3;
12461         }
12462
12463         /* send LOAD_DONE command to MCP */
12464         if (!BXE_NOMCP(sc)) {
12465             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12466             if (!load_code) {
12467                 BLOGE(sc, "MCP response failure, aborting\n");
12468                 sc->state = BXE_STATE_ERROR;
12469                 rc = ENXIO;
12470                 goto bxe_nic_load_error3;
12471             }
12472         }
12473
12474         rc = bxe_setup_leading(sc);
12475         if (rc) {
12476             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12477             sc->state = BXE_STATE_ERROR;
12478             goto bxe_nic_load_error3;
12479         }
12480
12481         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12482             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12483             if (rc) {
12484                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12485                 sc->state = BXE_STATE_ERROR;
12486                 goto bxe_nic_load_error3;
12487             }
12488         }
12489
12490         rc = bxe_init_rss_pf(sc);
12491         if (rc) {
12492             BLOGE(sc, "PF RSS init failed\n");
12493             sc->state = BXE_STATE_ERROR;
12494             goto bxe_nic_load_error3;
12495         }
12496     }
12497     /* XXX VF */
12498
12499     /* now when Clients are configured we are ready to work */
12500     sc->state = BXE_STATE_OPEN;
12501
12502     /* Configure a ucast MAC */
12503     if (IS_PF(sc)) {
12504         rc = bxe_set_eth_mac(sc, TRUE);
12505     }
12506     if (rc) {
12507         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12508         sc->state = BXE_STATE_ERROR;
12509         goto bxe_nic_load_error3;
12510     }
12511
12512     if (sc->port.pmf) {
12513         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12514         if (rc) {
12515             sc->state = BXE_STATE_ERROR;
12516             goto bxe_nic_load_error3;
12517         }
12518     }
12519
12520     sc->link_params.feature_config_flags &=
12521         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12522
12523     /* start fast path */
12524
12525     /* Initialize Rx filter */
12526     bxe_set_rx_mode(sc);
12527
12528     /* start the Tx */
12529     switch (/* XXX load_mode */LOAD_OPEN) {
12530     case LOAD_NORMAL:
12531     case LOAD_OPEN:
12532         break;
12533
12534     case LOAD_DIAG:
12535     case LOAD_LOOPBACK_EXT:
12536         sc->state = BXE_STATE_DIAG;
12537         break;
12538
12539     default:
12540         break;
12541     }
12542
12543     if (sc->port.pmf) {
12544         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12545     } else {
12546         bxe_link_status_update(sc);
12547     }
12548
12549     /* start the periodic timer callout */
12550     bxe_periodic_start(sc);
12551
12552     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12553         /* mark driver is loaded in shmem2 */
12554         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12555         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12556                   (val |
12557                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12558                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12559     }
12560
12561     /* wait for all pending SP commands to complete */
12562     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12563         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12564         bxe_periodic_stop(sc);
12565         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12566         return (ENXIO);
12567     }
12568
12569     /* Tell the stack the driver is running! */
12570     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12571
12572     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12573
12574     return (0);
12575
12576 bxe_nic_load_error3:
12577
12578     if (IS_PF(sc)) {
12579         bxe_int_disable_sync(sc, 1);
12580
12581         /* clean out queued objects */
12582         bxe_squeeze_objects(sc);
12583     }
12584
12585     bxe_interrupt_detach(sc);
12586
12587 bxe_nic_load_error2:
12588
12589     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12590         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12591         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12592     }
12593
12594     sc->port.pmf = 0;
12595
12596 bxe_nic_load_error1:
12597
12598     /* clear pf_load status, as it was already set */
12599     if (IS_PF(sc)) {
12600         bxe_clear_pf_load(sc);
12601     }
12602
12603 bxe_nic_load_error0:
12604
12605     bxe_free_fw_stats_mem(sc);
12606     bxe_free_fp_buffers(sc);
12607     bxe_free_mem(sc);
12608
12609     return (rc);
12610 }
12611
12612 static int
12613 bxe_init_locked(struct bxe_softc *sc)
12614 {
12615     int other_engine = SC_PATH(sc) ? 0 : 1;
12616     uint8_t other_load_status, load_status;
12617     uint8_t global = FALSE;
12618     int rc;
12619
12620     BXE_CORE_LOCK_ASSERT(sc);
12621
12622     /* check if the driver is already running */
12623     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12624         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12625         return (0);
12626     }
12627
12628     bxe_set_power_state(sc, PCI_PM_D0);
12629
12630     /*
12631      * If parity occurred during the unload, then attentions and/or
12632      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12633      * loaded on the current engine to complete the recovery. Parity recovery
12634      * is only relevant for PF driver.
12635      */
12636     if (IS_PF(sc)) {
12637         other_load_status = bxe_get_load_status(sc, other_engine);
12638         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12639
12640         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12641             bxe_chk_parity_attn(sc, &global, TRUE)) {
12642             do {
12643                 /*
12644                  * If there are attentions and they are in global blocks, set
12645                  * the GLOBAL_RESET bit regardless whether it will be this
12646                  * function that will complete the recovery or not.
12647                  */
12648                 if (global) {
12649                     bxe_set_reset_global(sc);
12650                 }
12651
12652                 /*
12653                  * Only the first function on the current engine should try
12654                  * to recover in open. In case of attentions in global blocks
12655                  * only the first in the chip should try to recover.
12656                  */
12657                 if ((!load_status && (!global || !other_load_status)) &&
12658                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12659                     BLOGI(sc, "Recovered during init\n");
12660                     break;
12661                 }
12662
12663                 /* recovery has failed... */
12664                 bxe_set_power_state(sc, PCI_PM_D3hot);
12665                 sc->recovery_state = BXE_RECOVERY_FAILED;
12666
12667                 BLOGE(sc, "Recovery flow hasn't properly "
12668                           "completed yet, try again later. "
12669                           "If you still see this message after a "
12670                           "few retries then power cycle is required.\n");
12671
12672                 rc = ENXIO;
12673                 goto bxe_init_locked_done;
12674             } while (0);
12675         }
12676     }
12677
12678     sc->recovery_state = BXE_RECOVERY_DONE;
12679
12680     rc = bxe_nic_load(sc, LOAD_OPEN);
12681
12682 bxe_init_locked_done:
12683
12684     if (rc) {
12685         /* Tell the stack the driver is NOT running! */
12686         BLOGE(sc, "Initialization failed, "
12687                   "stack notified driver is NOT running!\n");
12688         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12689     }
12690
12691     return (rc);
12692 }
12693
12694 static int
12695 bxe_stop_locked(struct bxe_softc *sc)
12696 {
12697     BXE_CORE_LOCK_ASSERT(sc);
12698     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12699 }
12700
12701 /*
12702  * Handles controller initialization when called from an unlocked routine.
12703  * ifconfig calls this function.
12704  *
12705  * Returns:
12706  *   void
12707  */
12708 static void
12709 bxe_init(void *xsc)
12710 {
12711     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12712
12713     BXE_CORE_LOCK(sc);
12714     bxe_init_locked(sc);
12715     BXE_CORE_UNLOCK(sc);
12716 }
12717
12718 static int
12719 bxe_init_ifnet(struct bxe_softc *sc)
12720 {
12721     struct ifnet *ifp;
12722
12723     /* ifconfig entrypoint for media type/status reporting */
12724     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12725                  bxe_ifmedia_update,
12726                  bxe_ifmedia_status);
12727
12728     /* set the default interface values */
12729     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12730     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12731     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12732
12733     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12734         BLOGI(sc, "IFMEDIA flags : %x\n", sc->ifmedia.ifm_media);
12735
12736     /* allocate the ifnet structure */
12737     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12738         BLOGE(sc, "Interface allocation failed!\n");
12739         return (ENXIO);
12740     }
12741
12742     ifp->if_softc = sc;
12743     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12744     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12745     ifp->if_ioctl = bxe_ioctl;
12746     ifp->if_start = bxe_tx_start;
12747 #if __FreeBSD_version >= 901504
12748     ifp->if_transmit = bxe_tx_mq_start;
12749     ifp->if_qflush = bxe_mq_flush;
12750 #endif
12751 #ifdef FreeBSD8_0
12752     ifp->if_timer = 0;
12753 #endif
12754     ifp->if_init = bxe_init;
12755     ifp->if_mtu = sc->mtu;
12756     ifp->if_hwassist = (CSUM_IP       |
12757                         CSUM_TCP      |
12758                         CSUM_UDP      |
12759                         CSUM_TSO      |
12760                         CSUM_TCP_IPV6 |
12761                         CSUM_UDP_IPV6);
12762     ifp->if_capabilities =
12763 #if __FreeBSD_version < 700000
12764         (IFCAP_VLAN_MTU       |
12765          IFCAP_VLAN_HWTAGGING |
12766          IFCAP_HWCSUM         |
12767          IFCAP_JUMBO_MTU      |
12768          IFCAP_LRO);
12769 #else
12770         (IFCAP_VLAN_MTU       |
12771          IFCAP_VLAN_HWTAGGING |
12772          IFCAP_VLAN_HWTSO     |
12773          IFCAP_VLAN_HWFILTER  |
12774          IFCAP_VLAN_HWCSUM    |
12775          IFCAP_HWCSUM         |
12776          IFCAP_JUMBO_MTU      |
12777          IFCAP_LRO            |
12778          IFCAP_TSO4           |
12779          IFCAP_TSO6           |
12780          IFCAP_WOL_MAGIC);
12781 #endif
12782     ifp->if_capenable = ifp->if_capabilities;
12783     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12784 #if __FreeBSD_version < 1000025
12785     ifp->if_baudrate = 1000000000;
12786 #else
12787     if_initbaudrate(ifp, IF_Gbps(10));
12788 #endif
12789     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12790
12791     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12792     IFQ_SET_READY(&ifp->if_snd);
12793
12794     sc->ifnet = ifp;
12795
12796     /* attach to the Ethernet interface list */
12797     ether_ifattach(ifp, sc->link_params.mac_addr);
12798
12799     return (0);
12800 }
12801
12802 static void
12803 bxe_deallocate_bars(struct bxe_softc *sc)
12804 {
12805     int i;
12806
12807     for (i = 0; i < MAX_BARS; i++) {
12808         if (sc->bar[i].resource != NULL) {
12809             bus_release_resource(sc->dev,
12810                                  SYS_RES_MEMORY,
12811                                  sc->bar[i].rid,
12812                                  sc->bar[i].resource);
12813             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12814                   i, PCIR_BAR(i));
12815         }
12816     }
12817 }
12818
12819 static int
12820 bxe_allocate_bars(struct bxe_softc *sc)
12821 {
12822     u_int flags;
12823     int i;
12824
12825     memset(sc->bar, 0, sizeof(sc->bar));
12826
12827     for (i = 0; i < MAX_BARS; i++) {
12828
12829         /* memory resources reside at BARs 0, 2, 4 */
12830         /* Run `pciconf -lb` to see mappings */
12831         if ((i != 0) && (i != 2) && (i != 4)) {
12832             continue;
12833         }
12834
12835         sc->bar[i].rid = PCIR_BAR(i);
12836
12837         flags = RF_ACTIVE;
12838         if (i == 0) {
12839             flags |= RF_SHAREABLE;
12840         }
12841
12842         if ((sc->bar[i].resource =
12843              bus_alloc_resource_any(sc->dev,
12844                                     SYS_RES_MEMORY,
12845                                     &sc->bar[i].rid,
12846                                     flags)) == NULL) {
12847             return (0);
12848         }
12849
12850         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12851         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12852         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12853
12854         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12855               i, PCIR_BAR(i),
12856               (void *)rman_get_start(sc->bar[i].resource),
12857               (void *)rman_get_end(sc->bar[i].resource),
12858               rman_get_size(sc->bar[i].resource),
12859               (void *)sc->bar[i].kva);
12860     }
12861
12862     return (0);
12863 }
12864
12865 static void
12866 bxe_get_function_num(struct bxe_softc *sc)
12867 {
12868     uint32_t val = 0;
12869
12870     /*
12871      * Read the ME register to get the function number. The ME register
12872      * holds the relative-function number and absolute-function number. The
12873      * absolute-function number appears only in E2 and above. Before that
12874      * these bits always contained zero, therefore we cannot blindly use them.
12875      */
12876
12877     val = REG_RD(sc, BAR_ME_REGISTER);
12878
12879     sc->pfunc_rel =
12880         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12881     sc->path_id =
12882         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12883
12884     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12885         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12886     } else {
12887         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12888     }
12889
12890     BLOGD(sc, DBG_LOAD,
12891           "Relative function %d, Absolute function %d, Path %d\n",
12892           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12893 }
12894
12895 static uint32_t
12896 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12897 {
12898     uint32_t shmem2_size;
12899     uint32_t offset;
12900     uint32_t mf_cfg_offset_value;
12901
12902     /* Non 57712 */
12903     offset = (SHMEM_RD(sc, func_mb) +
12904               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12905
12906     /* 57712 plus */
12907     if (sc->devinfo.shmem2_base != 0) {
12908         shmem2_size = SHMEM2_RD(sc, size);
12909         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12910             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12911             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12912                 offset = mf_cfg_offset_value;
12913             }
12914         }
12915     }
12916
12917     return (offset);
12918 }
12919
12920 static uint32_t
12921 bxe_pcie_capability_read(struct bxe_softc *sc,
12922                          int    reg,
12923                          int    width)
12924 {
12925     int pcie_reg;
12926
12927     /* ensure PCIe capability is enabled */
12928     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12929         if (pcie_reg != 0) {
12930             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12931             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12932         }
12933     }
12934
12935     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12936
12937     return (0);
12938 }
12939
12940 static uint8_t
12941 bxe_is_pcie_pending(struct bxe_softc *sc)
12942 {
12943     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12944             PCIM_EXP_STA_TRANSACTION_PND);
12945 }
12946
12947 /*
12948  * Walk the PCI capabiites list for the device to find what features are
12949  * supported. These capabilites may be enabled/disabled by firmware so it's
12950  * best to walk the list rather than make assumptions.
12951  */
12952 static void
12953 bxe_probe_pci_caps(struct bxe_softc *sc)
12954 {
12955     uint16_t link_status;
12956     int reg;
12957
12958     /* check if PCI Power Management is enabled */
12959     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12960         if (reg != 0) {
12961             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12962
12963             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12964             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12965         }
12966     }
12967
12968     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12969
12970     /* handle PCIe 2.0 workarounds for 57710 */
12971     if (CHIP_IS_E1(sc)) {
12972         /* workaround for 57710 errata E4_57710_27462 */
12973         sc->devinfo.pcie_link_speed =
12974             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12975
12976         /* workaround for 57710 errata E4_57710_27488 */
12977         sc->devinfo.pcie_link_width =
12978             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12979         if (sc->devinfo.pcie_link_speed > 1) {
12980             sc->devinfo.pcie_link_width =
12981                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12982         }
12983     } else {
12984         sc->devinfo.pcie_link_speed =
12985             (link_status & PCIM_LINK_STA_SPEED);
12986         sc->devinfo.pcie_link_width =
12987             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12988     }
12989
12990     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12991           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12992
12993     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12994     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12995
12996     /* check if MSI capability is enabled */
12997     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12998         if (reg != 0) {
12999             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13000
13001             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13002             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13003         }
13004     }
13005
13006     /* check if MSI-X capability is enabled */
13007     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13008         if (reg != 0) {
13009             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13010
13011             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13012             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13013         }
13014     }
13015 }
13016
13017 static int
13018 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13019 {
13020     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13021     uint32_t val;
13022
13023     /* get the outer vlan if we're in switch-dependent mode */
13024
13025     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13026     mf_info->ext_id = (uint16_t)val;
13027
13028     mf_info->multi_vnics_mode = 1;
13029
13030     if (!VALID_OVLAN(mf_info->ext_id)) {
13031         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13032         return (1);
13033     }
13034
13035     /* get the capabilities */
13036     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13037         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13038         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13039     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13040                FUNC_MF_CFG_PROTOCOL_FCOE) {
13041         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13042     } else {
13043         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13044     }
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 uint32_t
13053 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13054 {
13055     uint32_t retval = 0;
13056     uint32_t val;
13057
13058     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13059
13060     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13061         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13062             retval |= MF_PROTO_SUPPORT_ETHERNET;
13063         }
13064         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13065             retval |= MF_PROTO_SUPPORT_ISCSI;
13066         }
13067         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13068             retval |= MF_PROTO_SUPPORT_FCOE;
13069         }
13070     }
13071
13072     return (retval);
13073 }
13074
13075 static int
13076 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13077 {
13078     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13079     uint32_t val;
13080
13081     /*
13082      * There is no outer vlan if we're in switch-independent mode.
13083      * If the mac is valid then assume multi-function.
13084      */
13085
13086     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13087
13088     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13089
13090     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13091
13092     mf_info->vnics_per_port =
13093         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13094
13095     return (0);
13096 }
13097
13098 static int
13099 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13100 {
13101     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13102     uint32_t e1hov_tag;
13103     uint32_t func_config;
13104     uint32_t niv_config;
13105
13106     mf_info->multi_vnics_mode = 1;
13107
13108     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13109     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13110     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13111
13112     mf_info->ext_id =
13113         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13114                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13115
13116     mf_info->default_vlan =
13117         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13118                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13119
13120     mf_info->niv_allowed_priorities =
13121         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13122                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13123
13124     mf_info->niv_default_cos =
13125         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13126                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13127
13128     mf_info->afex_vlan_mode =
13129         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13130          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13131
13132     mf_info->niv_mba_enabled =
13133         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13134          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13135
13136     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13137
13138     mf_info->vnics_per_port =
13139         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13140
13141     return (0);
13142 }
13143
13144 static int
13145 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13146 {
13147     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13148     uint32_t mf_cfg1;
13149     uint32_t mf_cfg2;
13150     uint32_t ovlan1;
13151     uint32_t ovlan2;
13152     uint8_t i, j;
13153
13154     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13155           SC_PORT(sc));
13156     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13157           mf_info->mf_config[SC_VN(sc)]);
13158     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13159           mf_info->multi_vnics_mode);
13160     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13161           mf_info->vnics_per_port);
13162     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13163           mf_info->ext_id);
13164     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13165           mf_info->min_bw[0], mf_info->min_bw[1],
13166           mf_info->min_bw[2], mf_info->min_bw[3]);
13167     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13168           mf_info->max_bw[0], mf_info->max_bw[1],
13169           mf_info->max_bw[2], mf_info->max_bw[3]);
13170     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13171           sc->mac_addr_str);
13172
13173     /* various MF mode sanity checks... */
13174
13175     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13176         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13177               SC_PORT(sc));
13178         return (1);
13179     }
13180
13181     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13182         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13183               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13184         return (1);
13185     }
13186
13187     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13188         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13189         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13190             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13191                   SC_VN(sc), OVLAN(sc));
13192             return (1);
13193         }
13194
13195         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13196             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13197                   mf_info->multi_vnics_mode, OVLAN(sc));
13198             return (1);
13199         }
13200
13201         /*
13202          * Verify all functions are either MF or SF mode. If MF, make sure
13203          * sure that all non-hidden functions have a valid ovlan. If SF,
13204          * make sure that all non-hidden functions have an invalid ovlan.
13205          */
13206         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13207             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13208             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13209             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13210                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13211                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13212                 BLOGE(sc, "mf_mode=SD function %d MF config "
13213                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13214                       i, mf_info->multi_vnics_mode, ovlan1);
13215                 return (1);
13216             }
13217         }
13218
13219         /* Verify all funcs on the same port each have a different ovlan. */
13220         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13221             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13222             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13223             /* iterate from the next function on the port to the max func */
13224             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13225                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13226                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13227                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13228                     VALID_OVLAN(ovlan1) &&
13229                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13230                     VALID_OVLAN(ovlan2) &&
13231                     (ovlan1 == ovlan2)) {
13232                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13233                               "have the same ovlan (%d)\n",
13234                           i, j, ovlan1);
13235                     return (1);
13236                 }
13237             }
13238         }
13239     } /* MULTI_FUNCTION_SD */
13240
13241     return (0);
13242 }
13243
13244 static int
13245 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13246 {
13247     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13248     uint32_t val, mac_upper;
13249     uint8_t i, vnic;
13250
13251     /* initialize mf_info defaults */
13252     mf_info->vnics_per_port   = 1;
13253     mf_info->multi_vnics_mode = FALSE;
13254     mf_info->path_has_ovlan   = FALSE;
13255     mf_info->mf_mode          = SINGLE_FUNCTION;
13256
13257     if (!CHIP_IS_MF_CAP(sc)) {
13258         return (0);
13259     }
13260
13261     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13262         BLOGE(sc, "Invalid mf_cfg_base!\n");
13263         return (1);
13264     }
13265
13266     /* get the MF mode (switch dependent / independent / single-function) */
13267
13268     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13269
13270     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13271     {
13272     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13273
13274         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13275
13276         /* check for legal upper mac bytes */
13277         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13278             mf_info->mf_mode = MULTI_FUNCTION_SI;
13279         } else {
13280             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13281         }
13282
13283         break;
13284
13285     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13286     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13287
13288         /* get outer vlan configuration */
13289         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13290
13291         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13292             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13293             mf_info->mf_mode = MULTI_FUNCTION_SD;
13294         } else {
13295             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13296         }
13297
13298         break;
13299
13300     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13301
13302         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13303         return (0);
13304
13305     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13306
13307         /*
13308          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13309          * and the MAC address is valid.
13310          */
13311         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13312
13313         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13314             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13315             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13316         } else {
13317             BLOGE(sc, "Invalid config for AFEX mode\n");
13318         }
13319
13320         break;
13321
13322     default:
13323
13324         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13325               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13326
13327         return (1);
13328     }
13329
13330     /* set path mf_mode (which could be different than function mf_mode) */
13331     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13332         mf_info->path_has_ovlan = TRUE;
13333     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13334         /*
13335          * Decide on path multi vnics mode. If we're not in MF mode and in
13336          * 4-port mode, this is good enough to check vnic-0 of the other port
13337          * on the same path
13338          */
13339         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13340             uint8_t other_port = !(PORT_ID(sc) & 1);
13341             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13342
13343             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13344
13345             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13346         }
13347     }
13348
13349     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13350         /* invalid MF config */
13351         if (SC_VN(sc) >= 1) {
13352             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13353             return (1);
13354         }
13355
13356         return (0);
13357     }
13358
13359     /* get the MF configuration */
13360     mf_info->mf_config[SC_VN(sc)] =
13361         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13362
13363     switch(mf_info->mf_mode)
13364     {
13365     case MULTI_FUNCTION_SD:
13366
13367         bxe_get_shmem_mf_cfg_info_sd(sc);
13368         break;
13369
13370     case MULTI_FUNCTION_SI:
13371
13372         bxe_get_shmem_mf_cfg_info_si(sc);
13373         break;
13374
13375     case MULTI_FUNCTION_AFEX:
13376
13377         bxe_get_shmem_mf_cfg_info_niv(sc);
13378         break;
13379
13380     default:
13381
13382         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13383               mf_info->mf_mode);
13384         return (1);
13385     }
13386
13387     /* get the congestion management parameters */
13388
13389     vnic = 0;
13390     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13391         /* get min/max bw */
13392         val = MFCFG_RD(sc, func_mf_config[i].config);
13393         mf_info->min_bw[vnic] =
13394             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13395         mf_info->max_bw[vnic] =
13396             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13397         vnic++;
13398     }
13399
13400     return (bxe_check_valid_mf_cfg(sc));
13401 }
13402
13403 static int
13404 bxe_get_shmem_info(struct bxe_softc *sc)
13405 {
13406     int port;
13407     uint32_t mac_hi, mac_lo, val;
13408
13409     port = SC_PORT(sc);
13410     mac_hi = mac_lo = 0;
13411
13412     sc->link_params.sc   = sc;
13413     sc->link_params.port = port;
13414
13415     /* get the hardware config info */
13416     sc->devinfo.hw_config =
13417         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13418     sc->devinfo.hw_config2 =
13419         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13420
13421     sc->link_params.hw_led_mode =
13422         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13423          SHARED_HW_CFG_LED_MODE_SHIFT);
13424
13425     /* get the port feature config */
13426     sc->port.config =
13427         SHMEM_RD(sc, dev_info.port_feature_config[port].config);
13428
13429     /* get the link params */
13430     sc->link_params.speed_cap_mask[0] =
13431         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13432     sc->link_params.speed_cap_mask[1] =
13433         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13434
13435     /* get the lane config */
13436     sc->link_params.lane_config =
13437         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13438
13439     /* get the link config */
13440     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13441     sc->port.link_config[ELINK_INT_PHY] = val;
13442     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13443     sc->port.link_config[ELINK_EXT_PHY1] =
13444         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13445
13446     /* get the override preemphasis flag and enable it or turn it off */
13447     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13448     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13449         sc->link_params.feature_config_flags |=
13450             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13451     } else {
13452         sc->link_params.feature_config_flags &=
13453             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13454     }
13455
13456     /* get the initial value of the link params */
13457     sc->link_params.multi_phy_config =
13458         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13459
13460     /* get external phy info */
13461     sc->port.ext_phy_config =
13462         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13463
13464     /* get the multifunction configuration */
13465     bxe_get_mf_cfg_info(sc);
13466
13467     /* get the mac address */
13468     if (IS_MF(sc)) {
13469         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13470         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13471     } else {
13472         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13473         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13474     }
13475
13476     if ((mac_lo == 0) && (mac_hi == 0)) {
13477         *sc->mac_addr_str = 0;
13478         BLOGE(sc, "No Ethernet address programmed!\n");
13479     } else {
13480         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13481         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13482         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13483         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13484         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13485         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13486         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13487                  "%02x:%02x:%02x:%02x:%02x:%02x",
13488                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13489                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13490                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13491         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13492     }
13493
13494     return (0);
13495 }
13496
13497 static void
13498 bxe_get_tunable_params(struct bxe_softc *sc)
13499 {
13500     /* sanity checks */
13501
13502     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13503         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13504         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13505         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13506         bxe_interrupt_mode = INTR_MODE_MSIX;
13507     }
13508
13509     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13510         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13511         bxe_queue_count = 0;
13512     }
13513
13514     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13515         if (bxe_max_rx_bufs == 0) {
13516             bxe_max_rx_bufs = RX_BD_USABLE;
13517         } else {
13518             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13519             bxe_max_rx_bufs = 2048;
13520         }
13521     }
13522
13523     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13524         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13525         bxe_hc_rx_ticks = 25;
13526     }
13527
13528     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13529         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13530         bxe_hc_tx_ticks = 50;
13531     }
13532
13533     if (bxe_max_aggregation_size == 0) {
13534         bxe_max_aggregation_size = TPA_AGG_SIZE;
13535     }
13536
13537     if (bxe_max_aggregation_size > 0xffff) {
13538         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13539               bxe_max_aggregation_size);
13540         bxe_max_aggregation_size = TPA_AGG_SIZE;
13541     }
13542
13543     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13544         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13545         bxe_mrrs = -1;
13546     }
13547
13548     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13549         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13550         bxe_autogreeen = 0;
13551     }
13552
13553     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13554         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13555         bxe_udp_rss = 0;
13556     }
13557
13558     /* pull in user settings */
13559
13560     sc->interrupt_mode       = bxe_interrupt_mode;
13561     sc->max_rx_bufs          = bxe_max_rx_bufs;
13562     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13563     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13564     sc->max_aggregation_size = bxe_max_aggregation_size;
13565     sc->mrrs                 = bxe_mrrs;
13566     sc->autogreeen           = bxe_autogreeen;
13567     sc->udp_rss              = bxe_udp_rss;
13568
13569     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13570         sc->num_queues = 1;
13571     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13572         sc->num_queues =
13573             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13574                 MAX_RSS_CHAINS);
13575         if (sc->num_queues > mp_ncpus) {
13576             sc->num_queues = mp_ncpus;
13577         }
13578     }
13579
13580     BLOGD(sc, DBG_LOAD,
13581           "User Config: "
13582           "debug=0x%lx "
13583           "interrupt_mode=%d "
13584           "queue_count=%d "
13585           "hc_rx_ticks=%d "
13586           "hc_tx_ticks=%d "
13587           "rx_budget=%d "
13588           "max_aggregation_size=%d "
13589           "mrrs=%d "
13590           "autogreeen=%d "
13591           "udp_rss=%d\n",
13592           bxe_debug,
13593           sc->interrupt_mode,
13594           sc->num_queues,
13595           sc->hc_rx_ticks,
13596           sc->hc_tx_ticks,
13597           bxe_rx_budget,
13598           sc->max_aggregation_size,
13599           sc->mrrs,
13600           sc->autogreeen,
13601           sc->udp_rss);
13602 }
13603
13604 static int
13605 bxe_media_detect(struct bxe_softc *sc)
13606 {
13607     int port_type;
13608     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13609
13610     switch (sc->link_params.phy[phy_idx].media_type) {
13611     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13612     case ELINK_ETH_PHY_XFP_FIBER:
13613         BLOGI(sc, "Found 10Gb Fiber media.\n");
13614         sc->media = IFM_10G_SR;
13615         port_type = PORT_FIBRE;
13616         break;
13617     case ELINK_ETH_PHY_SFP_1G_FIBER:
13618         BLOGI(sc, "Found 1Gb Fiber media.\n");
13619         sc->media = IFM_1000_SX;
13620         port_type = PORT_FIBRE;
13621         break;
13622     case ELINK_ETH_PHY_KR:
13623     case ELINK_ETH_PHY_CX4:
13624         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13625         sc->media = IFM_10G_CX4;
13626         port_type = PORT_FIBRE;
13627         break;
13628     case ELINK_ETH_PHY_DA_TWINAX:
13629         BLOGI(sc, "Found 10Gb Twinax media.\n");
13630         sc->media = IFM_10G_TWINAX;
13631         port_type = PORT_DA;
13632         break;
13633     case ELINK_ETH_PHY_BASE_T:
13634         if (sc->link_params.speed_cap_mask[0] &
13635             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13636             BLOGI(sc, "Found 10GBase-T media.\n");
13637             sc->media = IFM_10G_T;
13638             port_type = PORT_TP;
13639         } else {
13640             BLOGI(sc, "Found 1000Base-T media.\n");
13641             sc->media = IFM_1000_T;
13642             port_type = PORT_TP;
13643         }
13644         break;
13645     case ELINK_ETH_PHY_NOT_PRESENT:
13646         BLOGI(sc, "Media not present.\n");
13647         sc->media = 0;
13648         port_type = PORT_OTHER;
13649         break;
13650     case ELINK_ETH_PHY_UNSPECIFIED:
13651     default:
13652         BLOGI(sc, "Unknown media!\n");
13653         sc->media = 0;
13654         port_type = PORT_OTHER;
13655         break;
13656     }
13657     return port_type;
13658 }
13659
13660 #define GET_FIELD(value, fname)                     \
13661     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13662 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13663 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13664
13665 static int
13666 bxe_get_igu_cam_info(struct bxe_softc *sc)
13667 {
13668     int pfid = SC_FUNC(sc);
13669     int igu_sb_id;
13670     uint32_t val;
13671     uint8_t fid, igu_sb_cnt = 0;
13672
13673     sc->igu_base_sb = 0xff;
13674
13675     if (CHIP_INT_MODE_IS_BC(sc)) {
13676         int vn = SC_VN(sc);
13677         igu_sb_cnt = sc->igu_sb_cnt;
13678         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13679                            FP_SB_MAX_E1x);
13680         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13681                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13682         return (0);
13683     }
13684
13685     /* IGU in normal mode - read CAM */
13686     for (igu_sb_id = 0;
13687          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13688          igu_sb_id++) {
13689         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13690         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13691             continue;
13692         }
13693         fid = IGU_FID(val);
13694         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13695             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13696                 continue;
13697             }
13698             if (IGU_VEC(val) == 0) {
13699                 /* default status block */
13700                 sc->igu_dsb_id = igu_sb_id;
13701             } else {
13702                 if (sc->igu_base_sb == 0xff) {
13703                     sc->igu_base_sb = igu_sb_id;
13704                 }
13705                 igu_sb_cnt++;
13706             }
13707         }
13708     }
13709
13710     /*
13711      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13712      * that number of CAM entries will not be equal to the value advertised in
13713      * PCI. Driver should use the minimal value of both as the actual status
13714      * block count
13715      */
13716     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13717
13718     if (igu_sb_cnt == 0) {
13719         BLOGE(sc, "CAM configuration error\n");
13720         return (-1);
13721     }
13722
13723     return (0);
13724 }
13725
13726 /*
13727  * Gather various information from the device config space, the device itself,
13728  * shmem, and the user input.
13729  */
13730 static int
13731 bxe_get_device_info(struct bxe_softc *sc)
13732 {
13733     uint32_t val;
13734     int rc;
13735
13736     /* Get the data for the device */
13737     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13738     sc->devinfo.device_id    = pci_get_device(sc->dev);
13739     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13740     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13741
13742     /* get the chip revision (chip metal comes from pci config space) */
13743     sc->devinfo.chip_id     =
13744     sc->link_params.chip_id =
13745         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13746          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13747          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13748          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13749
13750     /* force 57811 according to MISC register */
13751     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13752         if (CHIP_IS_57810(sc)) {
13753             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13754                                    (sc->devinfo.chip_id & 0x0000ffff));
13755         } else if (CHIP_IS_57810_MF(sc)) {
13756             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13757                                    (sc->devinfo.chip_id & 0x0000ffff));
13758         }
13759         sc->devinfo.chip_id |= 0x1;
13760     }
13761
13762     BLOGD(sc, DBG_LOAD,
13763           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13764           sc->devinfo.chip_id,
13765           ((sc->devinfo.chip_id >> 16) & 0xffff),
13766           ((sc->devinfo.chip_id >> 12) & 0xf),
13767           ((sc->devinfo.chip_id >>  4) & 0xff),
13768           ((sc->devinfo.chip_id >>  0) & 0xf));
13769
13770     val = (REG_RD(sc, 0x2874) & 0x55);
13771     if ((sc->devinfo.chip_id & 0x1) ||
13772         (CHIP_IS_E1(sc) && val) ||
13773         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13774         sc->flags |= BXE_ONE_PORT_FLAG;
13775         BLOGD(sc, DBG_LOAD, "single port device\n");
13776     }
13777
13778     /* set the doorbell size */
13779     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13780
13781     /* determine whether the device is in 2 port or 4 port mode */
13782     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13783     if (CHIP_IS_E2E3(sc)) {
13784         /*
13785          * Read port4mode_en_ovwr[0]:
13786          *   If 1, four port mode is in port4mode_en_ovwr[1].
13787          *   If 0, four port mode is in port4mode_en[0].
13788          */
13789         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13790         if (val & 1) {
13791             val = ((val >> 1) & 1);
13792         } else {
13793             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13794         }
13795
13796         sc->devinfo.chip_port_mode =
13797             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13798
13799         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13800     }
13801
13802     /* get the function and path info for the device */
13803     bxe_get_function_num(sc);
13804
13805     /* get the shared memory base address */
13806     sc->devinfo.shmem_base     =
13807     sc->link_params.shmem_base =
13808         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13809     sc->devinfo.shmem2_base =
13810         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13811                                   MISC_REG_GENERIC_CR_0));
13812
13813     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13814           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13815
13816     if (!sc->devinfo.shmem_base) {
13817         /* this should ONLY prevent upcoming shmem reads */
13818         BLOGI(sc, "MCP not active\n");
13819         sc->flags |= BXE_NO_MCP_FLAG;
13820         return (0);
13821     }
13822
13823     /* make sure the shared memory contents are valid */
13824     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13825     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13826         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13827         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13828         return (0);
13829     }
13830     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13831
13832     /* get the bootcode version */
13833     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13834     snprintf(sc->devinfo.bc_ver_str,
13835              sizeof(sc->devinfo.bc_ver_str),
13836              "%d.%d.%d",
13837              ((sc->devinfo.bc_ver >> 24) & 0xff),
13838              ((sc->devinfo.bc_ver >> 16) & 0xff),
13839              ((sc->devinfo.bc_ver >>  8) & 0xff));
13840     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13841
13842     /* get the bootcode shmem address */
13843     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13844     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13845
13846     /* clean indirect addresses as they're not used */
13847     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13848     if (IS_PF(sc)) {
13849         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13850         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13851         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13852         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13853         if (CHIP_IS_E1x(sc)) {
13854             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13855             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13856             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13857             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13858         }
13859
13860         /*
13861          * Enable internal target-read (in case we are probed after PF
13862          * FLR). Must be done prior to any BAR read access. Only for
13863          * 57712 and up
13864          */
13865         if (!CHIP_IS_E1x(sc)) {
13866             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13867         }
13868     }
13869
13870     /* get the nvram size */
13871     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13872     sc->devinfo.flash_size =
13873         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13874     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13875
13876     /* get PCI capabilites */
13877     bxe_probe_pci_caps(sc);
13878
13879     bxe_set_power_state(sc, PCI_PM_D0);
13880
13881     /* get various configuration parameters from shmem */
13882     bxe_get_shmem_info(sc);
13883
13884     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13885         val = pci_read_config(sc->dev,
13886                               (sc->devinfo.pcie_msix_cap_reg +
13887                                PCIR_MSIX_CTRL),
13888                               2);
13889         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13890     } else {
13891         sc->igu_sb_cnt = 1;
13892     }
13893
13894     sc->igu_base_addr = BAR_IGU_INTMEM;
13895
13896     /* initialize IGU parameters */
13897     if (CHIP_IS_E1x(sc)) {
13898         sc->devinfo.int_block = INT_BLOCK_HC;
13899         sc->igu_dsb_id = DEF_SB_IGU_ID;
13900         sc->igu_base_sb = 0;
13901     } else {
13902         sc->devinfo.int_block = INT_BLOCK_IGU;
13903
13904         /* do not allow device reset during IGU info preocessing */
13905         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13906
13907         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13908
13909         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13910             int tout = 5000;
13911
13912             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13913
13914             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13915             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13916             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13917
13918             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13919                 tout--;
13920                 DELAY(1000);
13921             }
13922
13923             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13924                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13925                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13926                 return (-1);
13927             }
13928         }
13929
13930         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13931             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13932             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13933         } else {
13934             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13935         }
13936
13937         rc = bxe_get_igu_cam_info(sc);
13938
13939         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13940
13941         if (rc) {
13942             return (rc);
13943         }
13944     }
13945
13946     /*
13947      * Get base FW non-default (fast path) status block ID. This value is
13948      * used to initialize the fw_sb_id saved on the fp/queue structure to
13949      * determine the id used by the FW.
13950      */
13951     if (CHIP_IS_E1x(sc)) {
13952         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13953     } else {
13954         /*
13955          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13956          * the same queue are indicated on the same IGU SB). So we prefer
13957          * FW and IGU SBs to be the same value.
13958          */
13959         sc->base_fw_ndsb = sc->igu_base_sb;
13960     }
13961
13962     BLOGD(sc, DBG_LOAD,
13963           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13964           sc->igu_dsb_id, sc->igu_base_sb,
13965           sc->igu_sb_cnt, sc->base_fw_ndsb);
13966
13967     elink_phy_probe(&sc->link_params);
13968
13969     return (0);
13970 }
13971
13972 static void
13973 bxe_link_settings_supported(struct bxe_softc *sc,
13974                             uint32_t         switch_cfg)
13975 {
13976     uint32_t cfg_size = 0;
13977     uint32_t idx;
13978     uint8_t port = SC_PORT(sc);
13979
13980     /* aggregation of supported attributes of all external phys */
13981     sc->port.supported[0] = 0;
13982     sc->port.supported[1] = 0;
13983
13984     switch (sc->link_params.num_phys) {
13985     case 1:
13986         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13987         cfg_size = 1;
13988         break;
13989     case 2:
13990         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13991         cfg_size = 1;
13992         break;
13993     case 3:
13994         if (sc->link_params.multi_phy_config &
13995             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13996             sc->port.supported[1] =
13997                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13998             sc->port.supported[0] =
13999                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14000         } else {
14001             sc->port.supported[0] =
14002                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14003             sc->port.supported[1] =
14004                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14005         }
14006         cfg_size = 2;
14007         break;
14008     }
14009
14010     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14011         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14012               SHMEM_RD(sc,
14013                        dev_info.port_hw_config[port].external_phy_config),
14014               SHMEM_RD(sc,
14015                        dev_info.port_hw_config[port].external_phy_config2));
14016         return;
14017     }
14018
14019     if (CHIP_IS_E3(sc))
14020         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14021     else {
14022         switch (switch_cfg) {
14023         case ELINK_SWITCH_CFG_1G:
14024             sc->port.phy_addr =
14025                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14026             break;
14027         case ELINK_SWITCH_CFG_10G:
14028             sc->port.phy_addr =
14029                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14030             break;
14031         default:
14032             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14033                   sc->port.link_config[0]);
14034             return;
14035         }
14036     }
14037
14038     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14039
14040     /* mask what we support according to speed_cap_mask per configuration */
14041     for (idx = 0; idx < cfg_size; idx++) {
14042         if (!(sc->link_params.speed_cap_mask[idx] &
14043               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14044             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14045         }
14046
14047         if (!(sc->link_params.speed_cap_mask[idx] &
14048               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14049             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14050         }
14051
14052         if (!(sc->link_params.speed_cap_mask[idx] &
14053               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14054             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14055         }
14056
14057         if (!(sc->link_params.speed_cap_mask[idx] &
14058               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14059             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14060         }
14061
14062         if (!(sc->link_params.speed_cap_mask[idx] &
14063               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14064             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14065         }
14066
14067         if (!(sc->link_params.speed_cap_mask[idx] &
14068               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14069             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14070         }
14071
14072         if (!(sc->link_params.speed_cap_mask[idx] &
14073               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14074             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14075         }
14076
14077         if (!(sc->link_params.speed_cap_mask[idx] &
14078               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14079             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14080         }
14081     }
14082
14083     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14084           sc->port.supported[0], sc->port.supported[1]);
14085         ELINK_DEBUG_P2(sc, "PHY supported 0=0x%08x 1=0x%08x\n",
14086                                         sc->port.supported[0], sc->port.supported[1]);
14087 }
14088
14089 static void
14090 bxe_link_settings_requested(struct bxe_softc *sc)
14091 {
14092     uint32_t link_config;
14093     uint32_t idx;
14094     uint32_t cfg_size = 0;
14095
14096     sc->port.advertising[0] = 0;
14097     sc->port.advertising[1] = 0;
14098
14099     switch (sc->link_params.num_phys) {
14100     case 1:
14101     case 2:
14102         cfg_size = 1;
14103         break;
14104     case 3:
14105         cfg_size = 2;
14106         break;
14107     }
14108
14109     for (idx = 0; idx < cfg_size; idx++) {
14110         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14111         link_config = sc->port.link_config[idx];
14112
14113         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14114         case PORT_FEATURE_LINK_SPEED_AUTO:
14115             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14116                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14117                 sc->port.advertising[idx] |= sc->port.supported[idx];
14118                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14119                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14120                     sc->port.advertising[idx] |=
14121                         (ELINK_SUPPORTED_100baseT_Half |
14122                          ELINK_SUPPORTED_100baseT_Full);
14123             } else {
14124                 /* force 10G, no AN */
14125                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14126                 sc->port.advertising[idx] |=
14127                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14128                 continue;
14129             }
14130             break;
14131
14132         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14133             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14134                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14135                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14136                                               ADVERTISED_TP);
14137             } else {
14138                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14139                           "speed_cap_mask=0x%08x\n",
14140                       link_config, sc->link_params.speed_cap_mask[idx]);
14141                 return;
14142             }
14143             break;
14144
14145         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14146             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14147                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14148                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14149                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14150                                               ADVERTISED_TP);
14151                                 ELINK_DEBUG_P1(sc, "driver requesting DUPLEX_HALF req_duplex = %x!\n",
14152                                                                 sc->link_params.req_duplex[idx]);
14153             } else {
14154                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14155                           "speed_cap_mask=0x%08x\n",
14156                       link_config, sc->link_params.speed_cap_mask[idx]);
14157                 return;
14158             }
14159             break;
14160
14161         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14162             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14163                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14164                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14165                                               ADVERTISED_TP);
14166             } else {
14167                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14168                           "speed_cap_mask=0x%08x\n",
14169                       link_config, sc->link_params.speed_cap_mask[idx]);
14170                 return;
14171             }
14172             break;
14173
14174         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14175             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14176                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14177                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14178                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14179                                               ADVERTISED_TP);
14180             } else {
14181                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14182                           "speed_cap_mask=0x%08x\n",
14183                       link_config, sc->link_params.speed_cap_mask[idx]);
14184                 return;
14185             }
14186             break;
14187
14188         case PORT_FEATURE_LINK_SPEED_1G:
14189             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14190                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14191                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14192                                               ADVERTISED_TP);
14193             } else {
14194                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14195                           "speed_cap_mask=0x%08x\n",
14196                       link_config, sc->link_params.speed_cap_mask[idx]);
14197                 return;
14198             }
14199             break;
14200
14201         case PORT_FEATURE_LINK_SPEED_2_5G:
14202             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14203                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14204                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14205                                               ADVERTISED_TP);
14206             } else {
14207                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14208                           "speed_cap_mask=0x%08x\n",
14209                       link_config, sc->link_params.speed_cap_mask[idx]);
14210                 return;
14211             }
14212             break;
14213
14214         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14215             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14216                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14217                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14218                                               ADVERTISED_FIBRE);
14219             } else {
14220                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14221                           "speed_cap_mask=0x%08x\n",
14222                       link_config, sc->link_params.speed_cap_mask[idx]);
14223                 return;
14224             }
14225             break;
14226
14227         case PORT_FEATURE_LINK_SPEED_20G:
14228             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14229             break;
14230
14231         default:
14232             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14233                       "speed_cap_mask=0x%08x\n",
14234                   link_config, sc->link_params.speed_cap_mask[idx]);
14235             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14236             sc->port.advertising[idx] = sc->port.supported[idx];
14237             break;
14238         }
14239
14240         sc->link_params.req_flow_ctrl[idx] =
14241             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14242
14243         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14244             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14245                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14246             } else {
14247                 bxe_set_requested_fc(sc);
14248             }
14249         }
14250
14251         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14252                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14253               sc->link_params.req_line_speed[idx],
14254               sc->link_params.req_duplex[idx],
14255               sc->link_params.req_flow_ctrl[idx],
14256               sc->port.advertising[idx]);
14257                 ELINK_DEBUG_P3(sc, "req_line_speed=%d req_duplex=%d "
14258                                                 "advertising=0x%x\n",
14259                                                 sc->link_params.req_line_speed[idx],
14260                                                 sc->link_params.req_duplex[idx],
14261                                                 sc->port.advertising[idx]);
14262     }
14263 }
14264
14265 static void
14266 bxe_get_phy_info(struct bxe_softc *sc)
14267 {
14268     uint8_t port = SC_PORT(sc);
14269     uint32_t config = sc->port.config;
14270     uint32_t eee_mode;
14271
14272     /* shmem data already read in bxe_get_shmem_info() */
14273
14274     ELINK_DEBUG_P3(sc, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14275                         "link_config0=0x%08x\n",
14276                sc->link_params.lane_config,
14277                sc->link_params.speed_cap_mask[0],
14278                sc->port.link_config[0]);
14279      
14280
14281     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14282     bxe_link_settings_requested(sc);
14283
14284     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14285         sc->link_params.feature_config_flags |=
14286             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14287     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14288         sc->link_params.feature_config_flags &=
14289             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14290     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14291         sc->link_params.feature_config_flags |=
14292             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14293     }
14294
14295     /* configure link feature according to nvram value */
14296     eee_mode =
14297         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14298           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14299          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14300     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14301         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14302                                     ELINK_EEE_MODE_ENABLE_LPI |
14303                                     ELINK_EEE_MODE_OUTPUT_TIME);
14304     } else {
14305         sc->link_params.eee_mode = 0;
14306     }
14307
14308     /* get the media type */
14309     bxe_media_detect(sc);
14310         ELINK_DEBUG_P1(sc, "detected media type\n", sc->media);
14311 }
14312
14313 static void
14314 bxe_get_params(struct bxe_softc *sc)
14315 {
14316     /* get user tunable params */
14317     bxe_get_tunable_params(sc);
14318
14319     /* select the RX and TX ring sizes */
14320     sc->tx_ring_size = TX_BD_USABLE;
14321     sc->rx_ring_size = RX_BD_USABLE;
14322
14323     /* XXX disable WoL */
14324     sc->wol = 0;
14325 }
14326
14327 static void
14328 bxe_set_modes_bitmap(struct bxe_softc *sc)
14329 {
14330     uint32_t flags = 0;
14331
14332     if (CHIP_REV_IS_FPGA(sc)) {
14333         SET_FLAGS(flags, MODE_FPGA);
14334     } else if (CHIP_REV_IS_EMUL(sc)) {
14335         SET_FLAGS(flags, MODE_EMUL);
14336     } else {
14337         SET_FLAGS(flags, MODE_ASIC);
14338     }
14339
14340     if (CHIP_IS_MODE_4_PORT(sc)) {
14341         SET_FLAGS(flags, MODE_PORT4);
14342     } else {
14343         SET_FLAGS(flags, MODE_PORT2);
14344     }
14345
14346     if (CHIP_IS_E2(sc)) {
14347         SET_FLAGS(flags, MODE_E2);
14348     } else if (CHIP_IS_E3(sc)) {
14349         SET_FLAGS(flags, MODE_E3);
14350         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14351             SET_FLAGS(flags, MODE_E3_A0);
14352         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14353             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14354         }
14355     }
14356
14357     if (IS_MF(sc)) {
14358         SET_FLAGS(flags, MODE_MF);
14359         switch (sc->devinfo.mf_info.mf_mode) {
14360         case MULTI_FUNCTION_SD:
14361             SET_FLAGS(flags, MODE_MF_SD);
14362             break;
14363         case MULTI_FUNCTION_SI:
14364             SET_FLAGS(flags, MODE_MF_SI);
14365             break;
14366         case MULTI_FUNCTION_AFEX:
14367             SET_FLAGS(flags, MODE_MF_AFEX);
14368             break;
14369         }
14370     } else {
14371         SET_FLAGS(flags, MODE_SF);
14372     }
14373
14374 #if defined(__LITTLE_ENDIAN)
14375     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14376 #else /* __BIG_ENDIAN */
14377     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14378 #endif
14379
14380     INIT_MODE_FLAGS(sc) = flags;
14381 }
14382
14383 static int
14384 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14385 {
14386     struct bxe_fastpath *fp;
14387     bus_addr_t busaddr;
14388     int max_agg_queues;
14389     int max_segments;
14390     bus_size_t max_size;
14391     bus_size_t max_seg_size;
14392     char buf[32];
14393     int rc;
14394     int i, j;
14395
14396     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14397
14398     /* allocate the parent bus DMA tag */
14399     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14400                             1,                        /* alignment */
14401                             0,                        /* boundary limit */
14402                             BUS_SPACE_MAXADDR,        /* restricted low */
14403                             BUS_SPACE_MAXADDR,        /* restricted hi */
14404                             NULL,                     /* addr filter() */
14405                             NULL,                     /* addr filter() arg */
14406                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14407                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14408                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14409                             0,                        /* flags */
14410                             NULL,                     /* lock() */
14411                             NULL,                     /* lock() arg */
14412                             &sc->parent_dma_tag);     /* returned dma tag */
14413     if (rc != 0) {
14414         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14415         return (1);
14416     }
14417
14418     /************************/
14419     /* DEFAULT STATUS BLOCK */
14420     /************************/
14421
14422     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14423                       &sc->def_sb_dma, "default status block") != 0) {
14424         /* XXX */
14425         bus_dma_tag_destroy(sc->parent_dma_tag);
14426         return (1);
14427     }
14428
14429     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14430
14431     /***************/
14432     /* EVENT QUEUE */
14433     /***************/
14434
14435     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14436                       &sc->eq_dma, "event queue") != 0) {
14437         /* XXX */
14438         bxe_dma_free(sc, &sc->def_sb_dma);
14439         sc->def_sb = NULL;
14440         bus_dma_tag_destroy(sc->parent_dma_tag);
14441         return (1);
14442     }
14443
14444     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14445
14446     /*************/
14447     /* SLOW PATH */
14448     /*************/
14449
14450     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14451                       &sc->sp_dma, "slow path") != 0) {
14452         /* XXX */
14453         bxe_dma_free(sc, &sc->eq_dma);
14454         sc->eq = NULL;
14455         bxe_dma_free(sc, &sc->def_sb_dma);
14456         sc->def_sb = NULL;
14457         bus_dma_tag_destroy(sc->parent_dma_tag);
14458         return (1);
14459     }
14460
14461     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14462
14463     /*******************/
14464     /* SLOW PATH QUEUE */
14465     /*******************/
14466
14467     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14468                       &sc->spq_dma, "slow path queue") != 0) {
14469         /* XXX */
14470         bxe_dma_free(sc, &sc->sp_dma);
14471         sc->sp = NULL;
14472         bxe_dma_free(sc, &sc->eq_dma);
14473         sc->eq = NULL;
14474         bxe_dma_free(sc, &sc->def_sb_dma);
14475         sc->def_sb = NULL;
14476         bus_dma_tag_destroy(sc->parent_dma_tag);
14477         return (1);
14478     }
14479
14480     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14481
14482     /***************************/
14483     /* FW DECOMPRESSION BUFFER */
14484     /***************************/
14485
14486     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14487                       "fw decompression buffer") != 0) {
14488         /* XXX */
14489         bxe_dma_free(sc, &sc->spq_dma);
14490         sc->spq = NULL;
14491         bxe_dma_free(sc, &sc->sp_dma);
14492         sc->sp = NULL;
14493         bxe_dma_free(sc, &sc->eq_dma);
14494         sc->eq = NULL;
14495         bxe_dma_free(sc, &sc->def_sb_dma);
14496         sc->def_sb = NULL;
14497         bus_dma_tag_destroy(sc->parent_dma_tag);
14498         return (1);
14499     }
14500
14501     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14502
14503     if ((sc->gz_strm =
14504          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14505         /* XXX */
14506         bxe_dma_free(sc, &sc->gz_buf_dma);
14507         sc->gz_buf = NULL;
14508         bxe_dma_free(sc, &sc->spq_dma);
14509         sc->spq = NULL;
14510         bxe_dma_free(sc, &sc->sp_dma);
14511         sc->sp = NULL;
14512         bxe_dma_free(sc, &sc->eq_dma);
14513         sc->eq = NULL;
14514         bxe_dma_free(sc, &sc->def_sb_dma);
14515         sc->def_sb = NULL;
14516         bus_dma_tag_destroy(sc->parent_dma_tag);
14517         return (1);
14518     }
14519
14520     /*************/
14521     /* FASTPATHS */
14522     /*************/
14523
14524     /* allocate DMA memory for each fastpath structure */
14525     for (i = 0; i < sc->num_queues; i++) {
14526         fp = &sc->fp[i];
14527         fp->sc    = sc;
14528         fp->index = i;
14529
14530         /*******************/
14531         /* FP STATUS BLOCK */
14532         /*******************/
14533
14534         snprintf(buf, sizeof(buf), "fp %d status block", i);
14535         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14536                           &fp->sb_dma, buf) != 0) {
14537             /* XXX unwind and free previous fastpath allocations */
14538             BLOGE(sc, "Failed to alloc %s\n", buf);
14539             return (1);
14540         } else {
14541             if (CHIP_IS_E2E3(sc)) {
14542                 fp->status_block.e2_sb =
14543                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14544             } else {
14545                 fp->status_block.e1x_sb =
14546                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14547             }
14548         }
14549
14550         /******************/
14551         /* FP TX BD CHAIN */
14552         /******************/
14553
14554         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14555         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14556                           &fp->tx_dma, buf) != 0) {
14557             /* XXX unwind and free previous fastpath allocations */
14558             BLOGE(sc, "Failed to alloc %s\n", buf);
14559             return (1);
14560         } else {
14561             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14562         }
14563
14564         /* link together the tx bd chain pages */
14565         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14566             /* index into the tx bd chain array to last entry per page */
14567             struct eth_tx_next_bd *tx_next_bd =
14568                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14569             /* point to the next page and wrap from last page */
14570             busaddr = (fp->tx_dma.paddr +
14571                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14572             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14573             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14574         }
14575
14576         /******************/
14577         /* FP RX BD CHAIN */
14578         /******************/
14579
14580         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14581         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14582                           &fp->rx_dma, buf) != 0) {
14583             /* XXX unwind and free previous fastpath allocations */
14584             BLOGE(sc, "Failed to alloc %s\n", buf);
14585             return (1);
14586         } else {
14587             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14588         }
14589
14590         /* link together the rx bd chain pages */
14591         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14592             /* index into the rx bd chain array to last entry per page */
14593             struct eth_rx_bd *rx_bd =
14594                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14595             /* point to the next page and wrap from last page */
14596             busaddr = (fp->rx_dma.paddr +
14597                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14598             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14599             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14600         }
14601
14602         /*******************/
14603         /* FP RX RCQ CHAIN */
14604         /*******************/
14605
14606         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14607         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14608                           &fp->rcq_dma, buf) != 0) {
14609             /* XXX unwind and free previous fastpath allocations */
14610             BLOGE(sc, "Failed to alloc %s\n", buf);
14611             return (1);
14612         } else {
14613             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14614         }
14615
14616         /* link together the rcq chain pages */
14617         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14618             /* index into the rcq chain array to last entry per page */
14619             struct eth_rx_cqe_next_page *rx_cqe_next =
14620                 (struct eth_rx_cqe_next_page *)
14621                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14622             /* point to the next page and wrap from last page */
14623             busaddr = (fp->rcq_dma.paddr +
14624                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14625             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14626             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14627         }
14628
14629         /*******************/
14630         /* FP RX SGE CHAIN */
14631         /*******************/
14632
14633         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14634         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14635                           &fp->rx_sge_dma, buf) != 0) {
14636             /* XXX unwind and free previous fastpath allocations */
14637             BLOGE(sc, "Failed to alloc %s\n", buf);
14638             return (1);
14639         } else {
14640             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14641         }
14642
14643         /* link together the sge chain pages */
14644         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14645             /* index into the rcq chain array to last entry per page */
14646             struct eth_rx_sge *rx_sge =
14647                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14648             /* point to the next page and wrap from last page */
14649             busaddr = (fp->rx_sge_dma.paddr +
14650                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14651             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14652             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14653         }
14654
14655         /***********************/
14656         /* FP TX MBUF DMA MAPS */
14657         /***********************/
14658
14659         /* set required sizes before mapping to conserve resources */
14660         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14661             max_size     = BXE_TSO_MAX_SIZE;
14662             max_segments = BXE_TSO_MAX_SEGMENTS;
14663             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14664         } else {
14665             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14666             max_segments = BXE_MAX_SEGMENTS;
14667             max_seg_size = MCLBYTES;
14668         }
14669
14670         /* create a dma tag for the tx mbufs */
14671         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14672                                 1,                  /* alignment */
14673                                 0,                  /* boundary limit */
14674                                 BUS_SPACE_MAXADDR,  /* restricted low */
14675                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14676                                 NULL,               /* addr filter() */
14677                                 NULL,               /* addr filter() arg */
14678                                 max_size,           /* max map size */
14679                                 max_segments,       /* num discontinuous */
14680                                 max_seg_size,       /* max seg size */
14681                                 0,                  /* flags */
14682                                 NULL,               /* lock() */
14683                                 NULL,               /* lock() arg */
14684                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14685         if (rc != 0) {
14686             /* XXX unwind and free previous fastpath allocations */
14687             BLOGE(sc, "Failed to create dma tag for "
14688                       "'fp %d tx mbufs' (%d)\n", i, rc);
14689             return (1);
14690         }
14691
14692         /* create dma maps for each of the tx mbuf clusters */
14693         for (j = 0; j < TX_BD_TOTAL; j++) {
14694             if (bus_dmamap_create(fp->tx_mbuf_tag,
14695                                   BUS_DMA_NOWAIT,
14696                                   &fp->tx_mbuf_chain[j].m_map)) {
14697                 /* XXX unwind and free previous fastpath allocations */
14698                 BLOGE(sc, "Failed to create dma map for "
14699                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14700                 return (1);
14701             }
14702         }
14703
14704         /***********************/
14705         /* FP RX MBUF DMA MAPS */
14706         /***********************/
14707
14708         /* create a dma tag for the rx mbufs */
14709         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14710                                 1,                  /* alignment */
14711                                 0,                  /* boundary limit */
14712                                 BUS_SPACE_MAXADDR,  /* restricted low */
14713                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14714                                 NULL,               /* addr filter() */
14715                                 NULL,               /* addr filter() arg */
14716                                 MJUM9BYTES,         /* max map size */
14717                                 1,                  /* num discontinuous */
14718                                 MJUM9BYTES,         /* max seg size */
14719                                 0,                  /* flags */
14720                                 NULL,               /* lock() */
14721                                 NULL,               /* lock() arg */
14722                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14723         if (rc != 0) {
14724             /* XXX unwind and free previous fastpath allocations */
14725             BLOGE(sc, "Failed to create dma tag for "
14726                       "'fp %d rx mbufs' (%d)\n", i, rc);
14727             return (1);
14728         }
14729
14730         /* create dma maps for each of the rx mbuf clusters */
14731         for (j = 0; j < RX_BD_TOTAL; j++) {
14732             if (bus_dmamap_create(fp->rx_mbuf_tag,
14733                                   BUS_DMA_NOWAIT,
14734                                   &fp->rx_mbuf_chain[j].m_map)) {
14735                 /* XXX unwind and free previous fastpath allocations */
14736                 BLOGE(sc, "Failed to create dma map for "
14737                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14738                 return (1);
14739             }
14740         }
14741
14742         /* create dma map for the spare rx mbuf cluster */
14743         if (bus_dmamap_create(fp->rx_mbuf_tag,
14744                               BUS_DMA_NOWAIT,
14745                               &fp->rx_mbuf_spare_map)) {
14746             /* XXX unwind and free previous fastpath allocations */
14747             BLOGE(sc, "Failed to create dma map for "
14748                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14749             return (1);
14750         }
14751
14752         /***************************/
14753         /* FP RX SGE MBUF DMA MAPS */
14754         /***************************/
14755
14756         /* create a dma tag for the rx sge mbufs */
14757         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14758                                 1,                  /* alignment */
14759                                 0,                  /* boundary limit */
14760                                 BUS_SPACE_MAXADDR,  /* restricted low */
14761                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14762                                 NULL,               /* addr filter() */
14763                                 NULL,               /* addr filter() arg */
14764                                 BCM_PAGE_SIZE,      /* max map size */
14765                                 1,                  /* num discontinuous */
14766                                 BCM_PAGE_SIZE,      /* max seg size */
14767                                 0,                  /* flags */
14768                                 NULL,               /* lock() */
14769                                 NULL,               /* lock() arg */
14770                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14771         if (rc != 0) {
14772             /* XXX unwind and free previous fastpath allocations */
14773             BLOGE(sc, "Failed to create dma tag for "
14774                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14775             return (1);
14776         }
14777
14778         /* create dma maps for the rx sge mbuf clusters */
14779         for (j = 0; j < RX_SGE_TOTAL; j++) {
14780             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14781                                   BUS_DMA_NOWAIT,
14782                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14783                 /* XXX unwind and free previous fastpath allocations */
14784                 BLOGE(sc, "Failed to create dma map for "
14785                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14786                 return (1);
14787             }
14788         }
14789
14790         /* create dma map for the spare rx sge mbuf cluster */
14791         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14792                               BUS_DMA_NOWAIT,
14793                               &fp->rx_sge_mbuf_spare_map)) {
14794             /* XXX unwind and free previous fastpath allocations */
14795             BLOGE(sc, "Failed to create dma map for "
14796                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14797             return (1);
14798         }
14799
14800         /***************************/
14801         /* FP RX TPA MBUF DMA MAPS */
14802         /***************************/
14803
14804         /* create dma maps for the rx tpa mbuf clusters */
14805         max_agg_queues = MAX_AGG_QS(sc);
14806
14807         for (j = 0; j < max_agg_queues; j++) {
14808             if (bus_dmamap_create(fp->rx_mbuf_tag,
14809                                   BUS_DMA_NOWAIT,
14810                                   &fp->rx_tpa_info[j].bd.m_map)) {
14811                 /* XXX unwind and free previous fastpath allocations */
14812                 BLOGE(sc, "Failed to create dma map for "
14813                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14814                 return (1);
14815             }
14816         }
14817
14818         /* create dma map for the spare rx tpa mbuf cluster */
14819         if (bus_dmamap_create(fp->rx_mbuf_tag,
14820                               BUS_DMA_NOWAIT,
14821                               &fp->rx_tpa_info_mbuf_spare_map)) {
14822             /* XXX unwind and free previous fastpath allocations */
14823             BLOGE(sc, "Failed to create dma map for "
14824                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14825             return (1);
14826         }
14827
14828         bxe_init_sge_ring_bit_mask(fp);
14829     }
14830
14831     return (0);
14832 }
14833
14834 static void
14835 bxe_free_hsi_mem(struct bxe_softc *sc)
14836 {
14837     struct bxe_fastpath *fp;
14838     int max_agg_queues;
14839     int i, j;
14840
14841     if (sc->parent_dma_tag == NULL) {
14842         return; /* assume nothing was allocated */
14843     }
14844
14845     for (i = 0; i < sc->num_queues; i++) {
14846         fp = &sc->fp[i];
14847
14848         /*******************/
14849         /* FP STATUS BLOCK */
14850         /*******************/
14851
14852         bxe_dma_free(sc, &fp->sb_dma);
14853         memset(&fp->status_block, 0, sizeof(fp->status_block));
14854
14855         /******************/
14856         /* FP TX BD CHAIN */
14857         /******************/
14858
14859         bxe_dma_free(sc, &fp->tx_dma);
14860         fp->tx_chain = NULL;
14861
14862         /******************/
14863         /* FP RX BD CHAIN */
14864         /******************/
14865
14866         bxe_dma_free(sc, &fp->rx_dma);
14867         fp->rx_chain = NULL;
14868
14869         /*******************/
14870         /* FP RX RCQ CHAIN */
14871         /*******************/
14872
14873         bxe_dma_free(sc, &fp->rcq_dma);
14874         fp->rcq_chain = NULL;
14875
14876         /*******************/
14877         /* FP RX SGE CHAIN */
14878         /*******************/
14879
14880         bxe_dma_free(sc, &fp->rx_sge_dma);
14881         fp->rx_sge_chain = NULL;
14882
14883         /***********************/
14884         /* FP TX MBUF DMA MAPS */
14885         /***********************/
14886
14887         if (fp->tx_mbuf_tag != NULL) {
14888             for (j = 0; j < TX_BD_TOTAL; j++) {
14889                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14890                     bus_dmamap_unload(fp->tx_mbuf_tag,
14891                                       fp->tx_mbuf_chain[j].m_map);
14892                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14893                                        fp->tx_mbuf_chain[j].m_map);
14894                 }
14895             }
14896
14897             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14898             fp->tx_mbuf_tag = NULL;
14899         }
14900
14901         /***********************/
14902         /* FP RX MBUF DMA MAPS */
14903         /***********************/
14904
14905         if (fp->rx_mbuf_tag != NULL) {
14906             for (j = 0; j < RX_BD_TOTAL; j++) {
14907                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14908                     bus_dmamap_unload(fp->rx_mbuf_tag,
14909                                       fp->rx_mbuf_chain[j].m_map);
14910                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14911                                        fp->rx_mbuf_chain[j].m_map);
14912                 }
14913             }
14914
14915             if (fp->rx_mbuf_spare_map != NULL) {
14916                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14917                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14918             }
14919
14920             /***************************/
14921             /* FP RX TPA MBUF DMA MAPS */
14922             /***************************/
14923
14924             max_agg_queues = MAX_AGG_QS(sc);
14925
14926             for (j = 0; j < max_agg_queues; j++) {
14927                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14928                     bus_dmamap_unload(fp->rx_mbuf_tag,
14929                                       fp->rx_tpa_info[j].bd.m_map);
14930                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14931                                        fp->rx_tpa_info[j].bd.m_map);
14932                 }
14933             }
14934
14935             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14936                 bus_dmamap_unload(fp->rx_mbuf_tag,
14937                                   fp->rx_tpa_info_mbuf_spare_map);
14938                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14939                                    fp->rx_tpa_info_mbuf_spare_map);
14940             }
14941
14942             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14943             fp->rx_mbuf_tag = NULL;
14944         }
14945
14946         /***************************/
14947         /* FP RX SGE MBUF DMA MAPS */
14948         /***************************/
14949
14950         if (fp->rx_sge_mbuf_tag != NULL) {
14951             for (j = 0; j < RX_SGE_TOTAL; j++) {
14952                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14953                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14954                                       fp->rx_sge_mbuf_chain[j].m_map);
14955                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14956                                        fp->rx_sge_mbuf_chain[j].m_map);
14957                 }
14958             }
14959
14960             if (fp->rx_sge_mbuf_spare_map != NULL) {
14961                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14962                                   fp->rx_sge_mbuf_spare_map);
14963                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14964                                    fp->rx_sge_mbuf_spare_map);
14965             }
14966
14967             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14968             fp->rx_sge_mbuf_tag = NULL;
14969         }
14970     }
14971
14972     /***************************/
14973     /* FW DECOMPRESSION BUFFER */
14974     /***************************/
14975
14976     bxe_dma_free(sc, &sc->gz_buf_dma);
14977     sc->gz_buf = NULL;
14978     free(sc->gz_strm, M_DEVBUF);
14979     sc->gz_strm = NULL;
14980
14981     /*******************/
14982     /* SLOW PATH QUEUE */
14983     /*******************/
14984
14985     bxe_dma_free(sc, &sc->spq_dma);
14986     sc->spq = NULL;
14987
14988     /*************/
14989     /* SLOW PATH */
14990     /*************/
14991
14992     bxe_dma_free(sc, &sc->sp_dma);
14993     sc->sp = NULL;
14994
14995     /***************/
14996     /* EVENT QUEUE */
14997     /***************/
14998
14999     bxe_dma_free(sc, &sc->eq_dma);
15000     sc->eq = NULL;
15001
15002     /************************/
15003     /* DEFAULT STATUS BLOCK */
15004     /************************/
15005
15006     bxe_dma_free(sc, &sc->def_sb_dma);
15007     sc->def_sb = NULL;
15008
15009     bus_dma_tag_destroy(sc->parent_dma_tag);
15010     sc->parent_dma_tag = NULL;
15011 }
15012
15013 /*
15014  * Previous driver DMAE transaction may have occurred when pre-boot stage
15015  * ended and boot began. This would invalidate the addresses of the
15016  * transaction, resulting in was-error bit set in the PCI causing all
15017  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15018  * the interrupt which detected this from the pglueb and the was-done bit
15019  */
15020 static void
15021 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15022 {
15023     uint32_t val;
15024
15025     if (!CHIP_IS_E1x(sc)) {
15026         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15027         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15028             BLOGD(sc, DBG_LOAD,
15029                   "Clearing 'was-error' bit that was set in pglueb");
15030             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15031         }
15032     }
15033 }
15034
15035 static int
15036 bxe_prev_mcp_done(struct bxe_softc *sc)
15037 {
15038     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15039                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15040     if (!rc) {
15041         BLOGE(sc, "MCP response failure, aborting\n");
15042         return (-1);
15043     }
15044
15045     return (0);
15046 }
15047
15048 static struct bxe_prev_list_node *
15049 bxe_prev_path_get_entry(struct bxe_softc *sc)
15050 {
15051     struct bxe_prev_list_node *tmp;
15052
15053     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15054         if ((sc->pcie_bus == tmp->bus) &&
15055             (sc->pcie_device == tmp->slot) &&
15056             (SC_PATH(sc) == tmp->path)) {
15057             return (tmp);
15058         }
15059     }
15060
15061     return (NULL);
15062 }
15063
15064 static uint8_t
15065 bxe_prev_is_path_marked(struct bxe_softc *sc)
15066 {
15067     struct bxe_prev_list_node *tmp;
15068     int rc = FALSE;
15069
15070     mtx_lock(&bxe_prev_mtx);
15071
15072     tmp = bxe_prev_path_get_entry(sc);
15073     if (tmp) {
15074         if (tmp->aer) {
15075             BLOGD(sc, DBG_LOAD,
15076                   "Path %d/%d/%d was marked by AER\n",
15077                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15078         } else {
15079             rc = TRUE;
15080             BLOGD(sc, DBG_LOAD,
15081                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15082                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15083         }
15084     }
15085
15086     mtx_unlock(&bxe_prev_mtx);
15087
15088     return (rc);
15089 }
15090
15091 static int
15092 bxe_prev_mark_path(struct bxe_softc *sc,
15093                    uint8_t          after_undi)
15094 {
15095     struct bxe_prev_list_node *tmp;
15096
15097     mtx_lock(&bxe_prev_mtx);
15098
15099     /* Check whether the entry for this path already exists */
15100     tmp = bxe_prev_path_get_entry(sc);
15101     if (tmp) {
15102         if (!tmp->aer) {
15103             BLOGD(sc, DBG_LOAD,
15104                   "Re-marking AER in path %d/%d/%d\n",
15105                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15106         } else {
15107             BLOGD(sc, DBG_LOAD,
15108                   "Removing AER indication from path %d/%d/%d\n",
15109                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15110             tmp->aer = 0;
15111         }
15112
15113         mtx_unlock(&bxe_prev_mtx);
15114         return (0);
15115     }
15116
15117     mtx_unlock(&bxe_prev_mtx);
15118
15119     /* Create an entry for this path and add it */
15120     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15121                  (M_NOWAIT | M_ZERO));
15122     if (!tmp) {
15123         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15124         return (-1);
15125     }
15126
15127     tmp->bus  = sc->pcie_bus;
15128     tmp->slot = sc->pcie_device;
15129     tmp->path = SC_PATH(sc);
15130     tmp->aer  = 0;
15131     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15132
15133     mtx_lock(&bxe_prev_mtx);
15134
15135     BLOGD(sc, DBG_LOAD,
15136           "Marked path %d/%d/%d - finished previous unload\n",
15137           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15138     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15139
15140     mtx_unlock(&bxe_prev_mtx);
15141
15142     return (0);
15143 }
15144
15145 static int
15146 bxe_do_flr(struct bxe_softc *sc)
15147 {
15148     int i;
15149
15150     /* only E2 and onwards support FLR */
15151     if (CHIP_IS_E1x(sc)) {
15152         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15153         return (-1);
15154     }
15155
15156     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15157     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15158         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15159               sc->devinfo.bc_ver);
15160         return (-1);
15161     }
15162
15163     /* Wait for Transaction Pending bit clean */
15164     for (i = 0; i < 4; i++) {
15165         if (i) {
15166             DELAY(((1 << (i - 1)) * 100) * 1000);
15167         }
15168
15169         if (!bxe_is_pcie_pending(sc)) {
15170             goto clear;
15171         }
15172     }
15173
15174     BLOGE(sc, "PCIE transaction is not cleared, "
15175               "proceeding with reset anyway\n");
15176
15177 clear:
15178
15179     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15180     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15181
15182     return (0);
15183 }
15184
15185 struct bxe_mac_vals {
15186     uint32_t xmac_addr;
15187     uint32_t xmac_val;
15188     uint32_t emac_addr;
15189     uint32_t emac_val;
15190     uint32_t umac_addr;
15191     uint32_t umac_val;
15192     uint32_t bmac_addr;
15193     uint32_t bmac_val[2];
15194 };
15195
15196 static void
15197 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15198                           struct bxe_mac_vals *vals)
15199 {
15200     uint32_t val, base_addr, offset, mask, reset_reg;
15201     uint8_t mac_stopped = FALSE;
15202     uint8_t port = SC_PORT(sc);
15203     uint32_t wb_data[2];
15204
15205     /* reset addresses as they also mark which values were changed */
15206     vals->bmac_addr = 0;
15207     vals->umac_addr = 0;
15208     vals->xmac_addr = 0;
15209     vals->emac_addr = 0;
15210
15211     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15212
15213     if (!CHIP_IS_E3(sc)) {
15214         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15215         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15216         if ((mask & reset_reg) && val) {
15217             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15218             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15219                                     : NIG_REG_INGRESS_BMAC0_MEM;
15220             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15221                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15222
15223             /*
15224              * use rd/wr since we cannot use dmae. This is safe
15225              * since MCP won't access the bus due to the request
15226              * to unload, and no function on the path can be
15227              * loaded at this time.
15228              */
15229             wb_data[0] = REG_RD(sc, base_addr + offset);
15230             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15231             vals->bmac_addr = base_addr + offset;
15232             vals->bmac_val[0] = wb_data[0];
15233             vals->bmac_val[1] = wb_data[1];
15234             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15235             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15236             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15237         }
15238
15239         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15240         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15241         vals->emac_val = REG_RD(sc, vals->emac_addr);
15242         REG_WR(sc, vals->emac_addr, 0);
15243         mac_stopped = TRUE;
15244     } else {
15245         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15246             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15247             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15248             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15249             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15250             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15251             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15252             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15253             REG_WR(sc, vals->xmac_addr, 0);
15254             mac_stopped = TRUE;
15255         }
15256
15257         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15258         if (mask & reset_reg) {
15259             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15260             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15261             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15262             vals->umac_val = REG_RD(sc, vals->umac_addr);
15263             REG_WR(sc, vals->umac_addr, 0);
15264             mac_stopped = TRUE;
15265         }
15266     }
15267
15268     if (mac_stopped) {
15269         DELAY(20000);
15270     }
15271 }
15272
15273 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15274 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15275 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15276 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15277
15278 static void
15279 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15280                          uint8_t          port,
15281                          uint8_t          inc)
15282 {
15283     uint16_t rcq, bd;
15284     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15285
15286     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15287     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15288
15289     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15290     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15291
15292     BLOGD(sc, DBG_LOAD,
15293           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15294           port, bd, rcq);
15295 }
15296
15297 static int
15298 bxe_prev_unload_common(struct bxe_softc *sc)
15299 {
15300     uint32_t reset_reg, tmp_reg = 0, rc;
15301     uint8_t prev_undi = FALSE;
15302     struct bxe_mac_vals mac_vals;
15303     uint32_t timer_count = 1000;
15304     uint32_t prev_brb;
15305
15306     /*
15307      * It is possible a previous function received 'common' answer,
15308      * but hasn't loaded yet, therefore creating a scenario of
15309      * multiple functions receiving 'common' on the same path.
15310      */
15311     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15312
15313     memset(&mac_vals, 0, sizeof(mac_vals));
15314
15315     if (bxe_prev_is_path_marked(sc)) {
15316         return (bxe_prev_mcp_done(sc));
15317     }
15318
15319     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15320
15321     /* Reset should be performed after BRB is emptied */
15322     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15323         /* Close the MAC Rx to prevent BRB from filling up */
15324         bxe_prev_unload_close_mac(sc, &mac_vals);
15325
15326         /* close LLH filters towards the BRB */
15327         elink_set_rx_filter(&sc->link_params, 0);
15328
15329         /*
15330          * Check if the UNDI driver was previously loaded.
15331          * UNDI driver initializes CID offset for normal bell to 0x7
15332          */
15333         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15334             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15335             if (tmp_reg == 0x7) {
15336                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15337                 prev_undi = TRUE;
15338                 /* clear the UNDI indication */
15339                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15340                 /* clear possible idle check errors */
15341                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15342             }
15343         }
15344
15345         /* wait until BRB is empty */
15346         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15347         while (timer_count) {
15348             prev_brb = tmp_reg;
15349
15350             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15351             if (!tmp_reg) {
15352                 break;
15353             }
15354
15355             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15356
15357             /* reset timer as long as BRB actually gets emptied */
15358             if (prev_brb > tmp_reg) {
15359                 timer_count = 1000;
15360             } else {
15361                 timer_count--;
15362             }
15363
15364             /* If UNDI resides in memory, manually increment it */
15365             if (prev_undi) {
15366                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15367             }
15368
15369             DELAY(10);
15370         }
15371
15372         if (!timer_count) {
15373             BLOGE(sc, "Failed to empty BRB\n");
15374         }
15375     }
15376
15377     /* No packets are in the pipeline, path is ready for reset */
15378     bxe_reset_common(sc);
15379
15380     if (mac_vals.xmac_addr) {
15381         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15382     }
15383     if (mac_vals.umac_addr) {
15384         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15385     }
15386     if (mac_vals.emac_addr) {
15387         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15388     }
15389     if (mac_vals.bmac_addr) {
15390         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15391         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15392     }
15393
15394     rc = bxe_prev_mark_path(sc, prev_undi);
15395     if (rc) {
15396         bxe_prev_mcp_done(sc);
15397         return (rc);
15398     }
15399
15400     return (bxe_prev_mcp_done(sc));
15401 }
15402
15403 static int
15404 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15405 {
15406     int rc;
15407
15408     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15409
15410     /* Test if previous unload process was already finished for this path */
15411     if (bxe_prev_is_path_marked(sc)) {
15412         return (bxe_prev_mcp_done(sc));
15413     }
15414
15415     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15416
15417     /*
15418      * If function has FLR capabilities, and existing FW version matches
15419      * the one required, then FLR will be sufficient to clean any residue
15420      * left by previous driver
15421      */
15422     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15423     if (!rc) {
15424         /* fw version is good */
15425         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15426         rc = bxe_do_flr(sc);
15427     }
15428
15429     if (!rc) {
15430         /* FLR was performed */
15431         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15432         return (0);
15433     }
15434
15435     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15436
15437     /* Close the MCP request, return failure*/
15438     rc = bxe_prev_mcp_done(sc);
15439     if (!rc) {
15440         rc = BXE_PREV_WAIT_NEEDED;
15441     }
15442
15443     return (rc);
15444 }
15445
15446 static int
15447 bxe_prev_unload(struct bxe_softc *sc)
15448 {
15449     int time_counter = 10;
15450     uint32_t fw, hw_lock_reg, hw_lock_val;
15451     uint32_t rc = 0;
15452
15453     /*
15454      * Clear HW from errors which may have resulted from an interrupted
15455      * DMAE transaction.
15456      */
15457     bxe_prev_interrupted_dmae(sc);
15458
15459     /* Release previously held locks */
15460     hw_lock_reg =
15461         (SC_FUNC(sc) <= 5) ?
15462             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15463             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15464
15465     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15466     if (hw_lock_val) {
15467         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15468             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15469             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15470                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15471         }
15472         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15473         REG_WR(sc, hw_lock_reg, 0xffffffff);
15474     } else {
15475         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15476     }
15477
15478     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15479         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15480         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15481     }
15482
15483     do {
15484         /* Lock MCP using an unload request */
15485         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15486         if (!fw) {
15487             BLOGE(sc, "MCP response failure, aborting\n");
15488             rc = -1;
15489             break;
15490         }
15491
15492         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15493             rc = bxe_prev_unload_common(sc);
15494             break;
15495         }
15496
15497         /* non-common reply from MCP night require looping */
15498         rc = bxe_prev_unload_uncommon(sc);
15499         if (rc != BXE_PREV_WAIT_NEEDED) {
15500             break;
15501         }
15502
15503         DELAY(20000);
15504     } while (--time_counter);
15505
15506     if (!time_counter || rc) {
15507         BLOGE(sc, "Failed to unload previous driver!"
15508             " time_counter %d rc %d\n", time_counter, rc);
15509         rc = -1;
15510     }
15511
15512     return (rc);
15513 }
15514
15515 void
15516 bxe_dcbx_set_state(struct bxe_softc *sc,
15517                    uint8_t          dcb_on,
15518                    uint32_t         dcbx_enabled)
15519 {
15520     if (!CHIP_IS_E1x(sc)) {
15521         sc->dcb_state = dcb_on;
15522         sc->dcbx_enabled = dcbx_enabled;
15523     } else {
15524         sc->dcb_state = FALSE;
15525         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15526     }
15527     BLOGD(sc, DBG_LOAD,
15528           "DCB state [%s:%s]\n",
15529           dcb_on ? "ON" : "OFF",
15530           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15531           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15532           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15533           "on-chip with negotiation" : "invalid");
15534 }
15535
15536 /* must be called after sriov-enable */
15537 static int
15538 bxe_set_qm_cid_count(struct bxe_softc *sc)
15539 {
15540     int cid_count = BXE_L2_MAX_CID(sc);
15541
15542     if (IS_SRIOV(sc)) {
15543         cid_count += BXE_VF_CIDS;
15544     }
15545
15546     if (CNIC_SUPPORT(sc)) {
15547         cid_count += CNIC_CID_MAX;
15548     }
15549
15550     return (roundup(cid_count, QM_CID_ROUND));
15551 }
15552
15553 static void
15554 bxe_init_multi_cos(struct bxe_softc *sc)
15555 {
15556     int pri, cos;
15557
15558     uint32_t pri_map = 0; /* XXX change to user config */
15559
15560     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15561         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15562         if (cos < sc->max_cos) {
15563             sc->prio_to_cos[pri] = cos;
15564         } else {
15565             BLOGW(sc, "Invalid COS %d for priority %d "
15566                       "(max COS is %d), setting to 0\n",
15567                   cos, pri, (sc->max_cos - 1));
15568             sc->prio_to_cos[pri] = 0;
15569         }
15570     }
15571 }
15572
15573 static int
15574 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15575 {
15576     struct bxe_softc *sc;
15577     int error, result;
15578
15579     result = 0;
15580     error = sysctl_handle_int(oidp, &result, 0, req);
15581
15582     if (error || !req->newptr) {
15583         return (error);
15584     }
15585
15586     if (result == 1) {
15587         uint32_t  temp;
15588         sc = (struct bxe_softc *)arg1;
15589
15590         BLOGI(sc, "... dumping driver state ...\n");
15591         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15592         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15593     }
15594
15595     return (error);
15596 }
15597
15598 static int
15599 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15600 {
15601     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15602     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15603     uint32_t *offset;
15604     uint64_t value = 0;
15605     int index = (int)arg2;
15606
15607     if (index >= BXE_NUM_ETH_STATS) {
15608         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15609         return (-1);
15610     }
15611
15612     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15613
15614     switch (bxe_eth_stats_arr[index].size) {
15615     case 4:
15616         value = (uint64_t)*offset;
15617         break;
15618     case 8:
15619         value = HILO_U64(*offset, *(offset + 1));
15620         break;
15621     default:
15622         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15623               index, bxe_eth_stats_arr[index].size);
15624         return (-1);
15625     }
15626
15627     return (sysctl_handle_64(oidp, &value, 0, req));
15628 }
15629
15630 static int
15631 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15632 {
15633     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15634     uint32_t *eth_stats;
15635     uint32_t *offset;
15636     uint64_t value = 0;
15637     uint32_t q_stat = (uint32_t)arg2;
15638     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15639     uint32_t index = (q_stat & 0xffff);
15640
15641     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15642
15643     if (index >= BXE_NUM_ETH_Q_STATS) {
15644         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15645         return (-1);
15646     }
15647
15648     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15649
15650     switch (bxe_eth_q_stats_arr[index].size) {
15651     case 4:
15652         value = (uint64_t)*offset;
15653         break;
15654     case 8:
15655         value = HILO_U64(*offset, *(offset + 1));
15656         break;
15657     default:
15658         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15659               index, bxe_eth_q_stats_arr[index].size);
15660         return (-1);
15661     }
15662
15663     return (sysctl_handle_64(oidp, &value, 0, req));
15664 }
15665
15666 static void bxe_force_link_reset(struct bxe_softc *sc)
15667 {
15668
15669         bxe_acquire_phy_lock(sc);
15670         elink_link_reset(&sc->link_params, &sc->link_vars, 1);
15671         bxe_release_phy_lock(sc);
15672 }
15673
15674 static int
15675 bxe_sysctl_pauseparam(SYSCTL_HANDLER_ARGS)
15676 {
15677         struct bxe_softc *sc = (struct bxe_softc *)arg1;;
15678         uint32_t cfg_idx = bxe_get_link_cfg_idx(sc);
15679         int rc = 0;
15680         int error;
15681         int result;
15682
15683
15684         error = sysctl_handle_int(oidp, &sc->bxe_pause_param, 0, req);
15685
15686         if (error || !req->newptr) {
15687                 return (error);
15688         }
15689         if ((sc->bxe_pause_param < 0) ||  (sc->bxe_pause_param > 8)) {
15690                 BLOGW(sc, "invalid pause param (%d) - use intergers between 1 & 8\n",sc->bxe_pause_param);
15691                 sc->bxe_pause_param = 8;
15692         }
15693
15694         result = (sc->bxe_pause_param << PORT_FEATURE_FLOW_CONTROL_SHIFT);
15695
15696
15697         if((result & 0x400) && !(sc->port.supported[cfg_idx] & ELINK_SUPPORTED_Autoneg))  {
15698                         BLOGW(sc, "Does not support Autoneg pause_param %d\n", sc->bxe_pause_param);
15699                         return -EINVAL;
15700         }
15701
15702         if(IS_MF(sc))
15703                 return 0;
15704        sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_AUTO;
15705         if(result & ELINK_FLOW_CTRL_RX)
15706                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_RX;
15707
15708         if(result & ELINK_FLOW_CTRL_TX)
15709                 sc->link_params.req_flow_ctrl[cfg_idx] |= ELINK_FLOW_CTRL_TX;
15710         if(sc->link_params.req_flow_ctrl[cfg_idx] == ELINK_FLOW_CTRL_AUTO)
15711                 sc->link_params.req_flow_ctrl[cfg_idx] = ELINK_FLOW_CTRL_NONE;
15712
15713         if(result & 0x400) {
15714                 if (sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG) {
15715                         sc->link_params.req_flow_ctrl[cfg_idx] =
15716                                 ELINK_FLOW_CTRL_AUTO;
15717                 }
15718                 sc->link_params.req_fc_auto_adv = 0;
15719                 if (result & ELINK_FLOW_CTRL_RX)
15720                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_RX;
15721
15722                 if (result & ELINK_FLOW_CTRL_TX)
15723                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_TX;
15724                 if (!sc->link_params.req_fc_auto_adv)
15725                         sc->link_params.req_fc_auto_adv |= ELINK_FLOW_CTRL_NONE;
15726         }
15727          if (IS_PF(sc)) {
15728                 if (sc->link_vars.link_up) {
15729                         bxe_stats_handle(sc, STATS_EVENT_STOP);
15730                 }
15731                 if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
15732                         bxe_force_link_reset(sc);
15733                         bxe_acquire_phy_lock(sc);
15734
15735                         rc = elink_phy_init(&sc->link_params, &sc->link_vars);
15736
15737                         bxe_release_phy_lock(sc);
15738
15739                         bxe_calc_fc_adv(sc);
15740                 }
15741         }
15742         return rc;
15743 }
15744
15745
15746 static void
15747 bxe_add_sysctls(struct bxe_softc *sc)
15748 {
15749     struct sysctl_ctx_list *ctx;
15750     struct sysctl_oid_list *children;
15751     struct sysctl_oid *queue_top, *queue;
15752     struct sysctl_oid_list *queue_top_children, *queue_children;
15753     char queue_num_buf[32];
15754     uint32_t q_stat;
15755     int i, j;
15756
15757     ctx = device_get_sysctl_ctx(sc->dev);
15758     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15759
15760     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15761                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15762                       "version");
15763
15764     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15765              BCM_5710_FW_MAJOR_VERSION,
15766              BCM_5710_FW_MINOR_VERSION,
15767              BCM_5710_FW_REVISION_VERSION,
15768              BCM_5710_FW_ENGINEERING_VERSION);
15769
15770     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15771         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15772          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15773          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15774          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15775                                                                 "Unknown"));
15776     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15777                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15778                     "multifunction vnics per port");
15779
15780     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15781         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15782          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15783          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15784                                               "???GT/s"),
15785         sc->devinfo.pcie_link_width);
15786
15787     sc->debug = bxe_debug;
15788
15789 #if __FreeBSD_version >= 900000
15790     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15791                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15792                       "bootcode version");
15793     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15794                       CTLFLAG_RD, sc->fw_ver_str, 0,
15795                       "firmware version");
15796     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15797                       CTLFLAG_RD, sc->mf_mode_str, 0,
15798                       "multifunction mode");
15799     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15800                       CTLFLAG_RD, sc->mac_addr_str, 0,
15801                       "mac address");
15802     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15803                       CTLFLAG_RD, sc->pci_link_str, 0,
15804                       "pci link status");
15805     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15806                     CTLFLAG_RW, &sc->debug,
15807                     "debug logging mode");
15808 #else
15809     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15810                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15811                       "bootcode version");
15812     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15813                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15814                       "firmware version");
15815     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15816                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15817                       "multifunction mode");
15818     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15819                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15820                       "mac address");
15821     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15822                       CTLFLAG_RD, &sc->pci_link_str, 0,
15823                       "pci link status");
15824     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15825                     CTLFLAG_RW, &sc->debug, 0,
15826                     "debug logging mode");
15827 #endif /* #if __FreeBSD_version >= 900000 */
15828
15829     sc->trigger_grcdump = 0;
15830     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15831                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15832                    "trigger grcdump should be invoked"
15833                    "  before collecting grcdump");
15834
15835     sc->grcdump_started = 0;
15836     sc->grcdump_done = 0;
15837     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15838                    CTLFLAG_RD, &sc->grcdump_done, 0,
15839                    "set by driver when grcdump is done");
15840
15841     sc->rx_budget = bxe_rx_budget;
15842     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15843                     CTLFLAG_RW, &sc->rx_budget, 0,
15844                     "rx processing budget");
15845
15846    SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_param",
15847                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15848                     bxe_sysctl_pauseparam, "IU",
15849                     "need pause frames- DEF:0/TX:1/RX:2/BOTH:3/AUTO:4/AUTOTX:5/AUTORX:6/AUTORXTX:7/NONE:8");
15850
15851
15852     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15853                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15854                     bxe_sysctl_state, "IU", "dump driver state");
15855
15856     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15857         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15858                         bxe_eth_stats_arr[i].string,
15859                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15860                         bxe_sysctl_eth_stat, "LU",
15861                         bxe_eth_stats_arr[i].string);
15862     }
15863
15864     /* add a new parent node for all queues "dev.bxe.#.queue" */
15865     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15866                                 CTLFLAG_RD, NULL, "queue");
15867     queue_top_children = SYSCTL_CHILDREN(queue_top);
15868
15869     for (i = 0; i < sc->num_queues; i++) {
15870         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15871         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15872         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15873                                 queue_num_buf, CTLFLAG_RD, NULL,
15874                                 "single queue");
15875         queue_children = SYSCTL_CHILDREN(queue);
15876
15877         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15878             q_stat = ((i << 16) | j);
15879             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15880                             bxe_eth_q_stats_arr[j].string,
15881                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15882                             bxe_sysctl_eth_q_stat, "LU",
15883                             bxe_eth_q_stats_arr[j].string);
15884         }
15885     }
15886 }
15887
15888 static int
15889 bxe_alloc_buf_rings(struct bxe_softc *sc)
15890 {
15891 #if __FreeBSD_version >= 901504
15892
15893     int i;
15894     struct bxe_fastpath *fp;
15895
15896     for (i = 0; i < sc->num_queues; i++) {
15897
15898         fp = &sc->fp[i];
15899
15900         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15901                                    M_NOWAIT, &fp->tx_mtx);
15902         if (fp->tx_br == NULL)
15903             return (-1);
15904     }
15905 #endif
15906     return (0);
15907 }
15908
15909 static void
15910 bxe_free_buf_rings(struct bxe_softc *sc)
15911 {
15912 #if __FreeBSD_version >= 901504
15913
15914     int i;
15915     struct bxe_fastpath *fp;
15916
15917     for (i = 0; i < sc->num_queues; i++) {
15918
15919         fp = &sc->fp[i];
15920
15921         if (fp->tx_br) {
15922             buf_ring_free(fp->tx_br, M_DEVBUF);
15923             fp->tx_br = NULL;
15924         }
15925     }
15926
15927 #endif
15928 }
15929
15930 static void
15931 bxe_init_fp_mutexs(struct bxe_softc *sc)
15932 {
15933     int i;
15934     struct bxe_fastpath *fp;
15935
15936     for (i = 0; i < sc->num_queues; i++) {
15937
15938         fp = &sc->fp[i];
15939
15940         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15941             "bxe%d_fp%d_tx_lock", sc->unit, i);
15942         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15943
15944         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15945             "bxe%d_fp%d_rx_lock", sc->unit, i);
15946         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15947     }
15948 }
15949
15950 static void
15951 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15952 {
15953     int i;
15954     struct bxe_fastpath *fp;
15955
15956     for (i = 0; i < sc->num_queues; i++) {
15957
15958         fp = &sc->fp[i];
15959
15960         if (mtx_initialized(&fp->tx_mtx)) {
15961             mtx_destroy(&fp->tx_mtx);
15962         }
15963
15964         if (mtx_initialized(&fp->rx_mtx)) {
15965             mtx_destroy(&fp->rx_mtx);
15966         }
15967     }
15968 }
15969
15970
15971 /*
15972  * Device attach function.
15973  *
15974  * Allocates device resources, performs secondary chip identification, and
15975  * initializes driver instance variables. This function is called from driver
15976  * load after a successful probe.
15977  *
15978  * Returns:
15979  *   0 = Success, >0 = Failure
15980  */
15981 static int
15982 bxe_attach(device_t dev)
15983 {
15984     struct bxe_softc *sc;
15985
15986     sc = device_get_softc(dev);
15987
15988     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15989
15990     sc->state = BXE_STATE_CLOSED;
15991
15992     sc->dev  = dev;
15993     sc->unit = device_get_unit(dev);
15994
15995     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15996
15997     sc->pcie_bus    = pci_get_bus(dev);
15998     sc->pcie_device = pci_get_slot(dev);
15999     sc->pcie_func   = pci_get_function(dev);
16000
16001     /* enable bus master capability */
16002     pci_enable_busmaster(dev);
16003
16004     /* get the BARs */
16005     if (bxe_allocate_bars(sc) != 0) {
16006         return (ENXIO);
16007     }
16008
16009     /* initialize the mutexes */
16010     bxe_init_mutexes(sc);
16011
16012     /* prepare the periodic callout */
16013     callout_init(&sc->periodic_callout, 0);
16014
16015     /* prepare the chip taskqueue */
16016     sc->chip_tq_flags = CHIP_TQ_NONE;
16017     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
16018              "bxe%d_chip_tq", sc->unit);
16019     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
16020     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
16021                                    taskqueue_thread_enqueue,
16022                                    &sc->chip_tq);
16023     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
16024                             "%s", sc->chip_tq_name);
16025
16026     /* get device info and set params */
16027     if (bxe_get_device_info(sc) != 0) {
16028         BLOGE(sc, "getting device info\n");
16029         bxe_deallocate_bars(sc);
16030         pci_disable_busmaster(dev);
16031         return (ENXIO);
16032     }
16033
16034     /* get final misc params */
16035     bxe_get_params(sc);
16036
16037     /* set the default MTU (changed via ifconfig) */
16038     sc->mtu = ETHERMTU;
16039
16040     bxe_set_modes_bitmap(sc);
16041
16042     /* XXX
16043      * If in AFEX mode and the function is configured for FCoE
16044      * then bail... no L2 allowed.
16045      */
16046
16047     /* get phy settings from shmem and 'and' against admin settings */
16048     bxe_get_phy_info(sc);
16049
16050     /* initialize the FreeBSD ifnet interface */
16051     if (bxe_init_ifnet(sc) != 0) {
16052         bxe_release_mutexes(sc);
16053         bxe_deallocate_bars(sc);
16054         pci_disable_busmaster(dev);
16055         return (ENXIO);
16056     }
16057
16058     if (bxe_add_cdev(sc) != 0) {
16059         if (sc->ifnet != NULL) {
16060             ether_ifdetach(sc->ifnet);
16061         }
16062         ifmedia_removeall(&sc->ifmedia);
16063         bxe_release_mutexes(sc);
16064         bxe_deallocate_bars(sc);
16065         pci_disable_busmaster(dev);
16066         return (ENXIO);
16067     }
16068
16069     /* allocate device interrupts */
16070     if (bxe_interrupt_alloc(sc) != 0) {
16071         bxe_del_cdev(sc);
16072         if (sc->ifnet != NULL) {
16073             ether_ifdetach(sc->ifnet);
16074         }
16075         ifmedia_removeall(&sc->ifmedia);
16076         bxe_release_mutexes(sc);
16077         bxe_deallocate_bars(sc);
16078         pci_disable_busmaster(dev);
16079         return (ENXIO);
16080     }
16081
16082     bxe_init_fp_mutexs(sc);
16083
16084     if (bxe_alloc_buf_rings(sc) != 0) {
16085         bxe_free_buf_rings(sc);
16086         bxe_interrupt_free(sc);
16087         bxe_del_cdev(sc);
16088         if (sc->ifnet != NULL) {
16089             ether_ifdetach(sc->ifnet);
16090         }
16091         ifmedia_removeall(&sc->ifmedia);
16092         bxe_release_mutexes(sc);
16093         bxe_deallocate_bars(sc);
16094         pci_disable_busmaster(dev);
16095         return (ENXIO);
16096     }
16097
16098     /* allocate ilt */
16099     if (bxe_alloc_ilt_mem(sc) != 0) {
16100         bxe_free_buf_rings(sc);
16101         bxe_interrupt_free(sc);
16102         bxe_del_cdev(sc);
16103         if (sc->ifnet != NULL) {
16104             ether_ifdetach(sc->ifnet);
16105         }
16106         ifmedia_removeall(&sc->ifmedia);
16107         bxe_release_mutexes(sc);
16108         bxe_deallocate_bars(sc);
16109         pci_disable_busmaster(dev);
16110         return (ENXIO);
16111     }
16112
16113     /* allocate the host hardware/software hsi structures */
16114     if (bxe_alloc_hsi_mem(sc) != 0) {
16115         bxe_free_ilt_mem(sc);
16116         bxe_free_buf_rings(sc);
16117         bxe_interrupt_free(sc);
16118         bxe_del_cdev(sc);
16119         if (sc->ifnet != NULL) {
16120             ether_ifdetach(sc->ifnet);
16121         }
16122         ifmedia_removeall(&sc->ifmedia);
16123         bxe_release_mutexes(sc);
16124         bxe_deallocate_bars(sc);
16125         pci_disable_busmaster(dev);
16126         return (ENXIO);
16127     }
16128
16129     /* need to reset chip if UNDI was active */
16130     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
16131         /* init fw_seq */
16132         sc->fw_seq =
16133             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
16134              DRV_MSG_SEQ_NUMBER_MASK);
16135         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
16136         bxe_prev_unload(sc);
16137     }
16138
16139 #if 1
16140     /* XXX */
16141     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16142 #else
16143     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16144         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16145         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16146         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16147         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16148         bxe_dcbx_init_params(sc);
16149     } else {
16150         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16151     }
16152 #endif
16153
16154     /* calculate qm_cid_count */
16155     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16156     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16157
16158     sc->max_cos = 1;
16159     bxe_init_multi_cos(sc);
16160
16161     bxe_add_sysctls(sc);
16162
16163     return (0);
16164 }
16165
16166 /*
16167  * Device detach function.
16168  *
16169  * Stops the controller, resets the controller, and releases resources.
16170  *
16171  * Returns:
16172  *   0 = Success, >0 = Failure
16173  */
16174 static int
16175 bxe_detach(device_t dev)
16176 {
16177     struct bxe_softc *sc;
16178     struct ifnet *ifp;
16179
16180     sc = device_get_softc(dev);
16181
16182     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16183
16184     ifp = sc->ifnet;
16185     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16186         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16187         return(EBUSY);
16188     }
16189
16190     bxe_del_cdev(sc);
16191
16192     /* stop the periodic callout */
16193     bxe_periodic_stop(sc);
16194
16195     /* stop the chip taskqueue */
16196     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16197     if (sc->chip_tq) {
16198         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16199         taskqueue_free(sc->chip_tq);
16200         sc->chip_tq = NULL;
16201     }
16202
16203     /* stop and reset the controller if it was open */
16204     if (sc->state != BXE_STATE_CLOSED) {
16205         BXE_CORE_LOCK(sc);
16206         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16207         sc->state = BXE_STATE_DISABLED;
16208         BXE_CORE_UNLOCK(sc);
16209     }
16210
16211     /* release the network interface */
16212     if (ifp != NULL) {
16213         ether_ifdetach(ifp);
16214     }
16215     ifmedia_removeall(&sc->ifmedia);
16216
16217     /* XXX do the following based on driver state... */
16218
16219     /* free the host hardware/software hsi structures */
16220     bxe_free_hsi_mem(sc);
16221
16222     /* free ilt */
16223     bxe_free_ilt_mem(sc);
16224
16225     bxe_free_buf_rings(sc);
16226
16227     /* release the interrupts */
16228     bxe_interrupt_free(sc);
16229
16230     /* Release the mutexes*/
16231     bxe_destroy_fp_mutexs(sc);
16232     bxe_release_mutexes(sc);
16233
16234
16235     /* Release the PCIe BAR mapped memory */
16236     bxe_deallocate_bars(sc);
16237
16238     /* Release the FreeBSD interface. */
16239     if (sc->ifnet != NULL) {
16240         if_free(sc->ifnet);
16241     }
16242
16243     pci_disable_busmaster(dev);
16244
16245     return (0);
16246 }
16247
16248 /*
16249  * Device shutdown function.
16250  *
16251  * Stops and resets the controller.
16252  *
16253  * Returns:
16254  *   Nothing
16255  */
16256 static int
16257 bxe_shutdown(device_t dev)
16258 {
16259     struct bxe_softc *sc;
16260
16261     sc = device_get_softc(dev);
16262
16263     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16264
16265     /* stop the periodic callout */
16266     bxe_periodic_stop(sc);
16267
16268     BXE_CORE_LOCK(sc);
16269     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16270     BXE_CORE_UNLOCK(sc);
16271
16272     return (0);
16273 }
16274
16275 void
16276 bxe_igu_ack_sb(struct bxe_softc *sc,
16277                uint8_t          igu_sb_id,
16278                uint8_t          segment,
16279                uint16_t         index,
16280                uint8_t          op,
16281                uint8_t          update)
16282 {
16283     uint32_t igu_addr = sc->igu_base_addr;
16284     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16285     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16286 }
16287
16288 static void
16289 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16290                      uint8_t          func,
16291                      uint8_t          idu_sb_id,
16292                      uint8_t          is_pf)
16293 {
16294     uint32_t data, ctl, cnt = 100;
16295     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16296     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16297     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16298     uint32_t sb_bit =  1 << (idu_sb_id%32);
16299     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16300     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16301
16302     /* Not supported in BC mode */
16303     if (CHIP_INT_MODE_IS_BC(sc)) {
16304         return;
16305     }
16306
16307     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16308              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16309             IGU_REGULAR_CLEANUP_SET |
16310             IGU_REGULAR_BCLEANUP);
16311
16312     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16313            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16314            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16315
16316     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16317             data, igu_addr_data);
16318     REG_WR(sc, igu_addr_data, data);
16319
16320     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16321                       BUS_SPACE_BARRIER_WRITE);
16322     mb();
16323
16324     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16325             ctl, igu_addr_ctl);
16326     REG_WR(sc, igu_addr_ctl, ctl);
16327
16328     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16329                       BUS_SPACE_BARRIER_WRITE);
16330     mb();
16331
16332     /* wait for clean up to finish */
16333     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16334         DELAY(20000);
16335     }
16336
16337     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16338         BLOGD(sc, DBG_LOAD,
16339               "Unable to finish IGU cleanup: "
16340               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16341               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16342     }
16343 }
16344
16345 static void
16346 bxe_igu_clear_sb(struct bxe_softc *sc,
16347                  uint8_t          idu_sb_id)
16348 {
16349     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16350 }
16351
16352
16353
16354
16355
16356
16357
16358 /*******************/
16359 /* ECORE CALLBACKS */
16360 /*******************/
16361
16362 static void
16363 bxe_reset_common(struct bxe_softc *sc)
16364 {
16365     uint32_t val = 0x1400;
16366
16367     /* reset_common */
16368     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16369
16370     if (CHIP_IS_E3(sc)) {
16371         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16372         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16373     }
16374
16375     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16376 }
16377
16378 static void
16379 bxe_common_init_phy(struct bxe_softc *sc)
16380 {
16381     uint32_t shmem_base[2];
16382     uint32_t shmem2_base[2];
16383
16384     /* Avoid common init in case MFW supports LFA */
16385     if (SHMEM2_RD(sc, size) >
16386         (uint32_t)offsetof(struct shmem2_region,
16387                            lfa_host_addr[SC_PORT(sc)])) {
16388         return;
16389     }
16390
16391     shmem_base[0]  = sc->devinfo.shmem_base;
16392     shmem2_base[0] = sc->devinfo.shmem2_base;
16393
16394     if (!CHIP_IS_E1x(sc)) {
16395         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16396         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16397     }
16398
16399     bxe_acquire_phy_lock(sc);
16400     elink_common_init_phy(sc, shmem_base, shmem2_base,
16401                           sc->devinfo.chip_id, 0);
16402     bxe_release_phy_lock(sc);
16403 }
16404
16405 static void
16406 bxe_pf_disable(struct bxe_softc *sc)
16407 {
16408     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16409
16410     val &= ~IGU_PF_CONF_FUNC_EN;
16411
16412     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16413     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16414     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16415 }
16416
16417 static void
16418 bxe_init_pxp(struct bxe_softc *sc)
16419 {
16420     uint16_t devctl;
16421     int r_order, w_order;
16422
16423     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16424
16425     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16426
16427     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16428
16429     if (sc->mrrs == -1) {
16430         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16431     } else {
16432         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16433         r_order = sc->mrrs;
16434     }
16435
16436     ecore_init_pxp_arb(sc, r_order, w_order);
16437 }
16438
16439 static uint32_t
16440 bxe_get_pretend_reg(struct bxe_softc *sc)
16441 {
16442     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16443     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16444     return (base + (SC_ABS_FUNC(sc)) * stride);
16445 }
16446
16447 /*
16448  * Called only on E1H or E2.
16449  * When pretending to be PF, the pretend value is the function number 0..7.
16450  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16451  * combination.
16452  */
16453 static int
16454 bxe_pretend_func(struct bxe_softc *sc,
16455                  uint16_t         pretend_func_val)
16456 {
16457     uint32_t pretend_reg;
16458
16459     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16460         return (-1);
16461     }
16462
16463     /* get my own pretend register */
16464     pretend_reg = bxe_get_pretend_reg(sc);
16465     REG_WR(sc, pretend_reg, pretend_func_val);
16466     REG_RD(sc, pretend_reg);
16467     return (0);
16468 }
16469
16470 static void
16471 bxe_iov_init_dmae(struct bxe_softc *sc)
16472 {
16473     return;
16474 }
16475
16476 static void
16477 bxe_iov_init_dq(struct bxe_softc *sc)
16478 {
16479     return;
16480 }
16481
16482 /* send a NIG loopback debug packet */
16483 static void
16484 bxe_lb_pckt(struct bxe_softc *sc)
16485 {
16486     uint32_t wb_write[3];
16487
16488     /* Ethernet source and destination addresses */
16489     wb_write[0] = 0x55555555;
16490     wb_write[1] = 0x55555555;
16491     wb_write[2] = 0x20;     /* SOP */
16492     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16493
16494     /* NON-IP protocol */
16495     wb_write[0] = 0x09000000;
16496     wb_write[1] = 0x55555555;
16497     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16498     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16499 }
16500
16501 /*
16502  * Some of the internal memories are not directly readable from the driver.
16503  * To test them we send debug packets.
16504  */
16505 static int
16506 bxe_int_mem_test(struct bxe_softc *sc)
16507 {
16508     int factor;
16509     int count, i;
16510     uint32_t val = 0;
16511
16512     if (CHIP_REV_IS_FPGA(sc)) {
16513         factor = 120;
16514     } else if (CHIP_REV_IS_EMUL(sc)) {
16515         factor = 200;
16516     } else {
16517         factor = 1;
16518     }
16519
16520     /* disable inputs of parser neighbor blocks */
16521     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16522     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16523     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16524     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16525
16526     /*  write 0 to parser credits for CFC search request */
16527     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16528
16529     /* send Ethernet packet */
16530     bxe_lb_pckt(sc);
16531
16532     /* TODO do i reset NIG statistic? */
16533     /* Wait until NIG register shows 1 packet of size 0x10 */
16534     count = 1000 * factor;
16535     while (count) {
16536         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16537         val = *BXE_SP(sc, wb_data[0]);
16538         if (val == 0x10) {
16539             break;
16540         }
16541
16542         DELAY(10000);
16543         count--;
16544     }
16545
16546     if (val != 0x10) {
16547         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16548         return (-1);
16549     }
16550
16551     /* wait until PRS register shows 1 packet */
16552     count = (1000 * factor);
16553     while (count) {
16554         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16555         if (val == 1) {
16556             break;
16557         }
16558
16559         DELAY(10000);
16560         count--;
16561     }
16562
16563     if (val != 0x1) {
16564         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16565         return (-2);
16566     }
16567
16568     /* Reset and init BRB, PRS */
16569     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16570     DELAY(50000);
16571     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16572     DELAY(50000);
16573     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16574     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16575
16576     /* Disable inputs of parser neighbor blocks */
16577     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16578     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16579     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16580     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16581
16582     /* Write 0 to parser credits for CFC search request */
16583     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16584
16585     /* send 10 Ethernet packets */
16586     for (i = 0; i < 10; i++) {
16587         bxe_lb_pckt(sc);
16588     }
16589
16590     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16591     count = (1000 * factor);
16592     while (count) {
16593         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16594         val = *BXE_SP(sc, wb_data[0]);
16595         if (val == 0xb0) {
16596             break;
16597         }
16598
16599         DELAY(10000);
16600         count--;
16601     }
16602
16603     if (val != 0xb0) {
16604         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16605         return (-3);
16606     }
16607
16608     /* Wait until PRS register shows 2 packets */
16609     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16610     if (val != 2) {
16611         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16612     }
16613
16614     /* Write 1 to parser credits for CFC search request */
16615     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16616
16617     /* Wait until PRS register shows 3 packets */
16618     DELAY(10000 * factor);
16619
16620     /* Wait until NIG register shows 1 packet of size 0x10 */
16621     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16622     if (val != 3) {
16623         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16624     }
16625
16626     /* clear NIG EOP FIFO */
16627     for (i = 0; i < 11; i++) {
16628         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16629     }
16630
16631     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16632     if (val != 1) {
16633         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16634         return (-4);
16635     }
16636
16637     /* Reset and init BRB, PRS, NIG */
16638     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16639     DELAY(50000);
16640     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16641     DELAY(50000);
16642     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16643     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16644     if (!CNIC_SUPPORT(sc)) {
16645         /* set NIC mode */
16646         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16647     }
16648
16649     /* Enable inputs of parser neighbor blocks */
16650     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16651     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16652     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16653     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16654
16655     return (0);
16656 }
16657
16658 static void
16659 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16660 {
16661     int is_required;
16662     uint32_t val;
16663     int port;
16664
16665     is_required = 0;
16666     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16667            SHARED_HW_CFG_FAN_FAILURE_MASK);
16668
16669     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16670         is_required = 1;
16671     }
16672     /*
16673      * The fan failure mechanism is usually related to the PHY type since
16674      * the power consumption of the board is affected by the PHY. Currently,
16675      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16676      */
16677     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16678         for (port = PORT_0; port < PORT_MAX; port++) {
16679             is_required |= elink_fan_failure_det_req(sc,
16680                                                      sc->devinfo.shmem_base,
16681                                                      sc->devinfo.shmem2_base,
16682                                                      port);
16683         }
16684     }
16685
16686     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16687
16688     if (is_required == 0) {
16689         return;
16690     }
16691
16692     /* Fan failure is indicated by SPIO 5 */
16693     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16694
16695     /* set to active low mode */
16696     val = REG_RD(sc, MISC_REG_SPIO_INT);
16697     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16698     REG_WR(sc, MISC_REG_SPIO_INT, val);
16699
16700     /* enable interrupt to signal the IGU */
16701     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16702     val |= MISC_SPIO_SPIO5;
16703     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16704 }
16705
16706 static void
16707 bxe_enable_blocks_attention(struct bxe_softc *sc)
16708 {
16709     uint32_t val;
16710
16711     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16712     if (!CHIP_IS_E1x(sc)) {
16713         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16714     } else {
16715         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16716     }
16717     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16718     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16719     /*
16720      * mask read length error interrupts in brb for parser
16721      * (parsing unit and 'checksum and crc' unit)
16722      * these errors are legal (PU reads fixed length and CAC can cause
16723      * read length error on truncated packets)
16724      */
16725     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16726     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16727     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16728     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16729     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16730     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16731 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16732 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16733     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16734     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16735     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16736 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16737 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16738     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16739     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16740     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16741     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16742 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16743 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16744
16745     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16746            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16747            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16748     if (!CHIP_IS_E1x(sc)) {
16749         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16750                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16751     }
16752     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16753
16754     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16755     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16756     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16757 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16758
16759     if (!CHIP_IS_E1x(sc)) {
16760         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16761         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16762     }
16763
16764     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16765     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16766 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16767     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16768 }
16769
16770 /**
16771  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16772  *
16773  * @sc:     driver handle
16774  */
16775 static int
16776 bxe_init_hw_common(struct bxe_softc *sc)
16777 {
16778     uint8_t abs_func_id;
16779     uint32_t val;
16780
16781     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16782           SC_ABS_FUNC(sc));
16783
16784     /*
16785      * take the RESET lock to protect undi_unload flow from accessing
16786      * registers while we are resetting the chip
16787      */
16788     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16789
16790     bxe_reset_common(sc);
16791
16792     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16793
16794     val = 0xfffc;
16795     if (CHIP_IS_E3(sc)) {
16796         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16797         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16798     }
16799
16800     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16801
16802     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16803
16804     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16805     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16806
16807     if (!CHIP_IS_E1x(sc)) {
16808         /*
16809          * 4-port mode or 2-port mode we need to turn off master-enable for
16810          * everyone. After that we turn it back on for self. So, we disregard
16811          * multi-function, and always disable all functions on the given path,
16812          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16813          */
16814         for (abs_func_id = SC_PATH(sc);
16815              abs_func_id < (E2_FUNC_MAX * 2);
16816              abs_func_id += 2) {
16817             if (abs_func_id == SC_ABS_FUNC(sc)) {
16818                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16819                 continue;
16820             }
16821
16822             bxe_pretend_func(sc, abs_func_id);
16823
16824             /* clear pf enable */
16825             bxe_pf_disable(sc);
16826
16827             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16828         }
16829     }
16830
16831     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16832
16833     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16834
16835     if (CHIP_IS_E1(sc)) {
16836         /*
16837          * enable HW interrupt from PXP on USDM overflow
16838          * bit 16 on INT_MASK_0
16839          */
16840         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16841     }
16842
16843     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16844     bxe_init_pxp(sc);
16845
16846 #ifdef __BIG_ENDIAN
16847     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16848     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16849     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16850     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16851     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16852     /* make sure this value is 0 */
16853     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16854
16855     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16856     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16857     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16858     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16859     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16860 #endif
16861
16862     ecore_ilt_init_page_size(sc, INITOP_SET);
16863
16864     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16865         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16866     }
16867
16868     /* let the HW do it's magic... */
16869     DELAY(100000);
16870
16871     /* finish PXP init */
16872     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16873     if (val != 1) {
16874         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16875             val);
16876         return (-1);
16877     }
16878     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16879     if (val != 1) {
16880         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16881         return (-1);
16882     }
16883
16884     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16885
16886     /*
16887      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16888      * entries with value "0" and valid bit on. This needs to be done by the
16889      * first PF that is loaded in a path (i.e. common phase)
16890      */
16891     if (!CHIP_IS_E1x(sc)) {
16892 /*
16893  * In E2 there is a bug in the timers block that can cause function 6 / 7
16894  * (i.e. vnic3) to start even if it is marked as "scan-off".
16895  * This occurs when a different function (func2,3) is being marked
16896  * as "scan-off". Real-life scenario for example: if a driver is being
16897  * load-unloaded while func6,7 are down. This will cause the timer to access
16898  * the ilt, translate to a logical address and send a request to read/write.
16899  * Since the ilt for the function that is down is not valid, this will cause
16900  * a translation error which is unrecoverable.
16901  * The Workaround is intended to make sure that when this happens nothing
16902  * fatal will occur. The workaround:
16903  *  1.  First PF driver which loads on a path will:
16904  *      a.  After taking the chip out of reset, by using pretend,
16905  *          it will write "0" to the following registers of
16906  *          the other vnics.
16907  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16908  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16909  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16910  *          And for itself it will write '1' to
16911  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16912  *          dmae-operations (writing to pram for example.)
16913  *          note: can be done for only function 6,7 but cleaner this
16914  *            way.
16915  *      b.  Write zero+valid to the entire ILT.
16916  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16917  *          VNIC3 (of that port). The range allocated will be the
16918  *          entire ILT. This is needed to prevent  ILT range error.
16919  *  2.  Any PF driver load flow:
16920  *      a.  ILT update with the physical addresses of the allocated
16921  *          logical pages.
16922  *      b.  Wait 20msec. - note that this timeout is needed to make
16923  *          sure there are no requests in one of the PXP internal
16924  *          queues with "old" ILT addresses.
16925  *      c.  PF enable in the PGLC.
16926  *      d.  Clear the was_error of the PF in the PGLC. (could have
16927  *          occurred while driver was down)
16928  *      e.  PF enable in the CFC (WEAK + STRONG)
16929  *      f.  Timers scan enable
16930  *  3.  PF driver unload flow:
16931  *      a.  Clear the Timers scan_en.
16932  *      b.  Polling for scan_on=0 for that PF.
16933  *      c.  Clear the PF enable bit in the PXP.
16934  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16935  *      e.  Write zero+valid to all ILT entries (The valid bit must
16936  *          stay set)
16937  *      f.  If this is VNIC 3 of a port then also init
16938  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16939  *          to the last enrty in the ILT.
16940  *
16941  *      Notes:
16942  *      Currently the PF error in the PGLC is non recoverable.
16943  *      In the future the there will be a recovery routine for this error.
16944  *      Currently attention is masked.
16945  *      Having an MCP lock on the load/unload process does not guarantee that
16946  *      there is no Timer disable during Func6/7 enable. This is because the
16947  *      Timers scan is currently being cleared by the MCP on FLR.
16948  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16949  *      there is error before clearing it. But the flow above is simpler and
16950  *      more general.
16951  *      All ILT entries are written by zero+valid and not just PF6/7
16952  *      ILT entries since in the future the ILT entries allocation for
16953  *      PF-s might be dynamic.
16954  */
16955         struct ilt_client_info ilt_cli;
16956         struct ecore_ilt ilt;
16957
16958         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16959         memset(&ilt, 0, sizeof(struct ecore_ilt));
16960
16961         /* initialize dummy TM client */
16962         ilt_cli.start      = 0;
16963         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16964         ilt_cli.client_num = ILT_CLIENT_TM;
16965
16966         /*
16967          * Step 1: set zeroes to all ilt page entries with valid bit on
16968          * Step 2: set the timers first/last ilt entry to point
16969          * to the entire range to prevent ILT range error for 3rd/4th
16970          * vnic (this code assumes existence of the vnic)
16971          *
16972          * both steps performed by call to ecore_ilt_client_init_op()
16973          * with dummy TM client
16974          *
16975          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16976          * and his brother are split registers
16977          */
16978
16979         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16980         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16981         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16982
16983         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16984         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16985         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16986     }
16987
16988     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16989     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16990
16991     if (!CHIP_IS_E1x(sc)) {
16992         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16993                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16994
16995         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16996         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16997
16998         /* let the HW do it's magic... */
16999         do {
17000             DELAY(200000);
17001             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
17002         } while (factor-- && (val != 1));
17003
17004         if (val != 1) {
17005             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
17006             return (-1);
17007         }
17008     }
17009
17010     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
17011
17012     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
17013
17014     bxe_iov_init_dmae(sc);
17015
17016     /* clean the DMAE memory */
17017     sc->dmae_ready = 1;
17018     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
17019
17020     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
17021
17022     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
17023
17024     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
17025
17026     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
17027
17028     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
17029     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
17030     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
17031     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
17032
17033     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
17034
17035     /* QM queues pointers table */
17036     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
17037
17038     /* soft reset pulse */
17039     REG_WR(sc, QM_REG_SOFT_RESET, 1);
17040     REG_WR(sc, QM_REG_SOFT_RESET, 0);
17041
17042     if (CNIC_SUPPORT(sc))
17043         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
17044
17045     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
17046     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
17047     if (!CHIP_REV_IS_SLOW(sc)) {
17048         /* enable hw interrupt from doorbell Q */
17049         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
17050     }
17051
17052     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
17053
17054     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
17055     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
17056
17057     if (!CHIP_IS_E1(sc)) {
17058         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
17059     }
17060
17061     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
17062         if (IS_MF_AFEX(sc)) {
17063             /*
17064              * configure that AFEX and VLAN headers must be
17065              * received in AFEX mode
17066              */
17067             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
17068             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
17069             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
17070             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
17071             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
17072         } else {
17073             /*
17074              * Bit-map indicating which L2 hdrs may appear
17075              * after the basic Ethernet header
17076              */
17077             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
17078                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17079         }
17080     }
17081
17082     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
17083     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
17084     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
17085     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
17086
17087     if (!CHIP_IS_E1x(sc)) {
17088         /* reset VFC memories */
17089         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17090                VFC_MEMORIES_RST_REG_CAM_RST |
17091                VFC_MEMORIES_RST_REG_RAM_RST);
17092         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
17093                VFC_MEMORIES_RST_REG_CAM_RST |
17094                VFC_MEMORIES_RST_REG_RAM_RST);
17095
17096         DELAY(20000);
17097     }
17098
17099     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
17100     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
17101     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
17102     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
17103
17104     /* sync semi rtc */
17105     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
17106            0x80000000);
17107     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
17108            0x80000000);
17109
17110     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
17111     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
17112     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
17113
17114     if (!CHIP_IS_E1x(sc)) {
17115         if (IS_MF_AFEX(sc)) {
17116             /*
17117              * configure that AFEX and VLAN headers must be
17118              * sent in AFEX mode
17119              */
17120             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
17121             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
17122             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
17123             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
17124             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
17125         } else {
17126             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
17127                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
17128         }
17129     }
17130
17131     REG_WR(sc, SRC_REG_SOFT_RST, 1);
17132
17133     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
17134
17135     if (CNIC_SUPPORT(sc)) {
17136         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
17137         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
17138         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
17139         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
17140         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
17141         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
17142         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
17143         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17144         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17145         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17146     }
17147     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17148
17149     if (sizeof(union cdu_context) != 1024) {
17150         /* we currently assume that a context is 1024 bytes */
17151         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17152               (long)sizeof(union cdu_context));
17153     }
17154
17155     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17156     val = (4 << 24) + (0 << 12) + 1024;
17157     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17158
17159     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17160
17161     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17162     /* enable context validation interrupt from CFC */
17163     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17164
17165     /* set the thresholds to prevent CFC/CDU race */
17166     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17167     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17168
17169     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17170         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17171     }
17172
17173     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17174     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17175
17176     /* Reset PCIE errors for debug */
17177     REG_WR(sc, 0x2814, 0xffffffff);
17178     REG_WR(sc, 0x3820, 0xffffffff);
17179
17180     if (!CHIP_IS_E1x(sc)) {
17181         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17182                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17183                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17184         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17185                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17186                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17187                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17188         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17189                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17190                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17191                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17192     }
17193
17194     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17195
17196     if (!CHIP_IS_E1(sc)) {
17197         /* in E3 this done in per-port section */
17198         if (!CHIP_IS_E3(sc))
17199             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17200     }
17201
17202     if (CHIP_IS_E1H(sc)) {
17203         /* not applicable for E2 (and above ...) */
17204         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17205     }
17206
17207     if (CHIP_REV_IS_SLOW(sc)) {
17208         DELAY(200000);
17209     }
17210
17211     /* finish CFC init */
17212     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17213     if (val != 1) {
17214         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17215         return (-1);
17216     }
17217     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17218     if (val != 1) {
17219         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17220         return (-1);
17221     }
17222     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17223     if (val != 1) {
17224         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17225         return (-1);
17226     }
17227     REG_WR(sc, CFC_REG_DEBUG0, 0);
17228
17229     if (CHIP_IS_E1(sc)) {
17230         /* read NIG statistic to see if this is our first up since powerup */
17231         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17232         val = *BXE_SP(sc, wb_data[0]);
17233
17234         /* do internal memory self test */
17235         if ((val == 0) && bxe_int_mem_test(sc)) {
17236             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17237             return (-1);
17238         }
17239     }
17240
17241     bxe_setup_fan_failure_detection(sc);
17242
17243     /* clear PXP2 attentions */
17244     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17245
17246     bxe_enable_blocks_attention(sc);
17247
17248     if (!CHIP_REV_IS_SLOW(sc)) {
17249         ecore_enable_blocks_parity(sc);
17250     }
17251
17252     if (!BXE_NOMCP(sc)) {
17253         if (CHIP_IS_E1x(sc)) {
17254             bxe_common_init_phy(sc);
17255         }
17256     }
17257
17258     return (0);
17259 }
17260
17261 /**
17262  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17263  *
17264  * @sc:     driver handle
17265  */
17266 static int
17267 bxe_init_hw_common_chip(struct bxe_softc *sc)
17268 {
17269     int rc = bxe_init_hw_common(sc);
17270
17271     if (rc) {
17272         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17273         return (rc);
17274     }
17275
17276     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17277     if (!BXE_NOMCP(sc)) {
17278         bxe_common_init_phy(sc);
17279     }
17280
17281     return (0);
17282 }
17283
17284 static int
17285 bxe_init_hw_port(struct bxe_softc *sc)
17286 {
17287     int port = SC_PORT(sc);
17288     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17289     uint32_t low, high;
17290     uint32_t val;
17291
17292     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17293
17294     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17295
17296     ecore_init_block(sc, BLOCK_MISC, init_phase);
17297     ecore_init_block(sc, BLOCK_PXP, init_phase);
17298     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17299
17300     /*
17301      * Timers bug workaround: disables the pf_master bit in pglue at
17302      * common phase, we need to enable it here before any dmae access are
17303      * attempted. Therefore we manually added the enable-master to the
17304      * port phase (it also happens in the function phase)
17305      */
17306     if (!CHIP_IS_E1x(sc)) {
17307         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17308     }
17309
17310     ecore_init_block(sc, BLOCK_ATC, init_phase);
17311     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17312     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17313     ecore_init_block(sc, BLOCK_QM, init_phase);
17314
17315     ecore_init_block(sc, BLOCK_TCM, init_phase);
17316     ecore_init_block(sc, BLOCK_UCM, init_phase);
17317     ecore_init_block(sc, BLOCK_CCM, init_phase);
17318     ecore_init_block(sc, BLOCK_XCM, init_phase);
17319
17320     /* QM cid (connection) count */
17321     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17322
17323     if (CNIC_SUPPORT(sc)) {
17324         ecore_init_block(sc, BLOCK_TM, init_phase);
17325         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17326         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17327     }
17328
17329     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17330
17331     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17332
17333     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17334         if (IS_MF(sc)) {
17335             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17336         } else if (sc->mtu > 4096) {
17337             if (BXE_ONE_PORT(sc)) {
17338                 low = 160;
17339             } else {
17340                 val = sc->mtu;
17341                 /* (24*1024 + val*4)/256 */
17342                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17343             }
17344         } else {
17345             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17346         }
17347         high = (low + 56); /* 14*1024/256 */
17348         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17349         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17350     }
17351
17352     if (CHIP_IS_MODE_4_PORT(sc)) {
17353         REG_WR(sc, SC_PORT(sc) ?
17354                BRB1_REG_MAC_GUARANTIED_1 :
17355                BRB1_REG_MAC_GUARANTIED_0, 40);
17356     }
17357
17358     ecore_init_block(sc, BLOCK_PRS, init_phase);
17359     if (CHIP_IS_E3B0(sc)) {
17360         if (IS_MF_AFEX(sc)) {
17361             /* configure headers for AFEX mode */
17362             REG_WR(sc, SC_PORT(sc) ?
17363                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17364                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17365             REG_WR(sc, SC_PORT(sc) ?
17366                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17367                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17368             REG_WR(sc, SC_PORT(sc) ?
17369                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17370                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17371         } else {
17372             /* Ovlan exists only if we are in multi-function +
17373              * switch-dependent mode, in switch-independent there
17374              * is no ovlan headers
17375              */
17376             REG_WR(sc, SC_PORT(sc) ?
17377                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17378                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17379                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17380         }
17381     }
17382
17383     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17384     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17385     ecore_init_block(sc, BLOCK_USDM, init_phase);
17386     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17387
17388     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17389     ecore_init_block(sc, BLOCK_USEM, init_phase);
17390     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17391     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17392
17393     ecore_init_block(sc, BLOCK_UPB, init_phase);
17394     ecore_init_block(sc, BLOCK_XPB, init_phase);
17395
17396     ecore_init_block(sc, BLOCK_PBF, init_phase);
17397
17398     if (CHIP_IS_E1x(sc)) {
17399         /* configure PBF to work without PAUSE mtu 9000 */
17400         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17401
17402         /* update threshold */
17403         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17404         /* update init credit */
17405         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17406
17407         /* probe changes */
17408         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17409         DELAY(50);
17410         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17411     }
17412
17413     if (CNIC_SUPPORT(sc)) {
17414         ecore_init_block(sc, BLOCK_SRC, init_phase);
17415     }
17416
17417     ecore_init_block(sc, BLOCK_CDU, init_phase);
17418     ecore_init_block(sc, BLOCK_CFC, init_phase);
17419
17420     if (CHIP_IS_E1(sc)) {
17421         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17422         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17423     }
17424     ecore_init_block(sc, BLOCK_HC, init_phase);
17425
17426     ecore_init_block(sc, BLOCK_IGU, init_phase);
17427
17428     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17429     /* init aeu_mask_attn_func_0/1:
17430      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17431      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17432      *             bits 4-7 are used for "per vn group attention" */
17433     val = IS_MF(sc) ? 0xF7 : 0x7;
17434     /* Enable DCBX attention for all but E1 */
17435     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17436     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17437
17438     ecore_init_block(sc, BLOCK_NIG, init_phase);
17439
17440     if (!CHIP_IS_E1x(sc)) {
17441         /* Bit-map indicating which L2 hdrs may appear after the
17442          * basic Ethernet header
17443          */
17444         if (IS_MF_AFEX(sc)) {
17445             REG_WR(sc, SC_PORT(sc) ?
17446                    NIG_REG_P1_HDRS_AFTER_BASIC :
17447                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17448         } else {
17449             REG_WR(sc, SC_PORT(sc) ?
17450                    NIG_REG_P1_HDRS_AFTER_BASIC :
17451                    NIG_REG_P0_HDRS_AFTER_BASIC,
17452                    IS_MF_SD(sc) ? 7 : 6);
17453         }
17454
17455         if (CHIP_IS_E3(sc)) {
17456             REG_WR(sc, SC_PORT(sc) ?
17457                    NIG_REG_LLH1_MF_MODE :
17458                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17459         }
17460     }
17461     if (!CHIP_IS_E3(sc)) {
17462         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17463     }
17464
17465     if (!CHIP_IS_E1(sc)) {
17466         /* 0x2 disable mf_ov, 0x1 enable */
17467         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17468                (IS_MF_SD(sc) ? 0x1 : 0x2));
17469
17470         if (!CHIP_IS_E1x(sc)) {
17471             val = 0;
17472             switch (sc->devinfo.mf_info.mf_mode) {
17473             case MULTI_FUNCTION_SD:
17474                 val = 1;
17475                 break;
17476             case MULTI_FUNCTION_SI:
17477             case MULTI_FUNCTION_AFEX:
17478                 val = 2;
17479                 break;
17480             }
17481
17482             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17483                         NIG_REG_LLH0_CLS_TYPE), val);
17484         }
17485         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17486         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17487         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17488     }
17489
17490     /* If SPIO5 is set to generate interrupts, enable it for this port */
17491     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17492     if (val & MISC_SPIO_SPIO5) {
17493         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17494                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17495         val = REG_RD(sc, reg_addr);
17496         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17497         REG_WR(sc, reg_addr, val);
17498     }
17499
17500     return (0);
17501 }
17502
17503 static uint32_t
17504 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17505                        uint32_t         reg,
17506                        uint32_t         expected,
17507                        uint32_t         poll_count)
17508 {
17509     uint32_t cur_cnt = poll_count;
17510     uint32_t val;
17511
17512     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17513         DELAY(FLR_WAIT_INTERVAL);
17514     }
17515
17516     return (val);
17517 }
17518
17519 static int
17520 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17521                               uint32_t         reg,
17522                               char             *msg,
17523                               uint32_t         poll_cnt)
17524 {
17525     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17526
17527     if (val != 0) {
17528         BLOGE(sc, "%s usage count=%d\n", msg, val);
17529         return (1);
17530     }
17531
17532     return (0);
17533 }
17534
17535 /* Common routines with VF FLR cleanup */
17536 static uint32_t
17537 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17538 {
17539     /* adjust polling timeout */
17540     if (CHIP_REV_IS_EMUL(sc)) {
17541         return (FLR_POLL_CNT * 2000);
17542     }
17543
17544     if (CHIP_REV_IS_FPGA(sc)) {
17545         return (FLR_POLL_CNT * 120);
17546     }
17547
17548     return (FLR_POLL_CNT);
17549 }
17550
17551 static int
17552 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17553                            uint32_t         poll_cnt)
17554 {
17555     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17556     if (bxe_flr_clnup_poll_hw_counter(sc,
17557                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17558                                       "CFC PF usage counter timed out",
17559                                       poll_cnt)) {
17560         return (1);
17561     }
17562
17563     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17564     if (bxe_flr_clnup_poll_hw_counter(sc,
17565                                       DORQ_REG_PF_USAGE_CNT,
17566                                       "DQ PF usage counter timed out",
17567                                       poll_cnt)) {
17568         return (1);
17569     }
17570
17571     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17572     if (bxe_flr_clnup_poll_hw_counter(sc,
17573                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17574                                       "QM PF usage counter timed out",
17575                                       poll_cnt)) {
17576         return (1);
17577     }
17578
17579     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17580     if (bxe_flr_clnup_poll_hw_counter(sc,
17581                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17582                                       "Timers VNIC usage counter timed out",
17583                                       poll_cnt)) {
17584         return (1);
17585     }
17586
17587     if (bxe_flr_clnup_poll_hw_counter(sc,
17588                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17589                                       "Timers NUM_SCANS usage counter timed out",
17590                                       poll_cnt)) {
17591         return (1);
17592     }
17593
17594     /* Wait DMAE PF usage counter to zero */
17595     if (bxe_flr_clnup_poll_hw_counter(sc,
17596                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17597                                       "DMAE dommand register timed out",
17598                                       poll_cnt)) {
17599         return (1);
17600     }
17601
17602     return (0);
17603 }
17604
17605 #define OP_GEN_PARAM(param)                                            \
17606     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17607 #define OP_GEN_TYPE(type)                                           \
17608     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17609 #define OP_GEN_AGG_VECT(index)                                             \
17610     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17611
17612 static int
17613 bxe_send_final_clnup(struct bxe_softc *sc,
17614                      uint8_t          clnup_func,
17615                      uint32_t         poll_cnt)
17616 {
17617     uint32_t op_gen_command = 0;
17618     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17619                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17620     int ret = 0;
17621
17622     if (REG_RD(sc, comp_addr)) {
17623         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17624         return (1);
17625     }
17626
17627     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17628     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17629     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17630     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17631
17632     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17633     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17634
17635     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17636         BLOGE(sc, "FW final cleanup did not succeed\n");
17637         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17638               (REG_RD(sc, comp_addr)));
17639         bxe_panic(sc, ("FLR cleanup failed\n"));
17640         return (1);
17641     }
17642
17643     /* Zero completion for nxt FLR */
17644     REG_WR(sc, comp_addr, 0);
17645
17646     return (ret);
17647 }
17648
17649 static void
17650 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17651                        struct pbf_pN_buf_regs *regs,
17652                        uint32_t               poll_count)
17653 {
17654     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17655     uint32_t cur_cnt = poll_count;
17656
17657     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17658     crd = crd_start = REG_RD(sc, regs->crd);
17659     init_crd = REG_RD(sc, regs->init_crd);
17660
17661     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17662     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17663     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17664
17665     while ((crd != init_crd) &&
17666            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17667             (init_crd - crd_start))) {
17668         if (cur_cnt--) {
17669             DELAY(FLR_WAIT_INTERVAL);
17670             crd = REG_RD(sc, regs->crd);
17671             crd_freed = REG_RD(sc, regs->crd_freed);
17672         } else {
17673             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17674             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17675             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17676             break;
17677         }
17678     }
17679
17680     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17681           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17682 }
17683
17684 static void
17685 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17686                        struct pbf_pN_cmd_regs *regs,
17687                        uint32_t               poll_count)
17688 {
17689     uint32_t occup, to_free, freed, freed_start;
17690     uint32_t cur_cnt = poll_count;
17691
17692     occup = to_free = REG_RD(sc, regs->lines_occup);
17693     freed = freed_start = REG_RD(sc, regs->lines_freed);
17694
17695     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17696     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17697
17698     while (occup &&
17699            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17700         if (cur_cnt--) {
17701             DELAY(FLR_WAIT_INTERVAL);
17702             occup = REG_RD(sc, regs->lines_occup);
17703             freed = REG_RD(sc, regs->lines_freed);
17704         } else {
17705             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17706             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17707             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17708             break;
17709         }
17710     }
17711
17712     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17713           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17714 }
17715
17716 static void
17717 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17718 {
17719     struct pbf_pN_cmd_regs cmd_regs[] = {
17720         {0, (CHIP_IS_E3B0(sc)) ?
17721             PBF_REG_TQ_OCCUPANCY_Q0 :
17722             PBF_REG_P0_TQ_OCCUPANCY,
17723             (CHIP_IS_E3B0(sc)) ?
17724             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17725             PBF_REG_P0_TQ_LINES_FREED_CNT},
17726         {1, (CHIP_IS_E3B0(sc)) ?
17727             PBF_REG_TQ_OCCUPANCY_Q1 :
17728             PBF_REG_P1_TQ_OCCUPANCY,
17729             (CHIP_IS_E3B0(sc)) ?
17730             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17731             PBF_REG_P1_TQ_LINES_FREED_CNT},
17732         {4, (CHIP_IS_E3B0(sc)) ?
17733             PBF_REG_TQ_OCCUPANCY_LB_Q :
17734             PBF_REG_P4_TQ_OCCUPANCY,
17735             (CHIP_IS_E3B0(sc)) ?
17736             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17737             PBF_REG_P4_TQ_LINES_FREED_CNT}
17738     };
17739
17740     struct pbf_pN_buf_regs buf_regs[] = {
17741         {0, (CHIP_IS_E3B0(sc)) ?
17742             PBF_REG_INIT_CRD_Q0 :
17743             PBF_REG_P0_INIT_CRD ,
17744             (CHIP_IS_E3B0(sc)) ?
17745             PBF_REG_CREDIT_Q0 :
17746             PBF_REG_P0_CREDIT,
17747             (CHIP_IS_E3B0(sc)) ?
17748             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17749             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17750         {1, (CHIP_IS_E3B0(sc)) ?
17751             PBF_REG_INIT_CRD_Q1 :
17752             PBF_REG_P1_INIT_CRD,
17753             (CHIP_IS_E3B0(sc)) ?
17754             PBF_REG_CREDIT_Q1 :
17755             PBF_REG_P1_CREDIT,
17756             (CHIP_IS_E3B0(sc)) ?
17757             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17758             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17759         {4, (CHIP_IS_E3B0(sc)) ?
17760             PBF_REG_INIT_CRD_LB_Q :
17761             PBF_REG_P4_INIT_CRD,
17762             (CHIP_IS_E3B0(sc)) ?
17763             PBF_REG_CREDIT_LB_Q :
17764             PBF_REG_P4_CREDIT,
17765             (CHIP_IS_E3B0(sc)) ?
17766             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17767             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17768     };
17769
17770     int i;
17771
17772     /* Verify the command queues are flushed P0, P1, P4 */
17773     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17774         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17775     }
17776
17777     /* Verify the transmission buffers are flushed P0, P1, P4 */
17778     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17779         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17780     }
17781 }
17782
17783 static void
17784 bxe_hw_enable_status(struct bxe_softc *sc)
17785 {
17786     uint32_t val;
17787
17788     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17789     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17790
17791     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17792     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17793
17794     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17795     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17796
17797     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17798     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17799
17800     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17801     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17802
17803     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17804     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17805
17806     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17807     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17808
17809     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17810     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17811 }
17812
17813 static int
17814 bxe_pf_flr_clnup(struct bxe_softc *sc)
17815 {
17816     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17817
17818     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17819
17820     /* Re-enable PF target read access */
17821     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17822
17823     /* Poll HW usage counters */
17824     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17825     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17826         return (-1);
17827     }
17828
17829     /* Zero the igu 'trailing edge' and 'leading edge' */
17830
17831     /* Send the FW cleanup command */
17832     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17833         return (-1);
17834     }
17835
17836     /* ATC cleanup */
17837
17838     /* Verify TX hw is flushed */
17839     bxe_tx_hw_flushed(sc, poll_cnt);
17840
17841     /* Wait 100ms (not adjusted according to platform) */
17842     DELAY(100000);
17843
17844     /* Verify no pending pci transactions */
17845     if (bxe_is_pcie_pending(sc)) {
17846         BLOGE(sc, "PCIE Transactions still pending\n");
17847     }
17848
17849     /* Debug */
17850     bxe_hw_enable_status(sc);
17851
17852     /*
17853      * Master enable - Due to WB DMAE writes performed before this
17854      * register is re-initialized as part of the regular function init
17855      */
17856     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17857
17858     return (0);
17859 }
17860
17861 static int
17862 bxe_init_hw_func(struct bxe_softc *sc)
17863 {
17864     int port = SC_PORT(sc);
17865     int func = SC_FUNC(sc);
17866     int init_phase = PHASE_PF0 + func;
17867     struct ecore_ilt *ilt = sc->ilt;
17868     uint16_t cdu_ilt_start;
17869     uint32_t addr, val;
17870     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17871     int i, main_mem_width, rc;
17872
17873     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17874
17875     /* FLR cleanup */
17876     if (!CHIP_IS_E1x(sc)) {
17877         rc = bxe_pf_flr_clnup(sc);
17878         if (rc) {
17879             BLOGE(sc, "FLR cleanup failed!\n");
17880             // XXX bxe_fw_dump(sc);
17881             // XXX bxe_idle_chk(sc);
17882             return (rc);
17883         }
17884     }
17885
17886     /* set MSI reconfigure capability */
17887     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17888         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17889         val = REG_RD(sc, addr);
17890         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17891         REG_WR(sc, addr, val);
17892     }
17893
17894     ecore_init_block(sc, BLOCK_PXP, init_phase);
17895     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17896
17897     ilt = sc->ilt;
17898     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17899
17900     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17901         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17902         ilt->lines[cdu_ilt_start + i].page_mapping =
17903             sc->context[i].vcxt_dma.paddr;
17904         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17905     }
17906     ecore_ilt_init_op(sc, INITOP_SET);
17907
17908     /* Set NIC mode */
17909     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17910     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17911
17912     if (!CHIP_IS_E1x(sc)) {
17913         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17914
17915         /* Turn on a single ISR mode in IGU if driver is going to use
17916          * INT#x or MSI
17917          */
17918         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17919             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17920         }
17921
17922         /*
17923          * Timers workaround bug: function init part.
17924          * Need to wait 20msec after initializing ILT,
17925          * needed to make sure there are no requests in
17926          * one of the PXP internal queues with "old" ILT addresses
17927          */
17928         DELAY(20000);
17929
17930         /*
17931          * Master enable - Due to WB DMAE writes performed before this
17932          * register is re-initialized as part of the regular function
17933          * init
17934          */
17935         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17936         /* Enable the function in IGU */
17937         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17938     }
17939
17940     sc->dmae_ready = 1;
17941
17942     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17943
17944     if (!CHIP_IS_E1x(sc))
17945         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17946
17947     ecore_init_block(sc, BLOCK_ATC, init_phase);
17948     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17949     ecore_init_block(sc, BLOCK_NIG, init_phase);
17950     ecore_init_block(sc, BLOCK_SRC, init_phase);
17951     ecore_init_block(sc, BLOCK_MISC, init_phase);
17952     ecore_init_block(sc, BLOCK_TCM, init_phase);
17953     ecore_init_block(sc, BLOCK_UCM, init_phase);
17954     ecore_init_block(sc, BLOCK_CCM, init_phase);
17955     ecore_init_block(sc, BLOCK_XCM, init_phase);
17956     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17957     ecore_init_block(sc, BLOCK_USEM, init_phase);
17958     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17959     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17960
17961     if (!CHIP_IS_E1x(sc))
17962         REG_WR(sc, QM_REG_PF_EN, 1);
17963
17964     if (!CHIP_IS_E1x(sc)) {
17965         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17966         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17967         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17968         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17969     }
17970     ecore_init_block(sc, BLOCK_QM, init_phase);
17971
17972     ecore_init_block(sc, BLOCK_TM, init_phase);
17973     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17974
17975     bxe_iov_init_dq(sc);
17976
17977     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17978     ecore_init_block(sc, BLOCK_PRS, init_phase);
17979     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17980     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17981     ecore_init_block(sc, BLOCK_USDM, init_phase);
17982     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17983     ecore_init_block(sc, BLOCK_UPB, init_phase);
17984     ecore_init_block(sc, BLOCK_XPB, init_phase);
17985     ecore_init_block(sc, BLOCK_PBF, init_phase);
17986     if (!CHIP_IS_E1x(sc))
17987         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17988
17989     ecore_init_block(sc, BLOCK_CDU, init_phase);
17990
17991     ecore_init_block(sc, BLOCK_CFC, init_phase);
17992
17993     if (!CHIP_IS_E1x(sc))
17994         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17995
17996     if (IS_MF(sc)) {
17997         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17998         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17999     }
18000
18001     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
18002
18003     /* HC init per function */
18004     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18005         if (CHIP_IS_E1H(sc)) {
18006             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18007
18008             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18009             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18010         }
18011         ecore_init_block(sc, BLOCK_HC, init_phase);
18012
18013     } else {
18014         int num_segs, sb_idx, prod_offset;
18015
18016         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
18017
18018         if (!CHIP_IS_E1x(sc)) {
18019             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18020             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18021         }
18022
18023         ecore_init_block(sc, BLOCK_IGU, init_phase);
18024
18025         if (!CHIP_IS_E1x(sc)) {
18026             int dsb_idx = 0;
18027             /**
18028              * Producer memory:
18029              * E2 mode: address 0-135 match to the mapping memory;
18030              * 136 - PF0 default prod; 137 - PF1 default prod;
18031              * 138 - PF2 default prod; 139 - PF3 default prod;
18032              * 140 - PF0 attn prod;    141 - PF1 attn prod;
18033              * 142 - PF2 attn prod;    143 - PF3 attn prod;
18034              * 144-147 reserved.
18035              *
18036              * E1.5 mode - In backward compatible mode;
18037              * for non default SB; each even line in the memory
18038              * holds the U producer and each odd line hold
18039              * the C producer. The first 128 producers are for
18040              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
18041              * producers are for the DSB for each PF.
18042              * Each PF has five segments: (the order inside each
18043              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
18044              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
18045              * 144-147 attn prods;
18046              */
18047             /* non-default-status-blocks */
18048             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18049                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
18050             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
18051                 prod_offset = (sc->igu_base_sb + sb_idx) *
18052                     num_segs;
18053
18054                 for (i = 0; i < num_segs; i++) {
18055                     addr = IGU_REG_PROD_CONS_MEMORY +
18056                             (prod_offset + i) * 4;
18057                     REG_WR(sc, addr, 0);
18058                 }
18059                 /* send consumer update with value 0 */
18060                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
18061                            USTORM_ID, 0, IGU_INT_NOP, 1);
18062                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
18063             }
18064
18065             /* default-status-blocks */
18066             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
18067                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
18068
18069             if (CHIP_IS_MODE_4_PORT(sc))
18070                 dsb_idx = SC_FUNC(sc);
18071             else
18072                 dsb_idx = SC_VN(sc);
18073
18074             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
18075                        IGU_BC_BASE_DSB_PROD + dsb_idx :
18076                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
18077
18078             /*
18079              * igu prods come in chunks of E1HVN_MAX (4) -
18080              * does not matters what is the current chip mode
18081              */
18082             for (i = 0; i < (num_segs * E1HVN_MAX);
18083                  i += E1HVN_MAX) {
18084                 addr = IGU_REG_PROD_CONS_MEMORY +
18085                             (prod_offset + i)*4;
18086                 REG_WR(sc, addr, 0);
18087             }
18088             /* send consumer update with 0 */
18089             if (CHIP_INT_MODE_IS_BC(sc)) {
18090                 bxe_ack_sb(sc, sc->igu_dsb_id,
18091                            USTORM_ID, 0, IGU_INT_NOP, 1);
18092                 bxe_ack_sb(sc, sc->igu_dsb_id,
18093                            CSTORM_ID, 0, IGU_INT_NOP, 1);
18094                 bxe_ack_sb(sc, sc->igu_dsb_id,
18095                            XSTORM_ID, 0, IGU_INT_NOP, 1);
18096                 bxe_ack_sb(sc, sc->igu_dsb_id,
18097                            TSTORM_ID, 0, IGU_INT_NOP, 1);
18098                 bxe_ack_sb(sc, sc->igu_dsb_id,
18099                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18100             } else {
18101                 bxe_ack_sb(sc, sc->igu_dsb_id,
18102                            USTORM_ID, 0, IGU_INT_NOP, 1);
18103                 bxe_ack_sb(sc, sc->igu_dsb_id,
18104                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
18105             }
18106             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
18107
18108             /* !!! these should become driver const once
18109                rf-tool supports split-68 const */
18110             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
18111             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
18112             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
18113             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
18114             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
18115             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
18116         }
18117     }
18118
18119     /* Reset PCIE errors for debug */
18120     REG_WR(sc, 0x2114, 0xffffffff);
18121     REG_WR(sc, 0x2120, 0xffffffff);
18122
18123     if (CHIP_IS_E1x(sc)) {
18124         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
18125         main_mem_base = HC_REG_MAIN_MEMORY +
18126                 SC_PORT(sc) * (main_mem_size * 4);
18127         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
18128         main_mem_width = 8;
18129
18130         val = REG_RD(sc, main_mem_prty_clr);
18131         if (val) {
18132             BLOGD(sc, DBG_LOAD,
18133                   "Parity errors in HC block during function init (0x%x)!\n",
18134                   val);
18135         }
18136
18137         /* Clear "false" parity errors in MSI-X table */
18138         for (i = main_mem_base;
18139              i < main_mem_base + main_mem_size * 4;
18140              i += main_mem_width) {
18141             bxe_read_dmae(sc, i, main_mem_width / 4);
18142             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
18143                            i, main_mem_width / 4);
18144         }
18145         /* Clear HC parity attention */
18146         REG_RD(sc, main_mem_prty_clr);
18147     }
18148
18149 #if 1
18150     /* Enable STORMs SP logging */
18151     REG_WR8(sc, BAR_USTRORM_INTMEM +
18152            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18153     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18154            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18155     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18156            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18157     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18158            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18159 #endif
18160
18161     elink_phy_probe(&sc->link_params);
18162
18163     return (0);
18164 }
18165
18166 static void
18167 bxe_link_reset(struct bxe_softc *sc)
18168 {
18169     if (!BXE_NOMCP(sc)) {
18170         bxe_acquire_phy_lock(sc);
18171         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18172         bxe_release_phy_lock(sc);
18173     } else {
18174         if (!CHIP_REV_IS_SLOW(sc)) {
18175             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18176         }
18177     }
18178 }
18179
18180 static void
18181 bxe_reset_port(struct bxe_softc *sc)
18182 {
18183     int port = SC_PORT(sc);
18184     uint32_t val;
18185
18186         ELINK_DEBUG_P0(sc, "bxe_reset_port called\n");
18187     /* reset physical Link */
18188     bxe_link_reset(sc);
18189
18190     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18191
18192     /* Do not rcv packets to BRB */
18193     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18194     /* Do not direct rcv packets that are not for MCP to the BRB */
18195     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18196                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18197
18198     /* Configure AEU */
18199     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18200
18201     DELAY(100000);
18202
18203     /* Check for BRB port occupancy */
18204     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18205     if (val) {
18206         BLOGD(sc, DBG_LOAD,
18207               "BRB1 is not empty, %d blocks are occupied\n", val);
18208     }
18209
18210     /* TODO: Close Doorbell port? */
18211 }
18212
18213 static void
18214 bxe_ilt_wr(struct bxe_softc *sc,
18215            uint32_t         index,
18216            bus_addr_t       addr)
18217 {
18218     int reg;
18219     uint32_t wb_write[2];
18220
18221     if (CHIP_IS_E1(sc)) {
18222         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18223     } else {
18224         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18225     }
18226
18227     wb_write[0] = ONCHIP_ADDR1(addr);
18228     wb_write[1] = ONCHIP_ADDR2(addr);
18229     REG_WR_DMAE(sc, reg, wb_write, 2);
18230 }
18231
18232 static void
18233 bxe_clear_func_ilt(struct bxe_softc *sc,
18234                    uint32_t         func)
18235 {
18236     uint32_t i, base = FUNC_ILT_BASE(func);
18237     for (i = base; i < base + ILT_PER_FUNC; i++) {
18238         bxe_ilt_wr(sc, i, 0);
18239     }
18240 }
18241
18242 static void
18243 bxe_reset_func(struct bxe_softc *sc)
18244 {
18245     struct bxe_fastpath *fp;
18246     int port = SC_PORT(sc);
18247     int func = SC_FUNC(sc);
18248     int i;
18249
18250     /* Disable the function in the FW */
18251     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18252     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18253     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18254     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18255
18256     /* FP SBs */
18257     FOR_EACH_ETH_QUEUE(sc, i) {
18258         fp = &sc->fp[i];
18259         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18260                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18261                 SB_DISABLED);
18262     }
18263
18264     /* SP SB */
18265     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18266             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18267             SB_DISABLED);
18268
18269     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18270         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18271     }
18272
18273     /* Configure IGU */
18274     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18275         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18276         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18277     } else {
18278         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18279         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18280     }
18281
18282     if (CNIC_LOADED(sc)) {
18283         /* Disable Timer scan */
18284         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18285         /*
18286          * Wait for at least 10ms and up to 2 second for the timers
18287          * scan to complete
18288          */
18289         for (i = 0; i < 200; i++) {
18290             DELAY(10000);
18291             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18292                 break;
18293         }
18294     }
18295
18296     /* Clear ILT */
18297     bxe_clear_func_ilt(sc, func);
18298
18299     /*
18300      * Timers workaround bug for E2: if this is vnic-3,
18301      * we need to set the entire ilt range for this timers.
18302      */
18303     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18304         struct ilt_client_info ilt_cli;
18305         /* use dummy TM client */
18306         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18307         ilt_cli.start = 0;
18308         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18309         ilt_cli.client_num = ILT_CLIENT_TM;
18310
18311         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18312     }
18313
18314     /* this assumes that reset_port() called before reset_func()*/
18315     if (!CHIP_IS_E1x(sc)) {
18316         bxe_pf_disable(sc);
18317     }
18318
18319     sc->dmae_ready = 0;
18320 }
18321
18322 static int
18323 bxe_gunzip_init(struct bxe_softc *sc)
18324 {
18325     return (0);
18326 }
18327
18328 static void
18329 bxe_gunzip_end(struct bxe_softc *sc)
18330 {
18331     return;
18332 }
18333
18334 static int
18335 bxe_init_firmware(struct bxe_softc *sc)
18336 {
18337     if (CHIP_IS_E1(sc)) {
18338         ecore_init_e1_firmware(sc);
18339         sc->iro_array = e1_iro_arr;
18340     } else if (CHIP_IS_E1H(sc)) {
18341         ecore_init_e1h_firmware(sc);
18342         sc->iro_array = e1h_iro_arr;
18343     } else if (!CHIP_IS_E1x(sc)) {
18344         ecore_init_e2_firmware(sc);
18345         sc->iro_array = e2_iro_arr;
18346     } else {
18347         BLOGE(sc, "Unsupported chip revision\n");
18348         return (-1);
18349     }
18350
18351     return (0);
18352 }
18353
18354 static void
18355 bxe_release_firmware(struct bxe_softc *sc)
18356 {
18357     /* Do nothing */
18358     return;
18359 }
18360
18361 static int
18362 ecore_gunzip(struct bxe_softc *sc,
18363              const uint8_t    *zbuf,
18364              int              len)
18365 {
18366     /* XXX : Implement... */
18367     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18368     return (FALSE);
18369 }
18370
18371 static void
18372 ecore_reg_wr_ind(struct bxe_softc *sc,
18373                  uint32_t         addr,
18374                  uint32_t         val)
18375 {
18376     bxe_reg_wr_ind(sc, addr, val);
18377 }
18378
18379 static void
18380 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18381                           bus_addr_t       phys_addr,
18382                           uint32_t         addr,
18383                           uint32_t         len)
18384 {
18385     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18386 }
18387
18388 void
18389 ecore_storm_memset_struct(struct bxe_softc *sc,
18390                           uint32_t         addr,
18391                           size_t           size,
18392                           uint32_t         *data)
18393 {
18394     uint8_t i;
18395     for (i = 0; i < size/4; i++) {
18396         REG_WR(sc, addr + (i * 4), data[i]);
18397     }
18398 }
18399
18400
18401 /*
18402  * character device - ioctl interface definitions
18403  */
18404
18405
18406 #include "bxe_dump.h"
18407 #include "bxe_ioctl.h"
18408 #include <sys/conf.h>
18409
18410 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18411                 struct thread *td);
18412
18413 static struct cdevsw bxe_cdevsw = {
18414     .d_version = D_VERSION,
18415     .d_ioctl = bxe_eioctl,
18416     .d_name = "bxecnic",
18417 };
18418
18419 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18420
18421
18422 #define DUMP_ALL_PRESETS        0x1FFF
18423 #define DUMP_MAX_PRESETS        13
18424 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18425 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18426 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18427 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18428 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18429
18430 #define IS_REG_IN_PRESET(presets, idx)  \
18431                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18432
18433
18434 static int
18435 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18436 {
18437     if (CHIP_IS_E1(sc))
18438         return dump_num_registers[0][preset-1];
18439     else if (CHIP_IS_E1H(sc))
18440         return dump_num_registers[1][preset-1];
18441     else if (CHIP_IS_E2(sc))
18442         return dump_num_registers[2][preset-1];
18443     else if (CHIP_IS_E3A0(sc))
18444         return dump_num_registers[3][preset-1];
18445     else if (CHIP_IS_E3B0(sc))
18446         return dump_num_registers[4][preset-1];
18447     else
18448         return 0;
18449 }
18450
18451 static int
18452 bxe_get_total_regs_len32(struct bxe_softc *sc)
18453 {
18454     uint32_t preset_idx;
18455     int regdump_len32 = 0;
18456
18457
18458     /* Calculate the total preset regs length */
18459     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18460         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18461     }
18462
18463     return regdump_len32;
18464 }
18465
18466 static const uint32_t *
18467 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18468 {
18469     if (CHIP_IS_E2(sc))
18470         return page_vals_e2;
18471     else if (CHIP_IS_E3(sc))
18472         return page_vals_e3;
18473     else
18474         return NULL;
18475 }
18476
18477 static uint32_t
18478 __bxe_get_page_reg_num(struct bxe_softc *sc)
18479 {
18480     if (CHIP_IS_E2(sc))
18481         return PAGE_MODE_VALUES_E2;
18482     else if (CHIP_IS_E3(sc))
18483         return PAGE_MODE_VALUES_E3;
18484     else
18485         return 0;
18486 }
18487
18488 static const uint32_t *
18489 __bxe_get_page_write_ar(struct bxe_softc *sc)
18490 {
18491     if (CHIP_IS_E2(sc))
18492         return page_write_regs_e2;
18493     else if (CHIP_IS_E3(sc))
18494         return page_write_regs_e3;
18495     else
18496         return NULL;
18497 }
18498
18499 static uint32_t
18500 __bxe_get_page_write_num(struct bxe_softc *sc)
18501 {
18502     if (CHIP_IS_E2(sc))
18503         return PAGE_WRITE_REGS_E2;
18504     else if (CHIP_IS_E3(sc))
18505         return PAGE_WRITE_REGS_E3;
18506     else
18507         return 0;
18508 }
18509
18510 static const struct reg_addr *
18511 __bxe_get_page_read_ar(struct bxe_softc *sc)
18512 {
18513     if (CHIP_IS_E2(sc))
18514         return page_read_regs_e2;
18515     else if (CHIP_IS_E3(sc))
18516         return page_read_regs_e3;
18517     else
18518         return NULL;
18519 }
18520
18521 static uint32_t
18522 __bxe_get_page_read_num(struct bxe_softc *sc)
18523 {
18524     if (CHIP_IS_E2(sc))
18525         return PAGE_READ_REGS_E2;
18526     else if (CHIP_IS_E3(sc))
18527         return PAGE_READ_REGS_E3;
18528     else
18529         return 0;
18530 }
18531
18532 static bool
18533 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18534 {
18535     if (CHIP_IS_E1(sc))
18536         return IS_E1_REG(reg_info->chips);
18537     else if (CHIP_IS_E1H(sc))
18538         return IS_E1H_REG(reg_info->chips);
18539     else if (CHIP_IS_E2(sc))
18540         return IS_E2_REG(reg_info->chips);
18541     else if (CHIP_IS_E3A0(sc))
18542         return IS_E3A0_REG(reg_info->chips);
18543     else if (CHIP_IS_E3B0(sc))
18544         return IS_E3B0_REG(reg_info->chips);
18545     else
18546         return 0;
18547 }
18548
18549 static bool
18550 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18551 {
18552     if (CHIP_IS_E1(sc))
18553         return IS_E1_REG(wreg_info->chips);
18554     else if (CHIP_IS_E1H(sc))
18555         return IS_E1H_REG(wreg_info->chips);
18556     else if (CHIP_IS_E2(sc))
18557         return IS_E2_REG(wreg_info->chips);
18558     else if (CHIP_IS_E3A0(sc))
18559         return IS_E3A0_REG(wreg_info->chips);
18560     else if (CHIP_IS_E3B0(sc))
18561         return IS_E3B0_REG(wreg_info->chips);
18562     else
18563         return 0;
18564 }
18565
18566 /**
18567  * bxe_read_pages_regs - read "paged" registers
18568  *
18569  * @bp          device handle
18570  * @p           output buffer
18571  *
18572  * Reads "paged" memories: memories that may only be read by first writing to a
18573  * specific address ("write address") and then reading from a specific address
18574  * ("read address"). There may be more than one write address per "page" and
18575  * more than one read address per write address.
18576  */
18577 static void
18578 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18579 {
18580     uint32_t i, j, k, n;
18581
18582     /* addresses of the paged registers */
18583     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18584     /* number of paged registers */
18585     int num_pages = __bxe_get_page_reg_num(sc);
18586     /* write addresses */
18587     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18588     /* number of write addresses */
18589     int write_num = __bxe_get_page_write_num(sc);
18590     /* read addresses info */
18591     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18592     /* number of read addresses */
18593     int read_num = __bxe_get_page_read_num(sc);
18594     uint32_t addr, size;
18595
18596     for (i = 0; i < num_pages; i++) {
18597         for (j = 0; j < write_num; j++) {
18598             REG_WR(sc, write_addr[j], page_addr[i]);
18599
18600             for (k = 0; k < read_num; k++) {
18601                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18602                     size = read_addr[k].size;
18603                     for (n = 0; n < size; n++) {
18604                         addr = read_addr[k].addr + n*4;
18605                         *p++ = REG_RD(sc, addr);
18606                     }
18607                 }
18608             }
18609         }
18610     }
18611     return;
18612 }
18613
18614
18615 static int
18616 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18617 {
18618     uint32_t i, j, addr;
18619     const struct wreg_addr *wreg_addr_p = NULL;
18620
18621     if (CHIP_IS_E1(sc))
18622         wreg_addr_p = &wreg_addr_e1;
18623     else if (CHIP_IS_E1H(sc))
18624         wreg_addr_p = &wreg_addr_e1h;
18625     else if (CHIP_IS_E2(sc))
18626         wreg_addr_p = &wreg_addr_e2;
18627     else if (CHIP_IS_E3A0(sc))
18628         wreg_addr_p = &wreg_addr_e3;
18629     else if (CHIP_IS_E3B0(sc))
18630         wreg_addr_p = &wreg_addr_e3b0;
18631     else
18632         return (-1);
18633
18634     /* Read the idle_chk registers */
18635     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18636         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18637             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18638             for (j = 0; j < idle_reg_addrs[i].size; j++)
18639                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18640         }
18641     }
18642
18643     /* Read the regular registers */
18644     for (i = 0; i < REGS_COUNT; i++) {
18645         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18646             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18647             for (j = 0; j < reg_addrs[i].size; j++)
18648                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18649         }
18650     }
18651
18652     /* Read the CAM registers */
18653     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18654         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18655         for (i = 0; i < wreg_addr_p->size; i++) {
18656             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18657
18658             /* In case of wreg_addr register, read additional
18659                registers from read_regs array
18660              */
18661             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18662                 addr = *(wreg_addr_p->read_regs);
18663                 *p++ = REG_RD(sc, addr + j*4);
18664             }
18665         }
18666     }
18667
18668     /* Paged registers are supported in E2 & E3 only */
18669     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18670         /* Read "paged" registers */
18671         bxe_read_pages_regs(sc, p, preset);
18672     }
18673
18674     return 0;
18675 }
18676
18677 int
18678 bxe_grc_dump(struct bxe_softc *sc)
18679 {
18680     int rval = 0;
18681     uint32_t preset_idx;
18682     uint8_t *buf;
18683     uint32_t size;
18684     struct  dump_header *d_hdr;
18685     uint32_t i;
18686     uint32_t reg_val;
18687     uint32_t reg_addr;
18688     uint32_t cmd_offset;
18689     struct ecore_ilt *ilt = SC_ILT(sc);
18690     struct bxe_fastpath *fp;
18691     struct ilt_client_info *ilt_cli;
18692     int grc_dump_size;
18693
18694
18695     if (sc->grcdump_done || sc->grcdump_started)
18696         return (rval);
18697     
18698     sc->grcdump_started = 1;
18699     BLOGI(sc, "Started collecting grcdump\n");
18700
18701     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18702                 sizeof(struct  dump_header);
18703
18704     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18705
18706     if (sc->grc_dump == NULL) {
18707         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18708         return(ENOMEM);
18709     }
18710
18711
18712
18713     /* Disable parity attentions as long as following dump may
18714      * cause false alarms by reading never written registers. We
18715      * will re-enable parity attentions right after the dump.
18716      */
18717
18718     /* Disable parity on path 0 */
18719     bxe_pretend_func(sc, 0);
18720
18721     ecore_disable_blocks_parity(sc);
18722
18723     /* Disable parity on path 1 */
18724     bxe_pretend_func(sc, 1);
18725     ecore_disable_blocks_parity(sc);
18726
18727     /* Return to current function */
18728     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18729
18730     buf = sc->grc_dump;
18731     d_hdr = sc->grc_dump;
18732
18733     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18734     d_hdr->version = BNX2X_DUMP_VERSION;
18735     d_hdr->preset = DUMP_ALL_PRESETS;
18736
18737     if (CHIP_IS_E1(sc)) {
18738         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18739     } else if (CHIP_IS_E1H(sc)) {
18740         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18741     } else if (CHIP_IS_E2(sc)) {
18742         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18743                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18744     } else if (CHIP_IS_E3A0(sc)) {
18745         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18746                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18747     } else if (CHIP_IS_E3B0(sc)) {
18748         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18749                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18750     }
18751
18752     buf += sizeof(struct  dump_header);
18753
18754     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18755
18756         /* Skip presets with IOR */
18757         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18758             (preset_idx == 11))
18759             continue;
18760
18761         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18762
18763         if (rval)
18764             break;
18765
18766         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18767
18768         buf += size;
18769     }
18770
18771     bxe_pretend_func(sc, 0);
18772     ecore_clear_blocks_parity(sc);
18773     ecore_enable_blocks_parity(sc);
18774
18775     bxe_pretend_func(sc, 1);
18776     ecore_clear_blocks_parity(sc);
18777     ecore_enable_blocks_parity(sc);
18778
18779     /* Return to current function */
18780     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18781
18782
18783
18784     if(sc->state == BXE_STATE_OPEN) {
18785         if(sc->fw_stats_req  != NULL) {
18786                 BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18787                                 (uintmax_t)sc->fw_stats_req_mapping,
18788                                 (uintmax_t)sc->fw_stats_data_mapping,
18789                                 sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18790                 }       
18791                 if(sc->def_sb != NULL) {
18792                         BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18793                                 (void *)sc->def_sb_dma.paddr, sc->def_sb,
18794                                 sizeof(struct host_sp_status_block));
18795                 }
18796                 if(sc->eq_dma.vaddr != NULL) {
18797                 BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18798                                 (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18799                 }
18800                 if(sc->sp_dma.vaddr != NULL) {
18801                 BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18802                                 (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18803                                 sizeof(struct bxe_slowpath));
18804                 }
18805                 if(sc->spq_dma.vaddr != NULL) {
18806                 BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18807                                 (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18808                 }
18809                 if(sc->gz_buf_dma.vaddr != NULL) {
18810                 BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18811                                 (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18812                                 FW_BUF_SIZE);
18813                 }
18814         for (i = 0; i < sc->num_queues; i++) {
18815                 fp = &sc->fp[i];
18816                         if(fp->sb_dma.vaddr != NULL && fp->tx_dma.vaddr != NULL &&
18817                         fp->rx_dma.vaddr != NULL && fp->rcq_dma.vaddr != NULL &&
18818                         fp->rx_sge_dma.vaddr != NULL) {
18819
18820                                 BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18821                                 (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18822                                 sizeof(union bxe_host_hc_status_block));
18823                                 BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18824                                 (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18825                                 (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18826                         BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18827                                 (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18828                                 (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18829                         BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18830                                 (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18831                                 (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18832                         BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18833                                 (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18834                                 (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18835                 }
18836                 }
18837                 if(ilt != NULL ) {
18838                 ilt_cli = &ilt->clients[1];
18839                         if(ilt->lines != NULL) {
18840                 for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18841                         BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18842                                 (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18843                                 ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18844                 }
18845                         }
18846                 }
18847
18848
18849         cmd_offset = DMAE_REG_CMD_MEM;
18850         for (i = 0; i < 224; i++) {
18851                 reg_addr = (cmd_offset +(i * 4));
18852                 reg_val = REG_RD(sc, reg_addr);
18853                 BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18854                                 reg_addr, reg_val);
18855         }
18856         }
18857
18858     BLOGI(sc, "Collection of grcdump done\n");
18859     sc->grcdump_done = 1;
18860     return(rval);
18861 }
18862
18863 static int
18864 bxe_add_cdev(struct bxe_softc *sc)
18865 {
18866     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18867
18868     if (sc->eeprom == NULL) {
18869         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18870         return (-1);
18871     }
18872
18873     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18874                             sc->ifnet->if_dunit,
18875                             UID_ROOT,
18876                             GID_WHEEL,
18877                             0600,
18878                             "%s",
18879                             if_name(sc->ifnet));
18880
18881     if (sc->ioctl_dev == NULL) {
18882         free(sc->eeprom, M_DEVBUF);
18883         sc->eeprom = NULL;
18884         return (-1);
18885     }
18886
18887     sc->ioctl_dev->si_drv1 = sc;
18888
18889     return (0);
18890 }
18891
18892 static void
18893 bxe_del_cdev(struct bxe_softc *sc)
18894 {
18895     if (sc->ioctl_dev != NULL)
18896         destroy_dev(sc->ioctl_dev);
18897
18898     if (sc->eeprom != NULL) {
18899         free(sc->eeprom, M_DEVBUF);
18900         sc->eeprom = NULL;
18901     }
18902     sc->ioctl_dev = NULL;
18903
18904     return;
18905 }
18906
18907 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18908 {
18909
18910     if ((sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) == 0)
18911         return FALSE;
18912
18913     return TRUE;
18914 }
18915
18916
18917 static int
18918 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18919 {
18920     int rval = 0;
18921
18922     if(!bxe_is_nvram_accessible(sc)) {
18923         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18924         return (-EAGAIN);
18925     }
18926     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18927
18928
18929    return (rval);
18930 }
18931
18932 static int
18933 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18934 {
18935     int rval = 0;
18936
18937     if(!bxe_is_nvram_accessible(sc)) {
18938         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18939         return (-EAGAIN);
18940     }
18941     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18942
18943    return (rval);
18944 }
18945
18946 static int
18947 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18948 {
18949     int rval = 0;
18950
18951     switch (eeprom->eeprom_cmd) {
18952
18953     case BXE_EEPROM_CMD_SET_EEPROM:
18954
18955         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18956                        eeprom->eeprom_data_len);
18957
18958         if (rval)
18959             break;
18960
18961         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18962                        eeprom->eeprom_data_len);
18963         break;
18964
18965     case BXE_EEPROM_CMD_GET_EEPROM:
18966
18967         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18968                        eeprom->eeprom_data_len);
18969
18970         if (rval) {
18971             break;
18972         }
18973
18974         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18975                        eeprom->eeprom_data_len);
18976         break;
18977
18978     default:
18979             rval = EINVAL;
18980             break;
18981     }
18982
18983     if (rval) {
18984         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18985     }
18986
18987     return (rval);
18988 }
18989
18990 static int
18991 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18992 {
18993     uint32_t ext_phy_config;
18994     int port = SC_PORT(sc);
18995     int cfg_idx = bxe_get_link_cfg_idx(sc);
18996
18997     dev_p->supported = sc->port.supported[cfg_idx] |
18998             (sc->port.supported[cfg_idx ^ 1] &
18999             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
19000     dev_p->advertising = sc->port.advertising[cfg_idx];
19001     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
19002         ELINK_ETH_PHY_SFP_1G_FIBER) {
19003         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
19004         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
19005     }
19006     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
19007         !(sc->flags & BXE_MF_FUNC_DIS)) {
19008         dev_p->duplex = sc->link_vars.duplex;
19009         if (IS_MF(sc) && !BXE_NOMCP(sc))
19010             dev_p->speed = bxe_get_mf_speed(sc);
19011         else
19012             dev_p->speed = sc->link_vars.line_speed;
19013     } else {
19014         dev_p->duplex = DUPLEX_UNKNOWN;
19015         dev_p->speed = SPEED_UNKNOWN;
19016     }
19017
19018     dev_p->port = bxe_media_detect(sc);
19019
19020     ext_phy_config = SHMEM_RD(sc,
19021                          dev_info.port_hw_config[port].external_phy_config);
19022     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
19023         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
19024         dev_p->phy_address =  sc->port.phy_addr;
19025     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19026             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
19027         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
19028             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
19029         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
19030     else
19031         dev_p->phy_address = 0;
19032
19033     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
19034         dev_p->autoneg = AUTONEG_ENABLE;
19035     else
19036        dev_p->autoneg = AUTONEG_DISABLE;
19037
19038
19039     return 0;
19040 }
19041
19042 static int
19043 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
19044         struct thread *td)
19045 {
19046     struct bxe_softc    *sc;
19047     int                 rval = 0;
19048     device_t            pci_dev;
19049     bxe_grcdump_t       *dump = NULL;
19050     int grc_dump_size;
19051     bxe_drvinfo_t   *drv_infop = NULL;
19052     bxe_dev_setting_t  *dev_p;
19053     bxe_dev_setting_t  dev_set;
19054     bxe_get_regs_t  *reg_p;
19055     bxe_reg_rdw_t *reg_rdw_p;
19056     bxe_pcicfg_rdw_t *cfg_rdw_p;
19057     bxe_perm_mac_addr_t *mac_addr_p;
19058
19059
19060     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
19061         return ENXIO;
19062
19063     pci_dev= sc->dev;
19064
19065     dump = (bxe_grcdump_t *)data;
19066
19067     switch(cmd) {
19068
19069         case BXE_GRC_DUMP_SIZE:
19070             dump->pci_func = sc->pcie_func;
19071             dump->grcdump_size =
19072                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19073                      sizeof(struct  dump_header);
19074             break;
19075
19076         case BXE_GRC_DUMP:
19077             
19078             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
19079                                 sizeof(struct  dump_header);
19080             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
19081                 (dump->grcdump_size < grc_dump_size)) {
19082                 rval = EINVAL;
19083                 break;
19084             }
19085
19086             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
19087                 (!sc->grcdump_started)) {
19088                 rval =  bxe_grc_dump(sc);
19089             }
19090
19091             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
19092                 (sc->grc_dump != NULL))  {
19093                 dump->grcdump_dwords = grc_dump_size >> 2;
19094                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
19095                 free(sc->grc_dump, M_DEVBUF);
19096                 sc->grc_dump = NULL;
19097                 sc->grcdump_started = 0;
19098                 sc->grcdump_done = 0;
19099             }
19100
19101             break;
19102
19103         case BXE_DRV_INFO:
19104             drv_infop = (bxe_drvinfo_t *)data;
19105             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
19106             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
19107                 BXE_DRIVER_VERSION);
19108             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
19109                 sc->devinfo.bc_ver_str);
19110             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
19111                 "%s", sc->fw_ver_str);
19112             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
19113             drv_infop->reg_dump_len =
19114                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
19115                     + sizeof(struct  dump_header);
19116             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
19117                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
19118             break;
19119
19120         case BXE_DEV_SETTING:
19121             dev_p = (bxe_dev_setting_t *)data;
19122             bxe_get_settings(sc, &dev_set);
19123             dev_p->supported = dev_set.supported;
19124             dev_p->advertising = dev_set.advertising;
19125             dev_p->speed = dev_set.speed;
19126             dev_p->duplex = dev_set.duplex;
19127             dev_p->port = dev_set.port;
19128             dev_p->phy_address = dev_set.phy_address;
19129             dev_p->autoneg = dev_set.autoneg;
19130
19131             break;
19132
19133         case BXE_GET_REGS:
19134
19135             reg_p = (bxe_get_regs_t *)data;
19136             grc_dump_size = reg_p->reg_buf_len;
19137
19138             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
19139                 bxe_grc_dump(sc);
19140             }
19141             if((sc->grcdump_done) && (sc->grcdump_started) &&
19142                 (sc->grc_dump != NULL))  {
19143                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
19144                 free(sc->grc_dump, M_DEVBUF);
19145                 sc->grc_dump = NULL;
19146                 sc->grcdump_started = 0;
19147                 sc->grcdump_done = 0;
19148             }
19149
19150             break;
19151
19152         case BXE_RDW_REG:
19153             reg_rdw_p = (bxe_reg_rdw_t *)data;
19154             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
19155                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19156                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19157
19158             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19159                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19160                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19161
19162             break;
19163
19164         case BXE_RDW_PCICFG:
19165             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19166             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19167
19168                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19169                                          cfg_rdw_p->cfg_width);
19170
19171             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19172                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19173                             cfg_rdw_p->cfg_width);
19174             } else {
19175                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19176             }
19177             break;
19178
19179         case BXE_MAC_ADDR:
19180             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19181             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19182                 sc->mac_addr_str);
19183             break;
19184
19185         case BXE_EEPROM:
19186             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19187             break;
19188
19189
19190         default:
19191             break;
19192     }
19193
19194     return (rval);
19195 }