]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/dev/bxe/bxe.c
MFC r295830
[FreeBSD/stable/9.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.79"
31
32 #include "bxe.h"
33 #include "ecore_sp.h"
34 #include "ecore_init.h"
35 #include "ecore_init_ops.h"
36
37 #include "57710_int_offsets.h"
38 #include "57711_int_offsets.h"
39 #include "57712_int_offsets.h"
40
41 /*
42  * CTLTYPE_U64 and sysctl_handle_64 were added in r217616. Define these
43  * explicitly here for older kernels that don't include this changeset.
44  */
45 #ifndef CTLTYPE_U64
46 #define CTLTYPE_U64      CTLTYPE_QUAD
47 #define sysctl_handle_64 sysctl_handle_quad
48 #endif
49
50 /*
51  * CSUM_TCP_IPV6 and CSUM_UDP_IPV6 were added in r236170. Define these
52  * here as zero(0) for older kernels that don't include this changeset
53  * thereby masking the functionality.
54  */
55 #ifndef CSUM_TCP_IPV6
56 #define CSUM_TCP_IPV6 0
57 #define CSUM_UDP_IPV6 0
58 #endif
59
60 /*
61  * pci_find_cap was added in r219865. Re-define this at pci_find_extcap
62  * for older kernels that don't include this changeset.
63  */
64 #if __FreeBSD_version < 900035
65 #define pci_find_cap pci_find_extcap
66 #endif
67
68 #define BXE_DEF_SB_ATT_IDX 0x0001
69 #define BXE_DEF_SB_IDX     0x0002
70
71 /*
72  * FLR Support - bxe_pf_flr_clnup() is called during nic_load in the per
73  * function HW initialization.
74  */
75 #define FLR_WAIT_USEC     10000 /* 10 msecs */
76 #define FLR_WAIT_INTERVAL 50    /* usecs */
77 #define FLR_POLL_CNT      (FLR_WAIT_USEC / FLR_WAIT_INTERVAL) /* 200 */
78
79 struct pbf_pN_buf_regs {
80     int pN;
81     uint32_t init_crd;
82     uint32_t crd;
83     uint32_t crd_freed;
84 };
85
86 struct pbf_pN_cmd_regs {
87     int pN;
88     uint32_t lines_occup;
89     uint32_t lines_freed;
90 };
91
92 /*
93  * PCI Device ID Table used by bxe_probe().
94  */
95 #define BXE_DEVDESC_MAX 64
96 static struct bxe_device_type bxe_devs[] = {
97     {
98         BRCM_VENDORID,
99         CHIP_NUM_57710,
100         PCI_ANY_ID, PCI_ANY_ID,
101         "QLogic NetXtreme II BCM57710 10GbE"
102     },
103     {
104         BRCM_VENDORID,
105         CHIP_NUM_57711,
106         PCI_ANY_ID, PCI_ANY_ID,
107         "QLogic NetXtreme II BCM57711 10GbE"
108     },
109     {
110         BRCM_VENDORID,
111         CHIP_NUM_57711E,
112         PCI_ANY_ID, PCI_ANY_ID,
113         "QLogic NetXtreme II BCM57711E 10GbE"
114     },
115     {
116         BRCM_VENDORID,
117         CHIP_NUM_57712,
118         PCI_ANY_ID, PCI_ANY_ID,
119         "QLogic NetXtreme II BCM57712 10GbE"
120     },
121     {
122         BRCM_VENDORID,
123         CHIP_NUM_57712_MF,
124         PCI_ANY_ID, PCI_ANY_ID,
125         "QLogic NetXtreme II BCM57712 MF 10GbE"
126     },
127     {
128         BRCM_VENDORID,
129         CHIP_NUM_57800,
130         PCI_ANY_ID, PCI_ANY_ID,
131         "QLogic NetXtreme II BCM57800 10GbE"
132     },
133     {
134         BRCM_VENDORID,
135         CHIP_NUM_57800_MF,
136         PCI_ANY_ID, PCI_ANY_ID,
137         "QLogic NetXtreme II BCM57800 MF 10GbE"
138     },
139     {
140         BRCM_VENDORID,
141         CHIP_NUM_57810,
142         PCI_ANY_ID, PCI_ANY_ID,
143         "QLogic NetXtreme II BCM57810 10GbE"
144     },
145     {
146         BRCM_VENDORID,
147         CHIP_NUM_57810_MF,
148         PCI_ANY_ID, PCI_ANY_ID,
149         "QLogic NetXtreme II BCM57810 MF 10GbE"
150     },
151     {
152         BRCM_VENDORID,
153         CHIP_NUM_57811,
154         PCI_ANY_ID, PCI_ANY_ID,
155         "QLogic NetXtreme II BCM57811 10GbE"
156     },
157     {
158         BRCM_VENDORID,
159         CHIP_NUM_57811_MF,
160         PCI_ANY_ID, PCI_ANY_ID,
161         "QLogic NetXtreme II BCM57811 MF 10GbE"
162     },
163     {
164         BRCM_VENDORID,
165         CHIP_NUM_57840_4_10,
166         PCI_ANY_ID, PCI_ANY_ID,
167         "QLogic NetXtreme II BCM57840 4x10GbE"
168     },
169     {
170         BRCM_VENDORID,
171         CHIP_NUM_57840_MF,
172         PCI_ANY_ID, PCI_ANY_ID,
173         "QLogic NetXtreme II BCM57840 MF 10GbE"
174     },
175     {
176         0, 0, 0, 0, NULL
177     }
178 };
179
180 MALLOC_DECLARE(M_BXE_ILT);
181 MALLOC_DEFINE(M_BXE_ILT, "bxe_ilt", "bxe ILT pointer");
182
183 /*
184  * FreeBSD device entry points.
185  */
186 static int bxe_probe(device_t);
187 static int bxe_attach(device_t);
188 static int bxe_detach(device_t);
189 static int bxe_shutdown(device_t);
190
191 /*
192  * FreeBSD KLD module/device interface event handler method.
193  */
194 static device_method_t bxe_methods[] = {
195     /* Device interface (device_if.h) */
196     DEVMETHOD(device_probe,     bxe_probe),
197     DEVMETHOD(device_attach,    bxe_attach),
198     DEVMETHOD(device_detach,    bxe_detach),
199     DEVMETHOD(device_shutdown,  bxe_shutdown),
200     /* Bus interface (bus_if.h) */
201     DEVMETHOD(bus_print_child,  bus_generic_print_child),
202     DEVMETHOD(bus_driver_added, bus_generic_driver_added),
203     KOBJMETHOD_END
204 };
205
206 /*
207  * FreeBSD KLD Module data declaration
208  */
209 static driver_t bxe_driver = {
210     "bxe",                   /* module name */
211     bxe_methods,             /* event handler */
212     sizeof(struct bxe_softc) /* extra data */
213 };
214
215 /*
216  * FreeBSD dev class is needed to manage dev instances and
217  * to associate with a bus type
218  */
219 static devclass_t bxe_devclass;
220
221 MODULE_DEPEND(bxe, pci, 1, 1, 1);
222 MODULE_DEPEND(bxe, ether, 1, 1, 1);
223 DRIVER_MODULE(bxe, pci, bxe_driver, bxe_devclass, 0, 0);
224
225 /* resources needed for unloading a previously loaded device */
226
227 #define BXE_PREV_WAIT_NEEDED 1
228 struct mtx bxe_prev_mtx;
229 MTX_SYSINIT(bxe_prev_mtx, &bxe_prev_mtx, "bxe_prev_lock", MTX_DEF);
230 struct bxe_prev_list_node {
231     LIST_ENTRY(bxe_prev_list_node) node;
232     uint8_t bus;
233     uint8_t slot;
234     uint8_t path;
235     uint8_t aer; /* XXX automatic error recovery */
236     uint8_t undi;
237 };
238 static LIST_HEAD(, bxe_prev_list_node) bxe_prev_list = LIST_HEAD_INITIALIZER(bxe_prev_list);
239
240 static int load_count[2][3] = { {0} }; /* per-path: 0-common, 1-port0, 2-port1 */
241
242 /* Tunable device values... */
243
244 SYSCTL_NODE(_hw, OID_AUTO, bxe, CTLFLAG_RD, 0, "bxe driver parameters");
245
246 /* Debug */
247 unsigned long bxe_debug = 0;
248 TUNABLE_ULONG("hw.bxe.debug", &bxe_debug);
249 SYSCTL_ULONG(_hw_bxe, OID_AUTO, debug, (CTLFLAG_RDTUN),
250              &bxe_debug, 0, "Debug logging mode");
251
252 /* Interrupt Mode: 0 (IRQ), 1 (MSI/IRQ), and 2 (MSI-X/MSI/IRQ) */
253 static int bxe_interrupt_mode = INTR_MODE_MSIX;
254 TUNABLE_INT("hw.bxe.interrupt_mode", &bxe_interrupt_mode);
255 SYSCTL_INT(_hw_bxe, OID_AUTO, interrupt_mode, CTLFLAG_RDTUN,
256            &bxe_interrupt_mode, 0, "Interrupt (MSI-X/MSI/INTx) mode");
257
258 /* Number of Queues: 0 (Auto) or 1 to 16 (fixed queue number) */
259 static int bxe_queue_count = 4;
260 TUNABLE_INT("hw.bxe.queue_count", &bxe_queue_count);
261 SYSCTL_INT(_hw_bxe, OID_AUTO, queue_count, CTLFLAG_RDTUN,
262            &bxe_queue_count, 0, "Multi-Queue queue count");
263
264 /* max number of buffers per queue (default RX_BD_USABLE) */
265 static int bxe_max_rx_bufs = 0;
266 TUNABLE_INT("hw.bxe.max_rx_bufs", &bxe_max_rx_bufs);
267 SYSCTL_INT(_hw_bxe, OID_AUTO, max_rx_bufs, CTLFLAG_RDTUN,
268            &bxe_max_rx_bufs, 0, "Maximum Number of Rx Buffers Per Queue");
269
270 /* Host interrupt coalescing RX tick timer (usecs) */
271 static int bxe_hc_rx_ticks = 25;
272 TUNABLE_INT("hw.bxe.hc_rx_ticks", &bxe_hc_rx_ticks);
273 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_rx_ticks, CTLFLAG_RDTUN,
274            &bxe_hc_rx_ticks, 0, "Host Coalescing Rx ticks");
275
276 /* Host interrupt coalescing TX tick timer (usecs) */
277 static int bxe_hc_tx_ticks = 50;
278 TUNABLE_INT("hw.bxe.hc_tx_ticks", &bxe_hc_tx_ticks);
279 SYSCTL_INT(_hw_bxe, OID_AUTO, hc_tx_ticks, CTLFLAG_RDTUN,
280            &bxe_hc_tx_ticks, 0, "Host Coalescing Tx ticks");
281
282 /* Maximum number of Rx packets to process at a time */
283 static int bxe_rx_budget = 0xffffffff;
284 TUNABLE_INT("hw.bxe.rx_budget", &bxe_rx_budget);
285 SYSCTL_INT(_hw_bxe, OID_AUTO, rx_budget, CTLFLAG_TUN,
286            &bxe_rx_budget, 0, "Rx processing budget");
287
288 /* Maximum LRO aggregation size */
289 static int bxe_max_aggregation_size = 0;
290 TUNABLE_INT("hw.bxe.max_aggregation_size", &bxe_max_aggregation_size);
291 SYSCTL_INT(_hw_bxe, OID_AUTO, max_aggregation_size, CTLFLAG_TUN,
292            &bxe_max_aggregation_size, 0, "max aggregation size");
293
294 /* PCI MRRS: -1 (Auto), 0 (128B), 1 (256B), 2 (512B), 3 (1KB) */
295 static int bxe_mrrs = -1;
296 TUNABLE_INT("hw.bxe.mrrs", &bxe_mrrs);
297 SYSCTL_INT(_hw_bxe, OID_AUTO, mrrs, CTLFLAG_RDTUN,
298            &bxe_mrrs, 0, "PCIe maximum read request size");
299
300 /* AutoGrEEEn: 0 (hardware default), 1 (force on), 2 (force off) */
301 static int bxe_autogreeen = 0;
302 TUNABLE_INT("hw.bxe.autogreeen", &bxe_autogreeen);
303 SYSCTL_INT(_hw_bxe, OID_AUTO, autogreeen, CTLFLAG_RDTUN,
304            &bxe_autogreeen, 0, "AutoGrEEEn support");
305
306 /* 4-tuple RSS support for UDP: 0 (disabled), 1 (enabled) */
307 static int bxe_udp_rss = 0;
308 TUNABLE_INT("hw.bxe.udp_rss", &bxe_udp_rss);
309 SYSCTL_INT(_hw_bxe, OID_AUTO, udp_rss, CTLFLAG_RDTUN,
310            &bxe_udp_rss, 0, "UDP RSS support");
311
312
313 #define STAT_NAME_LEN 32 /* no stat names below can be longer than this */
314
315 #define STATS_OFFSET32(stat_name)                   \
316     (offsetof(struct bxe_eth_stats, stat_name) / 4)
317
318 #define Q_STATS_OFFSET32(stat_name)                   \
319     (offsetof(struct bxe_eth_q_stats, stat_name) / 4)
320
321 static const struct {
322     uint32_t offset;
323     uint32_t size;
324     uint32_t flags;
325 #define STATS_FLAGS_PORT  1
326 #define STATS_FLAGS_FUNC  2 /* MF only cares about function stats */
327 #define STATS_FLAGS_BOTH  (STATS_FLAGS_FUNC | STATS_FLAGS_PORT)
328     char string[STAT_NAME_LEN];
329 } bxe_eth_stats_arr[] = {
330     { STATS_OFFSET32(total_bytes_received_hi),
331                 8, STATS_FLAGS_BOTH, "rx_bytes" },
332     { STATS_OFFSET32(error_bytes_received_hi),
333                 8, STATS_FLAGS_BOTH, "rx_error_bytes" },
334     { STATS_OFFSET32(total_unicast_packets_received_hi),
335                 8, STATS_FLAGS_BOTH, "rx_ucast_packets" },
336     { STATS_OFFSET32(total_multicast_packets_received_hi),
337                 8, STATS_FLAGS_BOTH, "rx_mcast_packets" },
338     { STATS_OFFSET32(total_broadcast_packets_received_hi),
339                 8, STATS_FLAGS_BOTH, "rx_bcast_packets" },
340     { STATS_OFFSET32(rx_stat_dot3statsfcserrors_hi),
341                 8, STATS_FLAGS_PORT, "rx_crc_errors" },
342     { STATS_OFFSET32(rx_stat_dot3statsalignmenterrors_hi),
343                 8, STATS_FLAGS_PORT, "rx_align_errors" },
344     { STATS_OFFSET32(rx_stat_etherstatsundersizepkts_hi),
345                 8, STATS_FLAGS_PORT, "rx_undersize_packets" },
346     { STATS_OFFSET32(etherstatsoverrsizepkts_hi),
347                 8, STATS_FLAGS_PORT, "rx_oversize_packets" },
348     { STATS_OFFSET32(rx_stat_etherstatsfragments_hi),
349                 8, STATS_FLAGS_PORT, "rx_fragments" },
350     { STATS_OFFSET32(rx_stat_etherstatsjabbers_hi),
351                 8, STATS_FLAGS_PORT, "rx_jabbers" },
352     { STATS_OFFSET32(no_buff_discard_hi),
353                 8, STATS_FLAGS_BOTH, "rx_discards" },
354     { STATS_OFFSET32(mac_filter_discard),
355                 4, STATS_FLAGS_PORT, "rx_filtered_packets" },
356     { STATS_OFFSET32(mf_tag_discard),
357                 4, STATS_FLAGS_PORT, "rx_mf_tag_discard" },
358     { STATS_OFFSET32(pfc_frames_received_hi),
359                 8, STATS_FLAGS_PORT, "pfc_frames_received" },
360     { STATS_OFFSET32(pfc_frames_sent_hi),
361                 8, STATS_FLAGS_PORT, "pfc_frames_sent" },
362     { STATS_OFFSET32(brb_drop_hi),
363                 8, STATS_FLAGS_PORT, "rx_brb_discard" },
364     { STATS_OFFSET32(brb_truncate_hi),
365                 8, STATS_FLAGS_PORT, "rx_brb_truncate" },
366     { STATS_OFFSET32(pause_frames_received_hi),
367                 8, STATS_FLAGS_PORT, "rx_pause_frames" },
368     { STATS_OFFSET32(rx_stat_maccontrolframesreceived_hi),
369                 8, STATS_FLAGS_PORT, "rx_mac_ctrl_frames" },
370     { STATS_OFFSET32(nig_timer_max),
371                 4, STATS_FLAGS_PORT, "rx_constant_pause_events" },
372     { STATS_OFFSET32(total_bytes_transmitted_hi),
373                 8, STATS_FLAGS_BOTH, "tx_bytes" },
374     { STATS_OFFSET32(tx_stat_ifhcoutbadoctets_hi),
375                 8, STATS_FLAGS_PORT, "tx_error_bytes" },
376     { STATS_OFFSET32(total_unicast_packets_transmitted_hi),
377                 8, STATS_FLAGS_BOTH, "tx_ucast_packets" },
378     { STATS_OFFSET32(total_multicast_packets_transmitted_hi),
379                 8, STATS_FLAGS_BOTH, "tx_mcast_packets" },
380     { STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
381                 8, STATS_FLAGS_BOTH, "tx_bcast_packets" },
382     { STATS_OFFSET32(tx_stat_dot3statsinternalmactransmiterrors_hi),
383                 8, STATS_FLAGS_PORT, "tx_mac_errors" },
384     { STATS_OFFSET32(rx_stat_dot3statscarriersenseerrors_hi),
385                 8, STATS_FLAGS_PORT, "tx_carrier_errors" },
386     { STATS_OFFSET32(tx_stat_dot3statssinglecollisionframes_hi),
387                 8, STATS_FLAGS_PORT, "tx_single_collisions" },
388     { STATS_OFFSET32(tx_stat_dot3statsmultiplecollisionframes_hi),
389                 8, STATS_FLAGS_PORT, "tx_multi_collisions" },
390     { STATS_OFFSET32(tx_stat_dot3statsdeferredtransmissions_hi),
391                 8, STATS_FLAGS_PORT, "tx_deferred" },
392     { STATS_OFFSET32(tx_stat_dot3statsexcessivecollisions_hi),
393                 8, STATS_FLAGS_PORT, "tx_excess_collisions" },
394     { STATS_OFFSET32(tx_stat_dot3statslatecollisions_hi),
395                 8, STATS_FLAGS_PORT, "tx_late_collisions" },
396     { STATS_OFFSET32(tx_stat_etherstatscollisions_hi),
397                 8, STATS_FLAGS_PORT, "tx_total_collisions" },
398     { STATS_OFFSET32(tx_stat_etherstatspkts64octets_hi),
399                 8, STATS_FLAGS_PORT, "tx_64_byte_packets" },
400     { STATS_OFFSET32(tx_stat_etherstatspkts65octetsto127octets_hi),
401                 8, STATS_FLAGS_PORT, "tx_65_to_127_byte_packets" },
402     { STATS_OFFSET32(tx_stat_etherstatspkts128octetsto255octets_hi),
403                 8, STATS_FLAGS_PORT, "tx_128_to_255_byte_packets" },
404     { STATS_OFFSET32(tx_stat_etherstatspkts256octetsto511octets_hi),
405                 8, STATS_FLAGS_PORT, "tx_256_to_511_byte_packets" },
406     { STATS_OFFSET32(tx_stat_etherstatspkts512octetsto1023octets_hi),
407                 8, STATS_FLAGS_PORT, "tx_512_to_1023_byte_packets" },
408     { STATS_OFFSET32(etherstatspkts1024octetsto1522octets_hi),
409                 8, STATS_FLAGS_PORT, "tx_1024_to_1522_byte_packets" },
410     { STATS_OFFSET32(etherstatspktsover1522octets_hi),
411                 8, STATS_FLAGS_PORT, "tx_1523_to_9022_byte_packets" },
412     { STATS_OFFSET32(pause_frames_sent_hi),
413                 8, STATS_FLAGS_PORT, "tx_pause_frames" },
414     { STATS_OFFSET32(total_tpa_aggregations_hi),
415                 8, STATS_FLAGS_FUNC, "tpa_aggregations" },
416     { STATS_OFFSET32(total_tpa_aggregated_frames_hi),
417                 8, STATS_FLAGS_FUNC, "tpa_aggregated_frames"},
418     { STATS_OFFSET32(total_tpa_bytes_hi),
419                 8, STATS_FLAGS_FUNC, "tpa_bytes"},
420     { STATS_OFFSET32(eee_tx_lpi),
421                 4, STATS_FLAGS_PORT, "eee_tx_lpi"},
422     { STATS_OFFSET32(rx_calls),
423                 4, STATS_FLAGS_FUNC, "rx_calls"},
424     { STATS_OFFSET32(rx_pkts),
425                 4, STATS_FLAGS_FUNC, "rx_pkts"},
426     { STATS_OFFSET32(rx_tpa_pkts),
427                 4, STATS_FLAGS_FUNC, "rx_tpa_pkts"},
428     { STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
429                 4, STATS_FLAGS_FUNC, "rx_erroneous_jumbo_sge_pkts"},
430     { STATS_OFFSET32(rx_bxe_service_rxsgl),
431                 4, STATS_FLAGS_FUNC, "rx_bxe_service_rxsgl"},
432     { STATS_OFFSET32(rx_jumbo_sge_pkts),
433                 4, STATS_FLAGS_FUNC, "rx_jumbo_sge_pkts"},
434     { STATS_OFFSET32(rx_soft_errors),
435                 4, STATS_FLAGS_FUNC, "rx_soft_errors"},
436     { STATS_OFFSET32(rx_hw_csum_errors),
437                 4, STATS_FLAGS_FUNC, "rx_hw_csum_errors"},
438     { STATS_OFFSET32(rx_ofld_frames_csum_ip),
439                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_ip"},
440     { STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
441                 4, STATS_FLAGS_FUNC, "rx_ofld_frames_csum_tcp_udp"},
442     { STATS_OFFSET32(rx_budget_reached),
443                 4, STATS_FLAGS_FUNC, "rx_budget_reached"},
444     { STATS_OFFSET32(tx_pkts),
445                 4, STATS_FLAGS_FUNC, "tx_pkts"},
446     { STATS_OFFSET32(tx_soft_errors),
447                 4, STATS_FLAGS_FUNC, "tx_soft_errors"},
448     { STATS_OFFSET32(tx_ofld_frames_csum_ip),
449                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_ip"},
450     { STATS_OFFSET32(tx_ofld_frames_csum_tcp),
451                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_tcp"},
452     { STATS_OFFSET32(tx_ofld_frames_csum_udp),
453                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_csum_udp"},
454     { STATS_OFFSET32(tx_ofld_frames_lso),
455                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso"},
456     { STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
457                 4, STATS_FLAGS_FUNC, "tx_ofld_frames_lso_hdr_splits"},
458     { STATS_OFFSET32(tx_encap_failures),
459                 4, STATS_FLAGS_FUNC, "tx_encap_failures"},
460     { STATS_OFFSET32(tx_hw_queue_full),
461                 4, STATS_FLAGS_FUNC, "tx_hw_queue_full"},
462     { STATS_OFFSET32(tx_hw_max_queue_depth),
463                 4, STATS_FLAGS_FUNC, "tx_hw_max_queue_depth"},
464     { STATS_OFFSET32(tx_dma_mapping_failure),
465                 4, STATS_FLAGS_FUNC, "tx_dma_mapping_failure"},
466     { STATS_OFFSET32(tx_max_drbr_queue_depth),
467                 4, STATS_FLAGS_FUNC, "tx_max_drbr_queue_depth"},
468     { STATS_OFFSET32(tx_window_violation_std),
469                 4, STATS_FLAGS_FUNC, "tx_window_violation_std"},
470     { STATS_OFFSET32(tx_window_violation_tso),
471                 4, STATS_FLAGS_FUNC, "tx_window_violation_tso"},
472     { STATS_OFFSET32(tx_chain_lost_mbuf),
473                 4, STATS_FLAGS_FUNC, "tx_chain_lost_mbuf"},
474     { STATS_OFFSET32(tx_frames_deferred),
475                 4, STATS_FLAGS_FUNC, "tx_frames_deferred"},
476     { STATS_OFFSET32(tx_queue_xoff),
477                 4, STATS_FLAGS_FUNC, "tx_queue_xoff"},
478     { STATS_OFFSET32(mbuf_defrag_attempts),
479                 4, STATS_FLAGS_FUNC, "mbuf_defrag_attempts"},
480     { STATS_OFFSET32(mbuf_defrag_failures),
481                 4, STATS_FLAGS_FUNC, "mbuf_defrag_failures"},
482     { STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
483                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_alloc_failed"},
484     { STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
485                 4, STATS_FLAGS_FUNC, "mbuf_rx_bd_mapping_failed"},
486     { STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
487                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_alloc_failed"},
488     { STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
489                 4, STATS_FLAGS_FUNC, "mbuf_rx_tpa_mapping_failed"},
490     { STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
491                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_alloc_failed"},
492     { STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
493                 4, STATS_FLAGS_FUNC, "mbuf_rx_sge_mapping_failed"},
494     { STATS_OFFSET32(mbuf_alloc_tx),
495                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tx"},
496     { STATS_OFFSET32(mbuf_alloc_rx),
497                 4, STATS_FLAGS_FUNC, "mbuf_alloc_rx"},
498     { STATS_OFFSET32(mbuf_alloc_sge),
499                 4, STATS_FLAGS_FUNC, "mbuf_alloc_sge"},
500     { STATS_OFFSET32(mbuf_alloc_tpa),
501                 4, STATS_FLAGS_FUNC, "mbuf_alloc_tpa"}
502 };
503
504 static const struct {
505     uint32_t offset;
506     uint32_t size;
507     char string[STAT_NAME_LEN];
508 } bxe_eth_q_stats_arr[] = {
509     { Q_STATS_OFFSET32(total_bytes_received_hi),
510                 8, "rx_bytes" },
511     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
512                 8, "rx_ucast_packets" },
513     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
514                 8, "rx_mcast_packets" },
515     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
516                 8, "rx_bcast_packets" },
517     { Q_STATS_OFFSET32(no_buff_discard_hi),
518                 8, "rx_discards" },
519     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
520                 8, "tx_bytes" },
521     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
522                 8, "tx_ucast_packets" },
523     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
524                 8, "tx_mcast_packets" },
525     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
526                 8, "tx_bcast_packets" },
527     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
528                 8, "tpa_aggregations" },
529     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
530                 8, "tpa_aggregated_frames"},
531     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
532                 8, "tpa_bytes"},
533     { Q_STATS_OFFSET32(rx_calls),
534                 4, "rx_calls"},
535     { Q_STATS_OFFSET32(rx_pkts),
536                 4, "rx_pkts"},
537     { Q_STATS_OFFSET32(rx_tpa_pkts),
538                 4, "rx_tpa_pkts"},
539     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
540                 4, "rx_erroneous_jumbo_sge_pkts"},
541     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
542                 4, "rx_bxe_service_rxsgl"},
543     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
544                 4, "rx_jumbo_sge_pkts"},
545     { Q_STATS_OFFSET32(rx_soft_errors),
546                 4, "rx_soft_errors"},
547     { Q_STATS_OFFSET32(rx_hw_csum_errors),
548                 4, "rx_hw_csum_errors"},
549     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
550                 4, "rx_ofld_frames_csum_ip"},
551     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
552                 4, "rx_ofld_frames_csum_tcp_udp"},
553     { Q_STATS_OFFSET32(rx_budget_reached),
554                 4, "rx_budget_reached"},
555     { Q_STATS_OFFSET32(tx_pkts),
556                 4, "tx_pkts"},
557     { Q_STATS_OFFSET32(tx_soft_errors),
558                 4, "tx_soft_errors"},
559     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
560                 4, "tx_ofld_frames_csum_ip"},
561     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
562                 4, "tx_ofld_frames_csum_tcp"},
563     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
564                 4, "tx_ofld_frames_csum_udp"},
565     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
566                 4, "tx_ofld_frames_lso"},
567     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
568                 4, "tx_ofld_frames_lso_hdr_splits"},
569     { Q_STATS_OFFSET32(tx_encap_failures),
570                 4, "tx_encap_failures"},
571     { Q_STATS_OFFSET32(tx_hw_queue_full),
572                 4, "tx_hw_queue_full"},
573     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
574                 4, "tx_hw_max_queue_depth"},
575     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
576                 4, "tx_dma_mapping_failure"},
577     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
578                 4, "tx_max_drbr_queue_depth"},
579     { Q_STATS_OFFSET32(tx_window_violation_std),
580                 4, "tx_window_violation_std"},
581     { Q_STATS_OFFSET32(tx_window_violation_tso),
582                 4, "tx_window_violation_tso"},
583     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
584                 4, "tx_chain_lost_mbuf"},
585     { Q_STATS_OFFSET32(tx_frames_deferred),
586                 4, "tx_frames_deferred"},
587     { Q_STATS_OFFSET32(tx_queue_xoff),
588                 4, "tx_queue_xoff"},
589     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
590                 4, "mbuf_defrag_attempts"},
591     { Q_STATS_OFFSET32(mbuf_defrag_failures),
592                 4, "mbuf_defrag_failures"},
593     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
594                 4, "mbuf_rx_bd_alloc_failed"},
595     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
596                 4, "mbuf_rx_bd_mapping_failed"},
597     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
598                 4, "mbuf_rx_tpa_alloc_failed"},
599     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
600                 4, "mbuf_rx_tpa_mapping_failed"},
601     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
602                 4, "mbuf_rx_sge_alloc_failed"},
603     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
604                 4, "mbuf_rx_sge_mapping_failed"},
605     { Q_STATS_OFFSET32(mbuf_alloc_tx),
606                 4, "mbuf_alloc_tx"},
607     { Q_STATS_OFFSET32(mbuf_alloc_rx),
608                 4, "mbuf_alloc_rx"},
609     { Q_STATS_OFFSET32(mbuf_alloc_sge),
610                 4, "mbuf_alloc_sge"},
611     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
612                 4, "mbuf_alloc_tpa"}
613 };
614
615 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
616 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
617
618
619 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
620                                  uint8_t          read_cfg,
621                                  uint8_t          cmng_type);
622 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
623 static void    storm_memset_cmng(struct bxe_softc *sc,
624                                  struct cmng_init *cmng,
625                                  uint8_t          port);
626 static void    bxe_set_reset_global(struct bxe_softc *sc);
627 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
628 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
629                                  int              engine);
630 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
631 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
632                                    uint8_t          *global,
633                                    uint8_t          print);
634 static void    bxe_int_disable(struct bxe_softc *sc);
635 static int     bxe_release_leader_lock(struct bxe_softc *sc);
636 static void    bxe_pf_disable(struct bxe_softc *sc);
637 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
638 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
639                                       struct bxe_fastpath *fp,
640                                       uint16_t            rx_bd_prod,
641                                       uint16_t            rx_cq_prod,
642                                       uint16_t            rx_sge_prod);
643 static void    bxe_link_report_locked(struct bxe_softc *sc);
644 static void    bxe_link_report(struct bxe_softc *sc);
645 static void    bxe_link_status_update(struct bxe_softc *sc);
646 static void    bxe_periodic_callout_func(void *xsc);
647 static void    bxe_periodic_start(struct bxe_softc *sc);
648 static void    bxe_periodic_stop(struct bxe_softc *sc);
649 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
650                                     uint16_t prev_index,
651                                     uint16_t index);
652 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
653                                      int                 queue);
654 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
655                                      uint16_t            index);
656 static uint8_t bxe_txeof(struct bxe_softc *sc,
657                          struct bxe_fastpath *fp);
658 static void    bxe_task_fp(struct bxe_fastpath *fp);
659 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
660                                      struct mbuf      *m,
661                                      uint8_t          contents);
662 static int     bxe_alloc_mem(struct bxe_softc *sc);
663 static void    bxe_free_mem(struct bxe_softc *sc);
664 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
665 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
666 static int     bxe_interrupt_attach(struct bxe_softc *sc);
667 static void    bxe_interrupt_detach(struct bxe_softc *sc);
668 static void    bxe_set_rx_mode(struct bxe_softc *sc);
669 static int     bxe_init_locked(struct bxe_softc *sc);
670 static int     bxe_stop_locked(struct bxe_softc *sc);
671 static __noinline int bxe_nic_load(struct bxe_softc *sc,
672                                    int              load_mode);
673 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
674                                      uint32_t         unload_mode,
675                                      uint8_t          keep_link);
676
677 static void bxe_handle_sp_tq(void *context, int pending);
678 static void bxe_handle_fp_tq(void *context, int pending);
679
680 static int bxe_add_cdev(struct bxe_softc *sc);
681 static void bxe_del_cdev(struct bxe_softc *sc);
682 static int bxe_grc_dump(struct bxe_softc *sc);
683
684 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
685 uint32_t
686 calc_crc32(uint8_t  *crc32_packet,
687            uint32_t crc32_length,
688            uint32_t crc32_seed,
689            uint8_t  complement)
690 {
691    uint32_t byte         = 0;
692    uint32_t bit          = 0;
693    uint8_t  msb          = 0;
694    uint32_t temp         = 0;
695    uint32_t shft         = 0;
696    uint8_t  current_byte = 0;
697    uint32_t crc32_result = crc32_seed;
698    const uint32_t CRC32_POLY = 0x1edc6f41;
699
700    if ((crc32_packet == NULL) ||
701        (crc32_length == 0) ||
702        ((crc32_length % 8) != 0))
703     {
704         return (crc32_result);
705     }
706
707     for (byte = 0; byte < crc32_length; byte = byte + 1)
708     {
709         current_byte = crc32_packet[byte];
710         for (bit = 0; bit < 8; bit = bit + 1)
711         {
712             /* msb = crc32_result[31]; */
713             msb = (uint8_t)(crc32_result >> 31);
714
715             crc32_result = crc32_result << 1;
716
717             /* it (msb != current_byte[bit]) */
718             if (msb != (0x1 & (current_byte >> bit)))
719             {
720                 crc32_result = crc32_result ^ CRC32_POLY;
721                 /* crc32_result[0] = 1 */
722                 crc32_result |= 1;
723             }
724         }
725     }
726
727     /* Last step is to:
728      * 1. "mirror" every bit
729      * 2. swap the 4 bytes
730      * 3. complement each bit
731      */
732
733     /* Mirror */
734     temp = crc32_result;
735     shft = sizeof(crc32_result) * 8 - 1;
736
737     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
738     {
739         temp <<= 1;
740         temp |= crc32_result & 1;
741         shft-- ;
742     }
743
744     /* temp[31-bit] = crc32_result[bit] */
745     temp <<= shft;
746
747     /* Swap */
748     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
749     {
750         uint32_t t0, t1, t2, t3;
751         t0 = (0x000000ff & (temp >> 24));
752         t1 = (0x0000ff00 & (temp >> 8));
753         t2 = (0x00ff0000 & (temp << 8));
754         t3 = (0xff000000 & (temp << 24));
755         crc32_result = t0 | t1 | t2 | t3;
756     }
757
758     /* Complement */
759     if (complement)
760     {
761         crc32_result = ~crc32_result;
762     }
763
764     return (crc32_result);
765 }
766
767 int
768 bxe_test_bit(int                    nr,
769              volatile unsigned long *addr)
770 {
771     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
772 }
773
774 void
775 bxe_set_bit(unsigned int           nr,
776             volatile unsigned long *addr)
777 {
778     atomic_set_acq_long(addr, (1 << nr));
779 }
780
781 void
782 bxe_clear_bit(int                    nr,
783               volatile unsigned long *addr)
784 {
785     atomic_clear_acq_long(addr, (1 << nr));
786 }
787
788 int
789 bxe_test_and_set_bit(int                    nr,
790                        volatile unsigned long *addr)
791 {
792     unsigned long x;
793     nr = (1 << nr);
794     do {
795         x = *addr;
796     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
797     // if (x & nr) bit_was_set; else bit_was_not_set;
798     return (x & nr);
799 }
800
801 int
802 bxe_test_and_clear_bit(int                    nr,
803                        volatile unsigned long *addr)
804 {
805     unsigned long x;
806     nr = (1 << nr);
807     do {
808         x = *addr;
809     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
810     // if (x & nr) bit_was_set; else bit_was_not_set;
811     return (x & nr);
812 }
813
814 int
815 bxe_cmpxchg(volatile int *addr,
816             int          old,
817             int          new)
818 {
819     int x;
820     do {
821         x = *addr;
822     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
823     return (x);
824 }
825
826 /*
827  * Get DMA memory from the OS.
828  *
829  * Validates that the OS has provided DMA buffers in response to a
830  * bus_dmamap_load call and saves the physical address of those buffers.
831  * When the callback is used the OS will return 0 for the mapping function
832  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
833  * failures back to the caller.
834  *
835  * Returns:
836  *   Nothing.
837  */
838 static void
839 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
840 {
841     struct bxe_dma *dma = arg;
842
843     if (error) {
844         dma->paddr = 0;
845         dma->nseg  = 0;
846         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
847     } else {
848         dma->paddr = segs->ds_addr;
849         dma->nseg  = nseg;
850     }
851 }
852
853 /*
854  * Allocate a block of memory and map it for DMA. No partial completions
855  * allowed and release any resources acquired if we can't acquire all
856  * resources.
857  *
858  * Returns:
859  *   0 = Success, !0 = Failure
860  */
861 int
862 bxe_dma_alloc(struct bxe_softc *sc,
863               bus_size_t       size,
864               struct bxe_dma   *dma,
865               const char       *msg)
866 {
867     int rc;
868
869     if (dma->size > 0) {
870         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
871               (unsigned long)dma->size);
872         return (1);
873     }
874
875     memset(dma, 0, sizeof(*dma)); /* sanity */
876     dma->sc   = sc;
877     dma->size = size;
878     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
879
880     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
881                             BCM_PAGE_SIZE,      /* alignment */
882                             0,                  /* boundary limit */
883                             BUS_SPACE_MAXADDR,  /* restricted low */
884                             BUS_SPACE_MAXADDR,  /* restricted hi */
885                             NULL,               /* addr filter() */
886                             NULL,               /* addr filter() arg */
887                             size,               /* max map size */
888                             1,                  /* num discontinuous */
889                             size,               /* max seg size */
890                             BUS_DMA_ALLOCNOW,   /* flags */
891                             NULL,               /* lock() */
892                             NULL,               /* lock() arg */
893                             &dma->tag);         /* returned dma tag */
894     if (rc != 0) {
895         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
896         memset(dma, 0, sizeof(*dma));
897         return (1);
898     }
899
900     rc = bus_dmamem_alloc(dma->tag,
901                           (void **)&dma->vaddr,
902                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
903                           &dma->map);
904     if (rc != 0) {
905         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
906         bus_dma_tag_destroy(dma->tag);
907         memset(dma, 0, sizeof(*dma));
908         return (1);
909     }
910
911     rc = bus_dmamap_load(dma->tag,
912                          dma->map,
913                          dma->vaddr,
914                          size,
915                          bxe_dma_map_addr, /* BLOGD in here */
916                          dma,
917                          BUS_DMA_NOWAIT);
918     if (rc != 0) {
919         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
920         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
921         bus_dma_tag_destroy(dma->tag);
922         memset(dma, 0, sizeof(*dma));
923         return (1);
924     }
925
926     return (0);
927 }
928
929 void
930 bxe_dma_free(struct bxe_softc *sc,
931              struct bxe_dma   *dma)
932 {
933     if (dma->size > 0) {
934         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
935
936         bus_dmamap_sync(dma->tag, dma->map,
937                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
938         bus_dmamap_unload(dma->tag, dma->map);
939         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
940         bus_dma_tag_destroy(dma->tag);
941     }
942
943     memset(dma, 0, sizeof(*dma));
944 }
945
946 /*
947  * These indirect read and write routines are only during init.
948  * The locking is handled by the MCP.
949  */
950
951 void
952 bxe_reg_wr_ind(struct bxe_softc *sc,
953                uint32_t         addr,
954                uint32_t         val)
955 {
956     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
957     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
958     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
959 }
960
961 uint32_t
962 bxe_reg_rd_ind(struct bxe_softc *sc,
963                uint32_t         addr)
964 {
965     uint32_t val;
966
967     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
968     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
969     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
970
971     return (val);
972 }
973
974 static int
975 bxe_acquire_hw_lock(struct bxe_softc *sc,
976                     uint32_t         resource)
977 {
978     uint32_t lock_status;
979     uint32_t resource_bit = (1 << resource);
980     int func = SC_FUNC(sc);
981     uint32_t hw_lock_control_reg;
982     int cnt;
983
984     /* validate the resource is within range */
985     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
986         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
987             " resource_bit 0x%x\n", resource, resource_bit);
988         return (-1);
989     }
990
991     if (func <= 5) {
992         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
993     } else {
994         hw_lock_control_reg =
995                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
996     }
997
998     /* validate the resource is not already taken */
999     lock_status = REG_RD(sc, hw_lock_control_reg);
1000     if (lock_status & resource_bit) {
1001         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1002               resource, lock_status, resource_bit);
1003         return (-1);
1004     }
1005
1006     /* try every 5ms for 5 seconds */
1007     for (cnt = 0; cnt < 1000; cnt++) {
1008         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1009         lock_status = REG_RD(sc, hw_lock_control_reg);
1010         if (lock_status & resource_bit) {
1011             return (0);
1012         }
1013         DELAY(5000);
1014     }
1015
1016     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1017         resource, resource_bit);
1018     return (-1);
1019 }
1020
1021 static int
1022 bxe_release_hw_lock(struct bxe_softc *sc,
1023                     uint32_t         resource)
1024 {
1025     uint32_t lock_status;
1026     uint32_t resource_bit = (1 << resource);
1027     int func = SC_FUNC(sc);
1028     uint32_t hw_lock_control_reg;
1029
1030     /* validate the resource is within range */
1031     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1032         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1033             " resource_bit 0x%x\n", resource, resource_bit);
1034         return (-1);
1035     }
1036
1037     if (func <= 5) {
1038         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1039     } else {
1040         hw_lock_control_reg =
1041                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1042     }
1043
1044     /* validate the resource is currently taken */
1045     lock_status = REG_RD(sc, hw_lock_control_reg);
1046     if (!(lock_status & resource_bit)) {
1047         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1048               resource, lock_status, resource_bit);
1049         return (-1);
1050     }
1051
1052     REG_WR(sc, hw_lock_control_reg, resource_bit);
1053     return (0);
1054 }
1055 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1056 {
1057         BXE_PHY_LOCK(sc);
1058         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1059 }
1060
1061 static void bxe_release_phy_lock(struct bxe_softc *sc)
1062 {
1063         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1064         BXE_PHY_UNLOCK(sc);
1065 }
1066 /*
1067  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1068  * had we done things the other way around, if two pfs from the same port
1069  * would attempt to access nvram at the same time, we could run into a
1070  * scenario such as:
1071  * pf A takes the port lock.
1072  * pf B succeeds in taking the same lock since they are from the same port.
1073  * pf A takes the per pf misc lock. Performs eeprom access.
1074  * pf A finishes. Unlocks the per pf misc lock.
1075  * Pf B takes the lock and proceeds to perform it's own access.
1076  * pf A unlocks the per port lock, while pf B is still working (!).
1077  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1078  * access corrupted by pf B).*
1079  */
1080 static int
1081 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1082 {
1083     int port = SC_PORT(sc);
1084     int count, i;
1085     uint32_t val = 0;
1086
1087     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1088     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1089
1090     /* adjust timeout for emulation/FPGA */
1091     count = NVRAM_TIMEOUT_COUNT;
1092     if (CHIP_REV_IS_SLOW(sc)) {
1093         count *= 100;
1094     }
1095
1096     /* request access to nvram interface */
1097     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1098            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1099
1100     for (i = 0; i < count*10; i++) {
1101         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1102         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1103             break;
1104         }
1105
1106         DELAY(5);
1107     }
1108
1109     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1110         BLOGE(sc, "Cannot get access to nvram interface "
1111             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1112             port, val);
1113         return (-1);
1114     }
1115
1116     return (0);
1117 }
1118
1119 static int
1120 bxe_release_nvram_lock(struct bxe_softc *sc)
1121 {
1122     int port = SC_PORT(sc);
1123     int count, i;
1124     uint32_t val = 0;
1125
1126     /* adjust timeout for emulation/FPGA */
1127     count = NVRAM_TIMEOUT_COUNT;
1128     if (CHIP_REV_IS_SLOW(sc)) {
1129         count *= 100;
1130     }
1131
1132     /* relinquish nvram interface */
1133     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1134            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1135
1136     for (i = 0; i < count*10; i++) {
1137         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1138         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1139             break;
1140         }
1141
1142         DELAY(5);
1143     }
1144
1145     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1146         BLOGE(sc, "Cannot free access to nvram interface "
1147             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1148             port, val);
1149         return (-1);
1150     }
1151
1152     /* release HW lock: protect against other PFs in PF Direct Assignment */
1153     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1154
1155     return (0);
1156 }
1157
1158 static void
1159 bxe_enable_nvram_access(struct bxe_softc *sc)
1160 {
1161     uint32_t val;
1162
1163     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1164
1165     /* enable both bits, even on read */
1166     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1167            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1168 }
1169
1170 static void
1171 bxe_disable_nvram_access(struct bxe_softc *sc)
1172 {
1173     uint32_t val;
1174
1175     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1176
1177     /* disable both bits, even after read */
1178     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1179            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1180                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1181 }
1182
1183 static int
1184 bxe_nvram_read_dword(struct bxe_softc *sc,
1185                      uint32_t         offset,
1186                      uint32_t         *ret_val,
1187                      uint32_t         cmd_flags)
1188 {
1189     int count, i, rc;
1190     uint32_t val;
1191
1192     /* build the command word */
1193     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1194
1195     /* need to clear DONE bit separately */
1196     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1197
1198     /* address of the NVRAM to read from */
1199     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1200            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1201
1202     /* issue a read command */
1203     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1204
1205     /* adjust timeout for emulation/FPGA */
1206     count = NVRAM_TIMEOUT_COUNT;
1207     if (CHIP_REV_IS_SLOW(sc)) {
1208         count *= 100;
1209     }
1210
1211     /* wait for completion */
1212     *ret_val = 0;
1213     rc = -1;
1214     for (i = 0; i < count; i++) {
1215         DELAY(5);
1216         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1217
1218         if (val & MCPR_NVM_COMMAND_DONE) {
1219             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1220             /* we read nvram data in cpu order
1221              * but ethtool sees it as an array of bytes
1222              * converting to big-endian will do the work
1223              */
1224             *ret_val = htobe32(val);
1225             rc = 0;
1226             break;
1227         }
1228     }
1229
1230     if (rc == -1) {
1231         BLOGE(sc, "nvram read timeout expired "
1232             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1233             offset, cmd_flags, val);
1234     }
1235
1236     return (rc);
1237 }
1238
1239 static int
1240 bxe_nvram_read(struct bxe_softc *sc,
1241                uint32_t         offset,
1242                uint8_t          *ret_buf,
1243                int              buf_size)
1244 {
1245     uint32_t cmd_flags;
1246     uint32_t val;
1247     int rc;
1248
1249     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1250         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1251               offset, buf_size);
1252         return (-1);
1253     }
1254
1255     if ((offset + buf_size) > sc->devinfo.flash_size) {
1256         BLOGE(sc, "Invalid parameter, "
1257                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1258               offset, buf_size, sc->devinfo.flash_size);
1259         return (-1);
1260     }
1261
1262     /* request access to nvram interface */
1263     rc = bxe_acquire_nvram_lock(sc);
1264     if (rc) {
1265         return (rc);
1266     }
1267
1268     /* enable access to nvram interface */
1269     bxe_enable_nvram_access(sc);
1270
1271     /* read the first word(s) */
1272     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1273     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1274         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1275         memcpy(ret_buf, &val, 4);
1276
1277         /* advance to the next dword */
1278         offset += sizeof(uint32_t);
1279         ret_buf += sizeof(uint32_t);
1280         buf_size -= sizeof(uint32_t);
1281         cmd_flags = 0;
1282     }
1283
1284     if (rc == 0) {
1285         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1286         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1287         memcpy(ret_buf, &val, 4);
1288     }
1289
1290     /* disable access to nvram interface */
1291     bxe_disable_nvram_access(sc);
1292     bxe_release_nvram_lock(sc);
1293
1294     return (rc);
1295 }
1296
1297 static int
1298 bxe_nvram_write_dword(struct bxe_softc *sc,
1299                       uint32_t         offset,
1300                       uint32_t         val,
1301                       uint32_t         cmd_flags)
1302 {
1303     int count, i, rc;
1304
1305     /* build the command word */
1306     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1307
1308     /* need to clear DONE bit separately */
1309     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1310
1311     /* write the data */
1312     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1313
1314     /* address of the NVRAM to write to */
1315     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1316            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1317
1318     /* issue the write command */
1319     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1320
1321     /* adjust timeout for emulation/FPGA */
1322     count = NVRAM_TIMEOUT_COUNT;
1323     if (CHIP_REV_IS_SLOW(sc)) {
1324         count *= 100;
1325     }
1326
1327     /* wait for completion */
1328     rc = -1;
1329     for (i = 0; i < count; i++) {
1330         DELAY(5);
1331         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1332         if (val & MCPR_NVM_COMMAND_DONE) {
1333             rc = 0;
1334             break;
1335         }
1336     }
1337
1338     if (rc == -1) {
1339         BLOGE(sc, "nvram write timeout expired "
1340             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1341             offset, cmd_flags, val);
1342     }
1343
1344     return (rc);
1345 }
1346
1347 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1348
1349 static int
1350 bxe_nvram_write1(struct bxe_softc *sc,
1351                  uint32_t         offset,
1352                  uint8_t          *data_buf,
1353                  int              buf_size)
1354 {
1355     uint32_t cmd_flags;
1356     uint32_t align_offset;
1357     uint32_t val;
1358     int rc;
1359
1360     if ((offset + buf_size) > sc->devinfo.flash_size) {
1361         BLOGE(sc, "Invalid parameter, "
1362                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1363               offset, buf_size, sc->devinfo.flash_size);
1364         return (-1);
1365     }
1366
1367     /* request access to nvram interface */
1368     rc = bxe_acquire_nvram_lock(sc);
1369     if (rc) {
1370         return (rc);
1371     }
1372
1373     /* enable access to nvram interface */
1374     bxe_enable_nvram_access(sc);
1375
1376     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1377     align_offset = (offset & ~0x03);
1378     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1379
1380     if (rc == 0) {
1381         val &= ~(0xff << BYTE_OFFSET(offset));
1382         val |= (*data_buf << BYTE_OFFSET(offset));
1383
1384         /* nvram data is returned as an array of bytes
1385          * convert it back to cpu order
1386          */
1387         val = be32toh(val);
1388
1389         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1390     }
1391
1392     /* disable access to nvram interface */
1393     bxe_disable_nvram_access(sc);
1394     bxe_release_nvram_lock(sc);
1395
1396     return (rc);
1397 }
1398
1399 static int
1400 bxe_nvram_write(struct bxe_softc *sc,
1401                 uint32_t         offset,
1402                 uint8_t          *data_buf,
1403                 int              buf_size)
1404 {
1405     uint32_t cmd_flags;
1406     uint32_t val;
1407     uint32_t written_so_far;
1408     int rc;
1409
1410     if (buf_size == 1) {
1411         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1412     }
1413
1414     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1415         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1416               offset, buf_size);
1417         return (-1);
1418     }
1419
1420     if (buf_size == 0) {
1421         return (0); /* nothing to do */
1422     }
1423
1424     if ((offset + buf_size) > sc->devinfo.flash_size) {
1425         BLOGE(sc, "Invalid parameter, "
1426                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1427               offset, buf_size, sc->devinfo.flash_size);
1428         return (-1);
1429     }
1430
1431     /* request access to nvram interface */
1432     rc = bxe_acquire_nvram_lock(sc);
1433     if (rc) {
1434         return (rc);
1435     }
1436
1437     /* enable access to nvram interface */
1438     bxe_enable_nvram_access(sc);
1439
1440     written_so_far = 0;
1441     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1442     while ((written_so_far < buf_size) && (rc == 0)) {
1443         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1444             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1445         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1446             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1447         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1448             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1449         }
1450
1451         memcpy(&val, data_buf, 4);
1452
1453         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1454
1455         /* advance to the next dword */
1456         offset += sizeof(uint32_t);
1457         data_buf += sizeof(uint32_t);
1458         written_so_far += sizeof(uint32_t);
1459         cmd_flags = 0;
1460     }
1461
1462     /* disable access to nvram interface */
1463     bxe_disable_nvram_access(sc);
1464     bxe_release_nvram_lock(sc);
1465
1466     return (rc);
1467 }
1468
1469 /* copy command into DMAE command memory and set DMAE command Go */
1470 void
1471 bxe_post_dmae(struct bxe_softc    *sc,
1472               struct dmae_command *dmae,
1473               int                 idx)
1474 {
1475     uint32_t cmd_offset;
1476     int i;
1477
1478     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_command) * idx));
1479     for (i = 0; i < ((sizeof(struct dmae_command) / 4)); i++) {
1480         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1481     }
1482
1483     REG_WR(sc, dmae_reg_go_c[idx], 1);
1484 }
1485
1486 uint32_t
1487 bxe_dmae_opcode_add_comp(uint32_t opcode,
1488                          uint8_t  comp_type)
1489 {
1490     return (opcode | ((comp_type << DMAE_COMMAND_C_DST_SHIFT) |
1491                       DMAE_COMMAND_C_TYPE_ENABLE));
1492 }
1493
1494 uint32_t
1495 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1496 {
1497     return (opcode & ~DMAE_COMMAND_SRC_RESET);
1498 }
1499
1500 uint32_t
1501 bxe_dmae_opcode(struct bxe_softc *sc,
1502                 uint8_t          src_type,
1503                 uint8_t          dst_type,
1504                 uint8_t          with_comp,
1505                 uint8_t          comp_type)
1506 {
1507     uint32_t opcode = 0;
1508
1509     opcode |= ((src_type << DMAE_COMMAND_SRC_SHIFT) |
1510                (dst_type << DMAE_COMMAND_DST_SHIFT));
1511
1512     opcode |= (DMAE_COMMAND_SRC_RESET | DMAE_COMMAND_DST_RESET);
1513
1514     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1515
1516     opcode |= ((SC_VN(sc) << DMAE_COMMAND_E1HVN_SHIFT) |
1517                (SC_VN(sc) << DMAE_COMMAND_DST_VN_SHIFT));
1518
1519     opcode |= (DMAE_COM_SET_ERR << DMAE_COMMAND_ERR_POLICY_SHIFT);
1520
1521 #ifdef __BIG_ENDIAN
1522     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1523 #else
1524     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1525 #endif
1526
1527     if (with_comp) {
1528         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1529     }
1530
1531     return (opcode);
1532 }
1533
1534 static void
1535 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1536                         struct dmae_command *dmae,
1537                         uint8_t             src_type,
1538                         uint8_t             dst_type)
1539 {
1540     memset(dmae, 0, sizeof(struct dmae_command));
1541
1542     /* set the opcode */
1543     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1544                                    TRUE, DMAE_COMP_PCI);
1545
1546     /* fill in the completion parameters */
1547     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1548     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1549     dmae->comp_val     = DMAE_COMP_VAL;
1550 }
1551
1552 /* issue a DMAE command over the init channel and wait for completion */
1553 static int
1554 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1555                          struct dmae_command *dmae)
1556 {
1557     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1558     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1559
1560     BXE_DMAE_LOCK(sc);
1561
1562     /* reset completion */
1563     *wb_comp = 0;
1564
1565     /* post the command on the channel used for initializations */
1566     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1567
1568     /* wait for completion */
1569     DELAY(5);
1570
1571     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1572         if (!timeout ||
1573             (sc->recovery_state != BXE_RECOVERY_DONE &&
1574              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1575             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1576                 *wb_comp, sc->recovery_state);
1577             BXE_DMAE_UNLOCK(sc);
1578             return (DMAE_TIMEOUT);
1579         }
1580
1581         timeout--;
1582         DELAY(50);
1583     }
1584
1585     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1586         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1587                 *wb_comp, sc->recovery_state);
1588         BXE_DMAE_UNLOCK(sc);
1589         return (DMAE_PCI_ERROR);
1590     }
1591
1592     BXE_DMAE_UNLOCK(sc);
1593     return (0);
1594 }
1595
1596 void
1597 bxe_read_dmae(struct bxe_softc *sc,
1598               uint32_t         src_addr,
1599               uint32_t         len32)
1600 {
1601     struct dmae_command dmae;
1602     uint32_t *data;
1603     int i, rc;
1604
1605     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1606
1607     if (!sc->dmae_ready) {
1608         data = BXE_SP(sc, wb_data[0]);
1609
1610         for (i = 0; i < len32; i++) {
1611             data[i] = (CHIP_IS_E1(sc)) ?
1612                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1613                           REG_RD(sc, (src_addr + (i * 4)));
1614         }
1615
1616         return;
1617     }
1618
1619     /* set opcode and fixed command fields */
1620     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1621
1622     /* fill in addresses and len */
1623     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1624     dmae.src_addr_hi = 0;
1625     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1626     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1627     dmae.len         = len32;
1628
1629     /* issue the command and wait for completion */
1630     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1631         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1632     };
1633 }
1634
1635 void
1636 bxe_write_dmae(struct bxe_softc *sc,
1637                bus_addr_t       dma_addr,
1638                uint32_t         dst_addr,
1639                uint32_t         len32)
1640 {
1641     struct dmae_command dmae;
1642     int rc;
1643
1644     if (!sc->dmae_ready) {
1645         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1646
1647         if (CHIP_IS_E1(sc)) {
1648             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1649         } else {
1650             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1651         }
1652
1653         return;
1654     }
1655
1656     /* set opcode and fixed command fields */
1657     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1658
1659     /* fill in addresses and len */
1660     dmae.src_addr_lo = U64_LO(dma_addr);
1661     dmae.src_addr_hi = U64_HI(dma_addr);
1662     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1663     dmae.dst_addr_hi = 0;
1664     dmae.len         = len32;
1665
1666     /* issue the command and wait for completion */
1667     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1668         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1669     }
1670 }
1671
1672 void
1673 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1674                         bus_addr_t       phys_addr,
1675                         uint32_t         addr,
1676                         uint32_t         len)
1677 {
1678     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1679     int offset = 0;
1680
1681     while (len > dmae_wr_max) {
1682         bxe_write_dmae(sc,
1683                        (phys_addr + offset), /* src DMA address */
1684                        (addr + offset),      /* dst GRC address */
1685                        dmae_wr_max);
1686         offset += (dmae_wr_max * 4);
1687         len -= dmae_wr_max;
1688     }
1689
1690     bxe_write_dmae(sc,
1691                    (phys_addr + offset), /* src DMA address */
1692                    (addr + offset),      /* dst GRC address */
1693                    len);
1694 }
1695
1696 void
1697 bxe_set_ctx_validation(struct bxe_softc   *sc,
1698                        struct eth_context *cxt,
1699                        uint32_t           cid)
1700 {
1701     /* ustorm cxt validation */
1702     cxt->ustorm_ag_context.cdu_usage =
1703         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1704             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1705     /* xcontext validation */
1706     cxt->xstorm_ag_context.cdu_reserved =
1707         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1708             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1709 }
1710
1711 static void
1712 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1713                             uint8_t          port,
1714                             uint8_t          fw_sb_id,
1715                             uint8_t          sb_index,
1716                             uint8_t          ticks)
1717 {
1718     uint32_t addr =
1719         (BAR_CSTRORM_INTMEM +
1720          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1721
1722     REG_WR8(sc, addr, ticks);
1723
1724     BLOGD(sc, DBG_LOAD,
1725           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1726           port, fw_sb_id, sb_index, ticks);
1727 }
1728
1729 static void
1730 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1731                             uint8_t          port,
1732                             uint16_t         fw_sb_id,
1733                             uint8_t          sb_index,
1734                             uint8_t          disable)
1735 {
1736     uint32_t enable_flag =
1737         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1738     uint32_t addr =
1739         (BAR_CSTRORM_INTMEM +
1740          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1741     uint8_t flags;
1742
1743     /* clear and set */
1744     flags = REG_RD8(sc, addr);
1745     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1746     flags |= enable_flag;
1747     REG_WR8(sc, addr, flags);
1748
1749     BLOGD(sc, DBG_LOAD,
1750           "port %d fw_sb_id %d sb_index %d disable %d\n",
1751           port, fw_sb_id, sb_index, disable);
1752 }
1753
1754 void
1755 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1756                              uint8_t          fw_sb_id,
1757                              uint8_t          sb_index,
1758                              uint8_t          disable,
1759                              uint16_t         usec)
1760 {
1761     int port = SC_PORT(sc);
1762     uint8_t ticks = (usec / 4); /* XXX ??? */
1763
1764     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1765
1766     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1767     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1768 }
1769
1770 void
1771 elink_cb_udelay(struct bxe_softc *sc,
1772                 uint32_t         usecs)
1773 {
1774     DELAY(usecs);
1775 }
1776
1777 uint32_t
1778 elink_cb_reg_read(struct bxe_softc *sc,
1779                   uint32_t         reg_addr)
1780 {
1781     return (REG_RD(sc, reg_addr));
1782 }
1783
1784 void
1785 elink_cb_reg_write(struct bxe_softc *sc,
1786                    uint32_t         reg_addr,
1787                    uint32_t         val)
1788 {
1789     REG_WR(sc, reg_addr, val);
1790 }
1791
1792 void
1793 elink_cb_reg_wb_write(struct bxe_softc *sc,
1794                       uint32_t         offset,
1795                       uint32_t         *wb_write,
1796                       uint16_t         len)
1797 {
1798     REG_WR_DMAE(sc, offset, wb_write, len);
1799 }
1800
1801 void
1802 elink_cb_reg_wb_read(struct bxe_softc *sc,
1803                      uint32_t         offset,
1804                      uint32_t         *wb_write,
1805                      uint16_t         len)
1806 {
1807     REG_RD_DMAE(sc, offset, wb_write, len);
1808 }
1809
1810 uint8_t
1811 elink_cb_path_id(struct bxe_softc *sc)
1812 {
1813     return (SC_PATH(sc));
1814 }
1815
1816 void
1817 elink_cb_event_log(struct bxe_softc     *sc,
1818                    const elink_log_id_t elink_log_id,
1819                    ...)
1820 {
1821     /* XXX */
1822     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1823 }
1824
1825 static int
1826 bxe_set_spio(struct bxe_softc *sc,
1827              int              spio,
1828              uint32_t         mode)
1829 {
1830     uint32_t spio_reg;
1831
1832     /* Only 2 SPIOs are configurable */
1833     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1834         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1835         return (-1);
1836     }
1837
1838     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1839
1840     /* read SPIO and mask except the float bits */
1841     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1842
1843     switch (mode) {
1844     case MISC_SPIO_OUTPUT_LOW:
1845         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1846         /* clear FLOAT and set CLR */
1847         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1848         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1849         break;
1850
1851     case MISC_SPIO_OUTPUT_HIGH:
1852         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1853         /* clear FLOAT and set SET */
1854         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1855         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1856         break;
1857
1858     case MISC_SPIO_INPUT_HI_Z:
1859         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1860         /* set FLOAT */
1861         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1862         break;
1863
1864     default:
1865         break;
1866     }
1867
1868     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1869     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1870
1871     return (0);
1872 }
1873
1874 static int
1875 bxe_gpio_read(struct bxe_softc *sc,
1876               int              gpio_num,
1877               uint8_t          port)
1878 {
1879     /* The GPIO should be swapped if swap register is set and active */
1880     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1881                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1882     int gpio_shift = (gpio_num +
1883                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1884     uint32_t gpio_mask = (1 << gpio_shift);
1885     uint32_t gpio_reg;
1886
1887     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1888         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1889             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1890             gpio_mask);
1891         return (-1);
1892     }
1893
1894     /* read GPIO value */
1895     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1896
1897     /* get the requested pin value */
1898     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1899 }
1900
1901 static int
1902 bxe_gpio_write(struct bxe_softc *sc,
1903                int              gpio_num,
1904                uint32_t         mode,
1905                uint8_t          port)
1906 {
1907     /* The GPIO should be swapped if swap register is set and active */
1908     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1909                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1910     int gpio_shift = (gpio_num +
1911                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1912     uint32_t gpio_mask = (1 << gpio_shift);
1913     uint32_t gpio_reg;
1914
1915     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1916         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1917             " gpio_shift %d gpio_mask 0x%x\n",
1918             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1919         return (-1);
1920     }
1921
1922     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1923
1924     /* read GPIO and mask except the float bits */
1925     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1926
1927     switch (mode) {
1928     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1929         BLOGD(sc, DBG_PHY,
1930               "Set GPIO %d (shift %d) -> output low\n",
1931               gpio_num, gpio_shift);
1932         /* clear FLOAT and set CLR */
1933         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1934         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1935         break;
1936
1937     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1938         BLOGD(sc, DBG_PHY,
1939               "Set GPIO %d (shift %d) -> output high\n",
1940               gpio_num, gpio_shift);
1941         /* clear FLOAT and set SET */
1942         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1943         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1944         break;
1945
1946     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1947         BLOGD(sc, DBG_PHY,
1948               "Set GPIO %d (shift %d) -> input\n",
1949               gpio_num, gpio_shift);
1950         /* set FLOAT */
1951         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1952         break;
1953
1954     default:
1955         break;
1956     }
1957
1958     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1959     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1960
1961     return (0);
1962 }
1963
1964 static int
1965 bxe_gpio_mult_write(struct bxe_softc *sc,
1966                     uint8_t          pins,
1967                     uint32_t         mode)
1968 {
1969     uint32_t gpio_reg;
1970
1971     /* any port swapping should be handled by caller */
1972
1973     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1974
1975     /* read GPIO and mask except the float bits */
1976     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1977     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1978     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1979     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1980
1981     switch (mode) {
1982     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1983         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
1984         /* set CLR */
1985         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
1986         break;
1987
1988     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1989         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
1990         /* set SET */
1991         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
1992         break;
1993
1994     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1995         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
1996         /* set FLOAT */
1997         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1998         break;
1999
2000     default:
2001         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2002             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2003         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2004         return (-1);
2005     }
2006
2007     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2008     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2009
2010     return (0);
2011 }
2012
2013 static int
2014 bxe_gpio_int_write(struct bxe_softc *sc,
2015                    int              gpio_num,
2016                    uint32_t         mode,
2017                    uint8_t          port)
2018 {
2019     /* The GPIO should be swapped if swap register is set and active */
2020     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2021                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2022     int gpio_shift = (gpio_num +
2023                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2024     uint32_t gpio_mask = (1 << gpio_shift);
2025     uint32_t gpio_reg;
2026
2027     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2028         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2029             " gpio_shift %d gpio_mask 0x%x\n",
2030             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2031         return (-1);
2032     }
2033
2034     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2035
2036     /* read GPIO int */
2037     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2038
2039     switch (mode) {
2040     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2041         BLOGD(sc, DBG_PHY,
2042               "Clear GPIO INT %d (shift %d) -> output low\n",
2043               gpio_num, gpio_shift);
2044         /* clear SET and set CLR */
2045         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2046         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2047         break;
2048
2049     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2050         BLOGD(sc, DBG_PHY,
2051               "Set GPIO INT %d (shift %d) -> output high\n",
2052               gpio_num, gpio_shift);
2053         /* clear CLR and set SET */
2054         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2055         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2056         break;
2057
2058     default:
2059         break;
2060     }
2061
2062     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2063     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2064
2065     return (0);
2066 }
2067
2068 uint32_t
2069 elink_cb_gpio_read(struct bxe_softc *sc,
2070                    uint16_t         gpio_num,
2071                    uint8_t          port)
2072 {
2073     return (bxe_gpio_read(sc, gpio_num, port));
2074 }
2075
2076 uint8_t
2077 elink_cb_gpio_write(struct bxe_softc *sc,
2078                     uint16_t         gpio_num,
2079                     uint8_t          mode, /* 0=low 1=high */
2080                     uint8_t          port)
2081 {
2082     return (bxe_gpio_write(sc, gpio_num, mode, port));
2083 }
2084
2085 uint8_t
2086 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2087                          uint8_t          pins,
2088                          uint8_t          mode) /* 0=low 1=high */
2089 {
2090     return (bxe_gpio_mult_write(sc, pins, mode));
2091 }
2092
2093 uint8_t
2094 elink_cb_gpio_int_write(struct bxe_softc *sc,
2095                         uint16_t         gpio_num,
2096                         uint8_t          mode, /* 0=low 1=high */
2097                         uint8_t          port)
2098 {
2099     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2100 }
2101
2102 void
2103 elink_cb_notify_link_changed(struct bxe_softc *sc)
2104 {
2105     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2106                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2107 }
2108
2109 /* send the MCP a request, block until there is a reply */
2110 uint32_t
2111 elink_cb_fw_command(struct bxe_softc *sc,
2112                     uint32_t         command,
2113                     uint32_t         param)
2114 {
2115     int mb_idx = SC_FW_MB_IDX(sc);
2116     uint32_t seq;
2117     uint32_t rc = 0;
2118     uint32_t cnt = 1;
2119     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2120
2121     BXE_FWMB_LOCK(sc);
2122
2123     seq = ++sc->fw_seq;
2124     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2125     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2126
2127     BLOGD(sc, DBG_PHY,
2128           "wrote command 0x%08x to FW MB param 0x%08x\n",
2129           (command | seq), param);
2130
2131     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2132     do {
2133         DELAY(delay * 1000);
2134         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2135     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2136
2137     BLOGD(sc, DBG_PHY,
2138           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2139           cnt*delay, rc, seq);
2140
2141     /* is this a reply to our command? */
2142     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2143         rc &= FW_MSG_CODE_MASK;
2144     } else {
2145         /* Ruh-roh! */
2146         BLOGE(sc, "FW failed to respond!\n");
2147         // XXX bxe_fw_dump(sc);
2148         rc = 0;
2149     }
2150
2151     BXE_FWMB_UNLOCK(sc);
2152     return (rc);
2153 }
2154
2155 static uint32_t
2156 bxe_fw_command(struct bxe_softc *sc,
2157                uint32_t         command,
2158                uint32_t         param)
2159 {
2160     return (elink_cb_fw_command(sc, command, param));
2161 }
2162
2163 static void
2164 __storm_memset_dma_mapping(struct bxe_softc *sc,
2165                            uint32_t         addr,
2166                            bus_addr_t       mapping)
2167 {
2168     REG_WR(sc, addr, U64_LO(mapping));
2169     REG_WR(sc, (addr + 4), U64_HI(mapping));
2170 }
2171
2172 static void
2173 storm_memset_spq_addr(struct bxe_softc *sc,
2174                       bus_addr_t       mapping,
2175                       uint16_t         abs_fid)
2176 {
2177     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2178                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2179     __storm_memset_dma_mapping(sc, addr, mapping);
2180 }
2181
2182 static void
2183 storm_memset_vf_to_pf(struct bxe_softc *sc,
2184                       uint16_t         abs_fid,
2185                       uint16_t         pf_id)
2186 {
2187     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2188     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2189     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2190     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2191 }
2192
2193 static void
2194 storm_memset_func_en(struct bxe_softc *sc,
2195                      uint16_t         abs_fid,
2196                      uint8_t          enable)
2197 {
2198     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2199     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2200     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2201     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2202 }
2203
2204 static void
2205 storm_memset_eq_data(struct bxe_softc       *sc,
2206                      struct event_ring_data *eq_data,
2207                      uint16_t               pfid)
2208 {
2209     uint32_t addr;
2210     size_t size;
2211
2212     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2213     size = sizeof(struct event_ring_data);
2214     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2215 }
2216
2217 static void
2218 storm_memset_eq_prod(struct bxe_softc *sc,
2219                      uint16_t         eq_prod,
2220                      uint16_t         pfid)
2221 {
2222     uint32_t addr = (BAR_CSTRORM_INTMEM +
2223                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2224     REG_WR16(sc, addr, eq_prod);
2225 }
2226
2227 /*
2228  * Post a slowpath command.
2229  *
2230  * A slowpath command is used to propogate a configuration change through
2231  * the controller in a controlled manner, allowing each STORM processor and
2232  * other H/W blocks to phase in the change.  The commands sent on the
2233  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2234  * completion of the ramrod will occur in different ways.  Here's a
2235  * breakdown of ramrods and how they complete:
2236  *
2237  * RAMROD_CMD_ID_ETH_PORT_SETUP
2238  *   Used to setup the leading connection on a port.  Completes on the
2239  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2240  *
2241  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2242  *   Used to setup an additional connection on a port.  Completes on the
2243  *   RCQ of the multi-queue/RSS connection being initialized.
2244  *
2245  * RAMROD_CMD_ID_ETH_STAT_QUERY
2246  *   Used to force the storm processors to update the statistics database
2247  *   in host memory.  This ramrod is send on the leading connection CID and
2248  *   completes as an index increment of the CSTORM on the default status
2249  *   block.
2250  *
2251  * RAMROD_CMD_ID_ETH_UPDATE
2252  *   Used to update the state of the leading connection, usually to udpate
2253  *   the RSS indirection table.  Completes on the RCQ of the leading
2254  *   connection. (Not currently used under FreeBSD until OS support becomes
2255  *   available.)
2256  *
2257  * RAMROD_CMD_ID_ETH_HALT
2258  *   Used when tearing down a connection prior to driver unload.  Completes
2259  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2260  *   use this on the leading connection.
2261  *
2262  * RAMROD_CMD_ID_ETH_SET_MAC
2263  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2264  *   the RCQ of the leading connection.
2265  *
2266  * RAMROD_CMD_ID_ETH_CFC_DEL
2267  *   Used when tearing down a conneciton prior to driver unload.  Completes
2268  *   on the RCQ of the leading connection (since the current connection
2269  *   has been completely removed from controller memory).
2270  *
2271  * RAMROD_CMD_ID_ETH_PORT_DEL
2272  *   Used to tear down the leading connection prior to driver unload,
2273  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2274  *   default status block.
2275  *
2276  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2277  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2278  *   RSS connection that is being offloaded.  (Not currently used under
2279  *   FreeBSD.)
2280  *
2281  * There can only be one command pending per function.
2282  *
2283  * Returns:
2284  *   0 = Success, !0 = Failure.
2285  */
2286
2287 /* must be called under the spq lock */
2288 static inline
2289 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2290 {
2291     struct eth_spe *next_spe = sc->spq_prod_bd;
2292
2293     if (sc->spq_prod_bd == sc->spq_last_bd) {
2294         /* wrap back to the first eth_spq */
2295         sc->spq_prod_bd = sc->spq;
2296         sc->spq_prod_idx = 0;
2297     } else {
2298         sc->spq_prod_bd++;
2299         sc->spq_prod_idx++;
2300     }
2301
2302     return (next_spe);
2303 }
2304
2305 /* must be called under the spq lock */
2306 static inline
2307 void bxe_sp_prod_update(struct bxe_softc *sc)
2308 {
2309     int func = SC_FUNC(sc);
2310
2311     /*
2312      * Make sure that BD data is updated before writing the producer.
2313      * BD data is written to the memory, the producer is read from the
2314      * memory, thus we need a full memory barrier to ensure the ordering.
2315      */
2316     mb();
2317
2318     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2319              sc->spq_prod_idx);
2320
2321     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2322                       BUS_SPACE_BARRIER_WRITE);
2323 }
2324
2325 /**
2326  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2327  *
2328  * @cmd:      command to check
2329  * @cmd_type: command type
2330  */
2331 static inline
2332 int bxe_is_contextless_ramrod(int cmd,
2333                               int cmd_type)
2334 {
2335     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2336         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2337         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2338         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2339         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2340         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2341         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2342         return (TRUE);
2343     } else {
2344         return (FALSE);
2345     }
2346 }
2347
2348 /**
2349  * bxe_sp_post - place a single command on an SP ring
2350  *
2351  * @sc:         driver handle
2352  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2353  * @cid:        SW CID the command is related to
2354  * @data_hi:    command private data address (high 32 bits)
2355  * @data_lo:    command private data address (low 32 bits)
2356  * @cmd_type:   command type (e.g. NONE, ETH)
2357  *
2358  * SP data is handled as if it's always an address pair, thus data fields are
2359  * not swapped to little endian in upper functions. Instead this function swaps
2360  * data as if it's two uint32 fields.
2361  */
2362 int
2363 bxe_sp_post(struct bxe_softc *sc,
2364             int              command,
2365             int              cid,
2366             uint32_t         data_hi,
2367             uint32_t         data_lo,
2368             int              cmd_type)
2369 {
2370     struct eth_spe *spe;
2371     uint16_t type;
2372     int common;
2373
2374     common = bxe_is_contextless_ramrod(command, cmd_type);
2375
2376     BXE_SP_LOCK(sc);
2377
2378     if (common) {
2379         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2380             BLOGE(sc, "EQ ring is full!\n");
2381             BXE_SP_UNLOCK(sc);
2382             return (-1);
2383         }
2384     } else {
2385         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2386             BLOGE(sc, "SPQ ring is full!\n");
2387             BXE_SP_UNLOCK(sc);
2388             return (-1);
2389         }
2390     }
2391
2392     spe = bxe_sp_get_next(sc);
2393
2394     /* CID needs port number to be encoded int it */
2395     spe->hdr.conn_and_cmd_data =
2396         htole32((command << SPE_HDR_CMD_ID_SHIFT) | HW_CID(sc, cid));
2397
2398     type = (cmd_type << SPE_HDR_CONN_TYPE_SHIFT) & SPE_HDR_CONN_TYPE;
2399
2400     /* TBD: Check if it works for VFs */
2401     type |= ((SC_FUNC(sc) << SPE_HDR_FUNCTION_ID_SHIFT) &
2402              SPE_HDR_FUNCTION_ID);
2403
2404     spe->hdr.type = htole16(type);
2405
2406     spe->data.update_data_addr.hi = htole32(data_hi);
2407     spe->data.update_data_addr.lo = htole32(data_lo);
2408
2409     /*
2410      * It's ok if the actual decrement is issued towards the memory
2411      * somewhere between the lock and unlock. Thus no more explict
2412      * memory barrier is needed.
2413      */
2414     if (common) {
2415         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2416     } else {
2417         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2418     }
2419
2420     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2421     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2422           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2423     BLOGD(sc, DBG_SP,
2424           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2425           sc->spq_prod_idx,
2426           (uint32_t)U64_HI(sc->spq_dma.paddr),
2427           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2428           command,
2429           common,
2430           HW_CID(sc, cid),
2431           data_hi,
2432           data_lo,
2433           type,
2434           atomic_load_acq_long(&sc->cq_spq_left),
2435           atomic_load_acq_long(&sc->eq_spq_left));
2436
2437     bxe_sp_prod_update(sc);
2438
2439     BXE_SP_UNLOCK(sc);
2440     return (0);
2441 }
2442
2443 /**
2444  * bxe_debug_print_ind_table - prints the indirection table configuration.
2445  *
2446  * @sc: driver hanlde
2447  * @p:  pointer to rss configuration
2448  */
2449
2450 /*
2451  * FreeBSD Device probe function.
2452  *
2453  * Compares the device found to the driver's list of supported devices and
2454  * reports back to the bsd loader whether this is the right driver for the device.
2455  * This is the driver entry function called from the "kldload" command.
2456  *
2457  * Returns:
2458  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2459  */
2460 static int
2461 bxe_probe(device_t dev)
2462 {
2463     struct bxe_softc *sc;
2464     struct bxe_device_type *t;
2465     char *descbuf;
2466     uint16_t did, sdid, svid, vid;
2467
2468     /* Find our device structure */
2469     sc = device_get_softc(dev);
2470     sc->dev = dev;
2471     t = bxe_devs;
2472
2473     /* Get the data for the device to be probed. */
2474     vid  = pci_get_vendor(dev);
2475     did  = pci_get_device(dev);
2476     svid = pci_get_subvendor(dev);
2477     sdid = pci_get_subdevice(dev);
2478
2479     BLOGD(sc, DBG_LOAD,
2480           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2481           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2482
2483     /* Look through the list of known devices for a match. */
2484     while (t->bxe_name != NULL) {
2485         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2486             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2487             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2488             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2489             if (descbuf == NULL)
2490                 return (ENOMEM);
2491
2492             /* Print out the device identity. */
2493             snprintf(descbuf, BXE_DEVDESC_MAX,
2494                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2495                      (((pci_read_config(dev, PCIR_REVID, 4) &
2496                         0xf0) >> 4) + 'A'),
2497                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2498                      BXE_DRIVER_VERSION);
2499
2500             device_set_desc_copy(dev, descbuf);
2501             free(descbuf, M_TEMP);
2502             return (BUS_PROBE_DEFAULT);
2503         }
2504         t++;
2505     }
2506
2507     return (ENXIO);
2508 }
2509
2510 static void
2511 bxe_init_mutexes(struct bxe_softc *sc)
2512 {
2513 #ifdef BXE_CORE_LOCK_SX
2514     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2515              "bxe%d_core_lock", sc->unit);
2516     sx_init(&sc->core_sx, sc->core_sx_name);
2517 #else
2518     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2519              "bxe%d_core_lock", sc->unit);
2520     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2521 #endif
2522
2523     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2524              "bxe%d_sp_lock", sc->unit);
2525     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2526
2527     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2528              "bxe%d_dmae_lock", sc->unit);
2529     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2530
2531     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2532              "bxe%d_phy_lock", sc->unit);
2533     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2534
2535     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2536              "bxe%d_fwmb_lock", sc->unit);
2537     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2538
2539     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2540              "bxe%d_print_lock", sc->unit);
2541     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2542
2543     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2544              "bxe%d_stats_lock", sc->unit);
2545     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2546
2547     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2548              "bxe%d_mcast_lock", sc->unit);
2549     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2550 }
2551
2552 static void
2553 bxe_release_mutexes(struct bxe_softc *sc)
2554 {
2555 #ifdef BXE_CORE_LOCK_SX
2556     sx_destroy(&sc->core_sx);
2557 #else
2558     if (mtx_initialized(&sc->core_mtx)) {
2559         mtx_destroy(&sc->core_mtx);
2560     }
2561 #endif
2562
2563     if (mtx_initialized(&sc->sp_mtx)) {
2564         mtx_destroy(&sc->sp_mtx);
2565     }
2566
2567     if (mtx_initialized(&sc->dmae_mtx)) {
2568         mtx_destroy(&sc->dmae_mtx);
2569     }
2570
2571     if (mtx_initialized(&sc->port.phy_mtx)) {
2572         mtx_destroy(&sc->port.phy_mtx);
2573     }
2574
2575     if (mtx_initialized(&sc->fwmb_mtx)) {
2576         mtx_destroy(&sc->fwmb_mtx);
2577     }
2578
2579     if (mtx_initialized(&sc->print_mtx)) {
2580         mtx_destroy(&sc->print_mtx);
2581     }
2582
2583     if (mtx_initialized(&sc->stats_mtx)) {
2584         mtx_destroy(&sc->stats_mtx);
2585     }
2586
2587     if (mtx_initialized(&sc->mcast_mtx)) {
2588         mtx_destroy(&sc->mcast_mtx);
2589     }
2590 }
2591
2592 static void
2593 bxe_tx_disable(struct bxe_softc* sc)
2594 {
2595     struct ifnet *ifp = sc->ifnet;
2596
2597     /* tell the stack the driver is stopped and TX queue is full */
2598     if (ifp != NULL) {
2599         ifp->if_drv_flags = 0;
2600     }
2601 }
2602
2603 static void
2604 bxe_drv_pulse(struct bxe_softc *sc)
2605 {
2606     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2607              sc->fw_drv_pulse_wr_seq);
2608 }
2609
2610 static inline uint16_t
2611 bxe_tx_avail(struct bxe_softc *sc,
2612              struct bxe_fastpath *fp)
2613 {
2614     int16_t  used;
2615     uint16_t prod;
2616     uint16_t cons;
2617
2618     prod = fp->tx_bd_prod;
2619     cons = fp->tx_bd_cons;
2620
2621     used = SUB_S16(prod, cons);
2622
2623     return (int16_t)(sc->tx_ring_size) - used;
2624 }
2625
2626 static inline int
2627 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2628 {
2629     uint16_t hw_cons;
2630
2631     mb(); /* status block fields can change */
2632     hw_cons = le16toh(*fp->tx_cons_sb);
2633     return (hw_cons != fp->tx_pkt_cons);
2634 }
2635
2636 static inline uint8_t
2637 bxe_has_tx_work(struct bxe_fastpath *fp)
2638 {
2639     /* expand this for multi-cos if ever supported */
2640     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2641 }
2642
2643 static inline int
2644 bxe_has_rx_work(struct bxe_fastpath *fp)
2645 {
2646     uint16_t rx_cq_cons_sb;
2647
2648     mb(); /* status block fields can change */
2649     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2650     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2651         rx_cq_cons_sb++;
2652     return (fp->rx_cq_cons != rx_cq_cons_sb);
2653 }
2654
2655 static void
2656 bxe_sp_event(struct bxe_softc    *sc,
2657              struct bxe_fastpath *fp,
2658              union eth_rx_cqe    *rr_cqe)
2659 {
2660     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2661     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2662     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2663     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2664
2665     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2666           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2667
2668     switch (command) {
2669     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2670         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2671         drv_cmd = ECORE_Q_CMD_UPDATE;
2672         break;
2673
2674     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2675         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2676         drv_cmd = ECORE_Q_CMD_SETUP;
2677         break;
2678
2679     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2680         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2681         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2682         break;
2683
2684     case (RAMROD_CMD_ID_ETH_HALT):
2685         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2686         drv_cmd = ECORE_Q_CMD_HALT;
2687         break;
2688
2689     case (RAMROD_CMD_ID_ETH_TERMINATE):
2690         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2691         drv_cmd = ECORE_Q_CMD_TERMINATE;
2692         break;
2693
2694     case (RAMROD_CMD_ID_ETH_EMPTY):
2695         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2696         drv_cmd = ECORE_Q_CMD_EMPTY;
2697         break;
2698
2699     default:
2700         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2701               command, fp->index);
2702         return;
2703     }
2704
2705     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2706         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2707         /*
2708          * q_obj->complete_cmd() failure means that this was
2709          * an unexpected completion.
2710          *
2711          * In this case we don't want to increase the sc->spq_left
2712          * because apparently we haven't sent this command the first
2713          * place.
2714          */
2715         // bxe_panic(sc, ("Unexpected SP completion\n"));
2716         return;
2717     }
2718
2719     atomic_add_acq_long(&sc->cq_spq_left, 1);
2720
2721     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2722           atomic_load_acq_long(&sc->cq_spq_left));
2723 }
2724
2725 /*
2726  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2727  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2728  * the current aggregation queue as in-progress.
2729  */
2730 static void
2731 bxe_tpa_start(struct bxe_softc            *sc,
2732               struct bxe_fastpath         *fp,
2733               uint16_t                    queue,
2734               uint16_t                    cons,
2735               uint16_t                    prod,
2736               struct eth_fast_path_rx_cqe *cqe)
2737 {
2738     struct bxe_sw_rx_bd tmp_bd;
2739     struct bxe_sw_rx_bd *rx_buf;
2740     struct eth_rx_bd *rx_bd;
2741     int max_agg_queues;
2742     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2743     uint16_t index;
2744
2745     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2746                        "cons=%d prod=%d\n",
2747           fp->index, queue, cons, prod);
2748
2749     max_agg_queues = MAX_AGG_QS(sc);
2750
2751     KASSERT((queue < max_agg_queues),
2752             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2753              fp->index, queue, max_agg_queues));
2754
2755     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2756             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2757              fp->index, queue));
2758
2759     /* copy the existing mbuf and mapping from the TPA pool */
2760     tmp_bd = tpa_info->bd;
2761
2762     if (tmp_bd.m == NULL) {
2763         uint32_t *tmp;
2764
2765         tmp = (uint32_t *)cqe;
2766
2767         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2768               fp->index, queue, cons, prod);
2769         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2770             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2771             
2772         /* XXX Error handling? */
2773         return;
2774     }
2775
2776     /* change the TPA queue to the start state */
2777     tpa_info->state            = BXE_TPA_STATE_START;
2778     tpa_info->placement_offset = cqe->placement_offset;
2779     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2780     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2781     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2782
2783     fp->rx_tpa_queue_used |= (1 << queue);
2784
2785     /*
2786      * If all the buffer descriptors are filled with mbufs then fill in
2787      * the current consumer index with a new BD. Else if a maximum Rx
2788      * buffer limit is imposed then fill in the next producer index.
2789      */
2790     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2791                 prod : cons;
2792
2793     /* move the received mbuf and mapping to TPA pool */
2794     tpa_info->bd = fp->rx_mbuf_chain[cons];
2795
2796     /* release any existing RX BD mbuf mappings */
2797     if (cons != index) {
2798         rx_buf = &fp->rx_mbuf_chain[cons];
2799
2800         if (rx_buf->m_map != NULL) {
2801             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2802                             BUS_DMASYNC_POSTREAD);
2803             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2804         }
2805
2806         /*
2807          * We get here when the maximum number of rx buffers is less than
2808          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2809          * it out here without concern of a memory leak.
2810          */
2811         fp->rx_mbuf_chain[cons].m = NULL;
2812     }
2813
2814     /* update the Rx SW BD with the mbuf info from the TPA pool */
2815     fp->rx_mbuf_chain[index] = tmp_bd;
2816
2817     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2818     rx_bd = &fp->rx_chain[index];
2819     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2820     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2821 }
2822
2823 /*
2824  * When a TPA aggregation is completed, loop through the individual mbufs
2825  * of the aggregation, combining them into a single mbuf which will be sent
2826  * up the stack. Refill all freed SGEs with mbufs as we go along.
2827  */
2828 static int
2829 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2830                    struct bxe_fastpath       *fp,
2831                    struct bxe_sw_tpa_info    *tpa_info,
2832                    uint16_t                  queue,
2833                    uint16_t                  pages,
2834                    struct mbuf               *m,
2835                                struct eth_end_agg_rx_cqe *cqe,
2836                    uint16_t                  cqe_idx)
2837 {
2838     struct mbuf *m_frag;
2839     uint32_t frag_len, frag_size, i;
2840     uint16_t sge_idx;
2841     int rc = 0;
2842     int j;
2843
2844     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2845
2846     BLOGD(sc, DBG_LRO,
2847           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2848           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2849
2850     /* make sure the aggregated frame is not too big to handle */
2851     if (pages > 8 * PAGES_PER_SGE) {
2852
2853         uint32_t *tmp = (uint32_t *)cqe;
2854
2855         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2856                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2857               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2858               tpa_info->len_on_bd, frag_size);
2859
2860         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2861             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2862
2863         bxe_panic(sc, ("sge page count error\n"));
2864         return (EINVAL);
2865     }
2866
2867     /*
2868      * Scan through the scatter gather list pulling individual mbufs into a
2869      * single mbuf for the host stack.
2870      */
2871     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2872         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2873
2874         /*
2875          * Firmware gives the indices of the SGE as if the ring is an array
2876          * (meaning that the "next" element will consume 2 indices).
2877          */
2878         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2879
2880         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2881                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2882               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2883
2884         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2885
2886         /* allocate a new mbuf for the SGE */
2887         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2888         if (rc) {
2889             /* Leave all remaining SGEs in the ring! */
2890             return (rc);
2891         }
2892
2893         /* update the fragment length */
2894         m_frag->m_len = frag_len;
2895
2896         /* concatenate the fragment to the head mbuf */
2897         m_cat(m, m_frag);
2898         fp->eth_q_stats.mbuf_alloc_sge--;
2899
2900         /* update the TPA mbuf size and remaining fragment size */
2901         m->m_pkthdr.len += frag_len;
2902         frag_size -= frag_len;
2903     }
2904
2905     BLOGD(sc, DBG_LRO,
2906           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2907           fp->index, queue, frag_size);
2908
2909     return (rc);
2910 }
2911
2912 static inline void
2913 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2914 {
2915     int i, j;
2916
2917     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2918         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2919
2920         for (j = 0; j < 2; j++) {
2921             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2922             idx--;
2923         }
2924     }
2925 }
2926
2927 static inline void
2928 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2929 {
2930     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2931     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2932
2933     /*
2934      * Clear the two last indices in the page to 1. These are the indices that
2935      * correspond to the "next" element, hence will never be indicated and
2936      * should be removed from the calculations.
2937      */
2938     bxe_clear_sge_mask_next_elems(fp);
2939 }
2940
2941 static inline void
2942 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2943                         uint16_t            idx)
2944 {
2945     uint16_t last_max = fp->last_max_sge;
2946
2947     if (SUB_S16(idx, last_max) > 0) {
2948         fp->last_max_sge = idx;
2949     }
2950 }
2951
2952 static inline void
2953 bxe_update_sge_prod(struct bxe_softc          *sc,
2954                     struct bxe_fastpath       *fp,
2955                     uint16_t                  sge_len,
2956                     union eth_sgl_or_raw_data *cqe)
2957 {
2958     uint16_t last_max, last_elem, first_elem;
2959     uint16_t delta = 0;
2960     uint16_t i;
2961
2962     if (!sge_len) {
2963         return;
2964     }
2965
2966     /* first mark all used pages */
2967     for (i = 0; i < sge_len; i++) {
2968         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2969                             RX_SGE(le16toh(cqe->sgl[i])));
2970     }
2971
2972     BLOGD(sc, DBG_LRO,
2973           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2974           fp->index, sge_len - 1,
2975           le16toh(cqe->sgl[sge_len - 1]));
2976
2977     /* assume that the last SGE index is the biggest */
2978     bxe_update_last_max_sge(fp,
2979                             le16toh(cqe->sgl[sge_len - 1]));
2980
2981     last_max = RX_SGE(fp->last_max_sge);
2982     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
2983     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
2984
2985     /* if ring is not full */
2986     if (last_elem + 1 != first_elem) {
2987         last_elem++;
2988     }
2989
2990     /* now update the prod */
2991     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
2992         if (__predict_true(fp->sge_mask[i])) {
2993             break;
2994         }
2995
2996         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
2997         delta += BIT_VEC64_ELEM_SZ;
2998     }
2999
3000     if (delta > 0) {
3001         fp->rx_sge_prod += delta;
3002         /* clear page-end entries */
3003         bxe_clear_sge_mask_next_elems(fp);
3004     }
3005
3006     BLOGD(sc, DBG_LRO,
3007           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3008           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3009 }
3010
3011 /*
3012  * The aggregation on the current TPA queue has completed. Pull the individual
3013  * mbuf fragments together into a single mbuf, perform all necessary checksum
3014  * calculations, and send the resuting mbuf to the stack.
3015  */
3016 static void
3017 bxe_tpa_stop(struct bxe_softc          *sc,
3018              struct bxe_fastpath       *fp,
3019              struct bxe_sw_tpa_info    *tpa_info,
3020              uint16_t                  queue,
3021              uint16_t                  pages,
3022                          struct eth_end_agg_rx_cqe *cqe,
3023              uint16_t                  cqe_idx)
3024 {
3025     struct ifnet *ifp = sc->ifnet;
3026     struct mbuf *m;
3027     int rc = 0;
3028
3029     BLOGD(sc, DBG_LRO,
3030           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3031           fp->index, queue, tpa_info->placement_offset,
3032           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3033
3034     m = tpa_info->bd.m;
3035
3036     /* allocate a replacement before modifying existing mbuf */
3037     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3038     if (rc) {
3039         /* drop the frame and log an error */
3040         fp->eth_q_stats.rx_soft_errors++;
3041         goto bxe_tpa_stop_exit;
3042     }
3043
3044     /* we have a replacement, fixup the current mbuf */
3045     m_adj(m, tpa_info->placement_offset);
3046     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3047
3048     /* mark the checksums valid (taken care of by the firmware) */
3049     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3050     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3051     m->m_pkthdr.csum_data = 0xffff;
3052     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3053                                CSUM_IP_VALID   |
3054                                CSUM_DATA_VALID |
3055                                CSUM_PSEUDO_HDR);
3056
3057     /* aggregate all of the SGEs into a single mbuf */
3058     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3059     if (rc) {
3060         /* drop the packet and log an error */
3061         fp->eth_q_stats.rx_soft_errors++;
3062         m_freem(m);
3063     } else {
3064         if (tpa_info->parsing_flags & PARSING_FLAGS_VLAN) {
3065             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3066             m->m_flags |= M_VLANTAG;
3067         }
3068
3069         /* assign packet to this interface interface */
3070         m->m_pkthdr.rcvif = ifp;
3071
3072 #if __FreeBSD_version >= 800000
3073         /* specify what RSS queue was used for this flow */
3074         m->m_pkthdr.flowid = fp->index;
3075         m->m_flags |= M_FLOWID;
3076 #endif
3077
3078         ifp->if_ipackets++;
3079         fp->eth_q_stats.rx_tpa_pkts++;
3080
3081         /* pass the frame to the stack */
3082         (*ifp->if_input)(ifp, m);
3083     }
3084
3085     /* we passed an mbuf up the stack or dropped the frame */
3086     fp->eth_q_stats.mbuf_alloc_tpa--;
3087
3088 bxe_tpa_stop_exit:
3089
3090     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3091     fp->rx_tpa_queue_used &= ~(1 << queue);
3092 }
3093
3094 static uint8_t
3095 bxe_service_rxsgl(
3096                  struct bxe_fastpath *fp,
3097                  uint16_t len,
3098                  uint16_t lenonbd,
3099                  struct mbuf *m,
3100                  struct eth_fast_path_rx_cqe *cqe_fp)
3101 {
3102     struct mbuf *m_frag;
3103     uint16_t frags, frag_len;
3104     uint16_t sge_idx = 0;
3105     uint16_t j;
3106     uint8_t i, rc = 0;
3107     uint32_t frag_size;
3108
3109     /* adjust the mbuf */
3110     m->m_len = lenonbd;
3111
3112     frag_size =  len - lenonbd;
3113     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3114
3115     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3116         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3117
3118         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3119         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3120         m_frag->m_len = frag_len;
3121
3122        /* allocate a new mbuf for the SGE */
3123         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3124         if (rc) {
3125             /* Leave all remaining SGEs in the ring! */
3126             return (rc);
3127         }
3128         fp->eth_q_stats.mbuf_alloc_sge--;
3129
3130         /* concatenate the fragment to the head mbuf */
3131         m_cat(m, m_frag);
3132
3133         frag_size -= frag_len;
3134     }
3135
3136     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3137
3138     return rc;
3139 }
3140
3141 static uint8_t
3142 bxe_rxeof(struct bxe_softc    *sc,
3143           struct bxe_fastpath *fp)
3144 {
3145     struct ifnet *ifp = sc->ifnet;
3146     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3147     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3148     int rx_pkts = 0;
3149     int rc = 0;
3150
3151     BXE_FP_RX_LOCK(fp);
3152
3153     /* CQ "next element" is of the size of the regular element */
3154     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3155     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3156         hw_cq_cons++;
3157     }
3158
3159     bd_cons = fp->rx_bd_cons;
3160     bd_prod = fp->rx_bd_prod;
3161     bd_prod_fw = bd_prod;
3162     sw_cq_cons = fp->rx_cq_cons;
3163     sw_cq_prod = fp->rx_cq_prod;
3164
3165     /*
3166      * Memory barrier necessary as speculative reads of the rx
3167      * buffer can be ahead of the index in the status block
3168      */
3169     rmb();
3170
3171     BLOGD(sc, DBG_RX,
3172           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3173           fp->index, hw_cq_cons, sw_cq_cons);
3174
3175     while (sw_cq_cons != hw_cq_cons) {
3176         struct bxe_sw_rx_bd *rx_buf = NULL;
3177         union eth_rx_cqe *cqe;
3178         struct eth_fast_path_rx_cqe *cqe_fp;
3179         uint8_t cqe_fp_flags;
3180         enum eth_rx_cqe_type cqe_fp_type;
3181         uint16_t len, lenonbd,  pad;
3182         struct mbuf *m = NULL;
3183
3184         comp_ring_cons = RCQ(sw_cq_cons);
3185         bd_prod = RX_BD(bd_prod);
3186         bd_cons = RX_BD(bd_cons);
3187
3188         cqe          = &fp->rcq_chain[comp_ring_cons];
3189         cqe_fp       = &cqe->fast_path_cqe;
3190         cqe_fp_flags = cqe_fp->type_error_flags;
3191         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3192
3193         BLOGD(sc, DBG_RX,
3194               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3195               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3196               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3197               fp->index,
3198               hw_cq_cons,
3199               sw_cq_cons,
3200               bd_prod,
3201               bd_cons,
3202               CQE_TYPE(cqe_fp_flags),
3203               cqe_fp_flags,
3204               cqe_fp->status_flags,
3205               le32toh(cqe_fp->rss_hash_result),
3206               le16toh(cqe_fp->vlan_tag),
3207               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3208               le16toh(cqe_fp->len_on_bd));
3209
3210         /* is this a slowpath msg? */
3211         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3212             bxe_sp_event(sc, fp, cqe);
3213             goto next_cqe;
3214         }
3215
3216         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3217
3218         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3219             struct bxe_sw_tpa_info *tpa_info;
3220             uint16_t frag_size, pages;
3221             uint8_t queue;
3222
3223             if (CQE_TYPE_START(cqe_fp_type)) {
3224                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3225                               bd_cons, bd_prod, cqe_fp);
3226                 m = NULL; /* packet not ready yet */
3227                 goto next_rx;
3228             }
3229
3230             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3231                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3232
3233             queue = cqe->end_agg_cqe.queue_index;
3234             tpa_info = &fp->rx_tpa_info[queue];
3235
3236             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3237                   fp->index, queue);
3238
3239             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3240                          tpa_info->len_on_bd);
3241             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3242
3243             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3244                          &cqe->end_agg_cqe, comp_ring_cons);
3245
3246             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3247
3248             goto next_cqe;
3249         }
3250
3251         /* non TPA */
3252
3253         /* is this an error packet? */
3254         if (__predict_false(cqe_fp_flags &
3255                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3256             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3257             fp->eth_q_stats.rx_soft_errors++;
3258             goto next_rx;
3259         }
3260
3261         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3262         lenonbd = le16toh(cqe_fp->len_on_bd);
3263         pad = cqe_fp->placement_offset;
3264
3265         m = rx_buf->m;
3266
3267         if (__predict_false(m == NULL)) {
3268             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3269                   bd_cons, fp->index);
3270             goto next_rx;
3271         }
3272
3273         /* XXX double copy if packet length under a threshold */
3274
3275         /*
3276          * If all the buffer descriptors are filled with mbufs then fill in
3277          * the current consumer index with a new BD. Else if a maximum Rx
3278          * buffer limit is imposed then fill in the next producer index.
3279          */
3280         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3281                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3282                                       bd_prod : bd_cons);
3283         if (rc != 0) {
3284
3285             /* we simply reuse the received mbuf and don't post it to the stack */
3286             m = NULL;
3287
3288             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3289                   fp->index, rc);
3290             fp->eth_q_stats.rx_soft_errors++;
3291
3292             if (sc->max_rx_bufs != RX_BD_USABLE) {
3293                 /* copy this consumer index to the producer index */
3294                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3295                        sizeof(struct bxe_sw_rx_bd));
3296                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3297             }
3298
3299             goto next_rx;
3300         }
3301
3302         /* current mbuf was detached from the bd */
3303         fp->eth_q_stats.mbuf_alloc_rx--;
3304
3305         /* we allocated a replacement mbuf, fixup the current one */
3306         m_adj(m, pad);
3307         m->m_pkthdr.len = m->m_len = len;
3308
3309         if ((len > 60) && (len > lenonbd)) {
3310             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3311             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3312             if (rc)
3313                 break;
3314             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3315         } else if (lenonbd < len) {
3316             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3317         }
3318
3319         /* assign packet to this interface interface */
3320         m->m_pkthdr.rcvif = ifp;
3321
3322         /* assume no hardware checksum has complated */
3323         m->m_pkthdr.csum_flags = 0;
3324
3325         /* validate checksum if offload enabled */
3326         if (ifp->if_capenable & IFCAP_RXCSUM) {
3327             /* check for a valid IP frame */
3328             if (!(cqe->fast_path_cqe.status_flags &
3329                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3330                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3331                 if (__predict_false(cqe_fp_flags &
3332                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3333                     fp->eth_q_stats.rx_hw_csum_errors++;
3334                 } else {
3335                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3336                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3337                 }
3338             }
3339
3340             /* check for a valid TCP/UDP frame */
3341             if (!(cqe->fast_path_cqe.status_flags &
3342                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3343                 if (__predict_false(cqe_fp_flags &
3344                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3345                     fp->eth_q_stats.rx_hw_csum_errors++;
3346                 } else {
3347                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3348                     m->m_pkthdr.csum_data = 0xFFFF;
3349                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3350                                                CSUM_PSEUDO_HDR);
3351                 }
3352             }
3353         }
3354
3355         /* if there is a VLAN tag then flag that info */
3356         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_VLAN) {
3357             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3358             m->m_flags |= M_VLANTAG;
3359         }
3360
3361 #if __FreeBSD_version >= 800000
3362         /* specify what RSS queue was used for this flow */
3363         m->m_pkthdr.flowid = fp->index;
3364         m->m_flags |= M_FLOWID;
3365 #endif
3366
3367 next_rx:
3368
3369         bd_cons    = RX_BD_NEXT(bd_cons);
3370         bd_prod    = RX_BD_NEXT(bd_prod);
3371         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3372
3373         /* pass the frame to the stack */
3374         if (__predict_true(m != NULL)) {
3375             ifp->if_ipackets++;
3376             rx_pkts++;
3377             (*ifp->if_input)(ifp, m);
3378         }
3379
3380 next_cqe:
3381
3382         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3383         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3384
3385         /* limit spinning on the queue */
3386         if (rc != 0)
3387             break;
3388
3389         if (rx_pkts == sc->rx_budget) {
3390             fp->eth_q_stats.rx_budget_reached++;
3391             break;
3392         }
3393     } /* while work to do */
3394
3395     fp->rx_bd_cons = bd_cons;
3396     fp->rx_bd_prod = bd_prod_fw;
3397     fp->rx_cq_cons = sw_cq_cons;
3398     fp->rx_cq_prod = sw_cq_prod;
3399
3400     /* Update producers */
3401     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3402
3403     fp->eth_q_stats.rx_pkts += rx_pkts;
3404     fp->eth_q_stats.rx_calls++;
3405
3406     BXE_FP_RX_UNLOCK(fp);
3407
3408     return (sw_cq_cons != hw_cq_cons);
3409 }
3410
3411 static uint16_t
3412 bxe_free_tx_pkt(struct bxe_softc    *sc,
3413                 struct bxe_fastpath *fp,
3414                 uint16_t            idx)
3415 {
3416     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3417     struct eth_tx_start_bd *tx_start_bd;
3418     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3419     uint16_t new_cons;
3420     int nbd;
3421
3422     /* unmap the mbuf from non-paged memory */
3423     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3424
3425     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3426     nbd = le16toh(tx_start_bd->nbd) - 1;
3427
3428     new_cons = (tx_buf->first_bd + nbd);
3429
3430     /* free the mbuf */
3431     if (__predict_true(tx_buf->m != NULL)) {
3432         m_freem(tx_buf->m);
3433         fp->eth_q_stats.mbuf_alloc_tx--;
3434     } else {
3435         fp->eth_q_stats.tx_chain_lost_mbuf++;
3436     }
3437
3438     tx_buf->m = NULL;
3439     tx_buf->first_bd = 0;
3440
3441     return (new_cons);
3442 }
3443
3444 /* transmit timeout watchdog */
3445 static int
3446 bxe_watchdog(struct bxe_softc    *sc,
3447              struct bxe_fastpath *fp)
3448 {
3449     BXE_FP_TX_LOCK(fp);
3450
3451     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3452         BXE_FP_TX_UNLOCK(fp);
3453         return (0);
3454     }
3455
3456     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3457
3458     BXE_FP_TX_UNLOCK(fp);
3459
3460     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3461     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3462
3463     return (-1);
3464 }
3465
3466 /* processes transmit completions */
3467 static uint8_t
3468 bxe_txeof(struct bxe_softc    *sc,
3469           struct bxe_fastpath *fp)
3470 {
3471     struct ifnet *ifp = sc->ifnet;
3472     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3473     uint16_t tx_bd_avail;
3474
3475     BXE_FP_TX_LOCK_ASSERT(fp);
3476
3477     bd_cons = fp->tx_bd_cons;
3478     hw_cons = le16toh(*fp->tx_cons_sb);
3479     sw_cons = fp->tx_pkt_cons;
3480
3481     while (sw_cons != hw_cons) {
3482         pkt_cons = TX_BD(sw_cons);
3483
3484         BLOGD(sc, DBG_TX,
3485               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3486               fp->index, hw_cons, sw_cons, pkt_cons);
3487
3488         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3489
3490         sw_cons++;
3491     }
3492
3493     fp->tx_pkt_cons = sw_cons;
3494     fp->tx_bd_cons  = bd_cons;
3495
3496     BLOGD(sc, DBG_TX,
3497           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3498           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3499
3500     mb();
3501
3502     tx_bd_avail = bxe_tx_avail(sc, fp);
3503
3504     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3505         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3506     } else {
3507         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3508     }
3509
3510     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3511         /* reset the watchdog timer if there are pending transmits */
3512         fp->watchdog_timer = BXE_TX_TIMEOUT;
3513         return (TRUE);
3514     } else {
3515         /* clear watchdog when there are no pending transmits */
3516         fp->watchdog_timer = 0;
3517         return (FALSE);
3518     }
3519 }
3520
3521 static void
3522 bxe_drain_tx_queues(struct bxe_softc *sc)
3523 {
3524     struct bxe_fastpath *fp;
3525     int i, count;
3526
3527     /* wait until all TX fastpath tasks have completed */
3528     for (i = 0; i < sc->num_queues; i++) {
3529         fp = &sc->fp[i];
3530
3531         count = 1000;
3532
3533         while (bxe_has_tx_work(fp)) {
3534
3535             BXE_FP_TX_LOCK(fp);
3536             bxe_txeof(sc, fp);
3537             BXE_FP_TX_UNLOCK(fp);
3538
3539             if (count == 0) {
3540                 BLOGE(sc, "Timeout waiting for fp[%d] "
3541                           "transmits to complete!\n", i);
3542                 bxe_panic(sc, ("tx drain failure\n"));
3543                 return;
3544             }
3545
3546             count--;
3547             DELAY(1000);
3548             rmb();
3549         }
3550     }
3551
3552     return;
3553 }
3554
3555 static int
3556 bxe_del_all_macs(struct bxe_softc          *sc,
3557                  struct ecore_vlan_mac_obj *mac_obj,
3558                  int                       mac_type,
3559                  uint8_t                   wait_for_comp)
3560 {
3561     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3562     int rc;
3563
3564     /* wait for completion of requested */
3565     if (wait_for_comp) {
3566         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3567     }
3568
3569     /* Set the mac type of addresses we want to clear */
3570     bxe_set_bit(mac_type, &vlan_mac_flags);
3571
3572     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3573     if (rc < 0) {
3574         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3575             rc, mac_type, wait_for_comp);
3576     }
3577
3578     return (rc);
3579 }
3580
3581 static int
3582 bxe_fill_accept_flags(struct bxe_softc *sc,
3583                       uint32_t         rx_mode,
3584                       unsigned long    *rx_accept_flags,
3585                       unsigned long    *tx_accept_flags)
3586 {
3587     /* Clear the flags first */
3588     *rx_accept_flags = 0;
3589     *tx_accept_flags = 0;
3590
3591     switch (rx_mode) {
3592     case BXE_RX_MODE_NONE:
3593         /*
3594          * 'drop all' supersedes any accept flags that may have been
3595          * passed to the function.
3596          */
3597         break;
3598
3599     case BXE_RX_MODE_NORMAL:
3600         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3601         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3602         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3603
3604         /* internal switching mode */
3605         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3606         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3607         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3608
3609         break;
3610
3611     case BXE_RX_MODE_ALLMULTI:
3612         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3613         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3614         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3615
3616         /* internal switching mode */
3617         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3618         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3619         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3620
3621         break;
3622
3623     case BXE_RX_MODE_PROMISC:
3624         /*
3625          * According to deffinition of SI mode, iface in promisc mode
3626          * should receive matched and unmatched (in resolution of port)
3627          * unicast packets.
3628          */
3629         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3630         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3631         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3632         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3633
3634         /* internal switching mode */
3635         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3636         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3637
3638         if (IS_MF_SI(sc)) {
3639             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3640         } else {
3641             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3642         }
3643
3644         break;
3645
3646     default:
3647         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3648         return (-1);
3649     }
3650
3651     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3652     if (rx_mode != BXE_RX_MODE_NONE) {
3653         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3654         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3655     }
3656
3657     return (0);
3658 }
3659
3660 static int
3661 bxe_set_q_rx_mode(struct bxe_softc *sc,
3662                   uint8_t          cl_id,
3663                   unsigned long    rx_mode_flags,
3664                   unsigned long    rx_accept_flags,
3665                   unsigned long    tx_accept_flags,
3666                   unsigned long    ramrod_flags)
3667 {
3668     struct ecore_rx_mode_ramrod_params ramrod_param;
3669     int rc;
3670
3671     memset(&ramrod_param, 0, sizeof(ramrod_param));
3672
3673     /* Prepare ramrod parameters */
3674     ramrod_param.cid = 0;
3675     ramrod_param.cl_id = cl_id;
3676     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3677     ramrod_param.func_id = SC_FUNC(sc);
3678
3679     ramrod_param.pstate = &sc->sp_state;
3680     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3681
3682     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3683     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3684
3685     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3686
3687     ramrod_param.ramrod_flags = ramrod_flags;
3688     ramrod_param.rx_mode_flags = rx_mode_flags;
3689
3690     ramrod_param.rx_accept_flags = rx_accept_flags;
3691     ramrod_param.tx_accept_flags = tx_accept_flags;
3692
3693     rc = ecore_config_rx_mode(sc, &ramrod_param);
3694     if (rc < 0) {
3695         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3696             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3697             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3698             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3699             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3700         return (rc);
3701     }
3702
3703     return (0);
3704 }
3705
3706 static int
3707 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3708 {
3709     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3710     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3711     int rc;
3712
3713     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3714                                &tx_accept_flags);
3715     if (rc) {
3716         return (rc);
3717     }
3718
3719     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3720     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3721
3722     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3723     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3724                               rx_accept_flags, tx_accept_flags,
3725                               ramrod_flags));
3726 }
3727
3728 /* returns the "mcp load_code" according to global load_count array */
3729 static int
3730 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3731 {
3732     int path = SC_PATH(sc);
3733     int port = SC_PORT(sc);
3734
3735     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3736           path, load_count[path][0], load_count[path][1],
3737           load_count[path][2]);
3738     load_count[path][0]++;
3739     load_count[path][1 + port]++;
3740     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3741           path, load_count[path][0], load_count[path][1],
3742           load_count[path][2]);
3743     if (load_count[path][0] == 1) {
3744         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3745     } else if (load_count[path][1 + port] == 1) {
3746         return (FW_MSG_CODE_DRV_LOAD_PORT);
3747     } else {
3748         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3749     }
3750 }
3751
3752 /* returns the "mcp load_code" according to global load_count array */
3753 static int
3754 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3755 {
3756     int port = SC_PORT(sc);
3757     int path = SC_PATH(sc);
3758
3759     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3760           path, load_count[path][0], load_count[path][1],
3761           load_count[path][2]);
3762     load_count[path][0]--;
3763     load_count[path][1 + port]--;
3764     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3765           path, load_count[path][0], load_count[path][1],
3766           load_count[path][2]);
3767     if (load_count[path][0] == 0) {
3768         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3769     } else if (load_count[path][1 + port] == 0) {
3770         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3771     } else {
3772         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3773     }
3774 }
3775
3776 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3777 static uint32_t
3778 bxe_send_unload_req(struct bxe_softc *sc,
3779                     int              unload_mode)
3780 {
3781     uint32_t reset_code = 0;
3782
3783     /* Select the UNLOAD request mode */
3784     if (unload_mode == UNLOAD_NORMAL) {
3785         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3786     } else {
3787         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3788     }
3789
3790     /* Send the request to the MCP */
3791     if (!BXE_NOMCP(sc)) {
3792         reset_code = bxe_fw_command(sc, reset_code, 0);
3793     } else {
3794         reset_code = bxe_nic_unload_no_mcp(sc);
3795     }
3796
3797     return (reset_code);
3798 }
3799
3800 /* send UNLOAD_DONE command to the MCP */
3801 static void
3802 bxe_send_unload_done(struct bxe_softc *sc,
3803                      uint8_t          keep_link)
3804 {
3805     uint32_t reset_param =
3806         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3807
3808     /* Report UNLOAD_DONE to MCP */
3809     if (!BXE_NOMCP(sc)) {
3810         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3811     }
3812 }
3813
3814 static int
3815 bxe_func_wait_started(struct bxe_softc *sc)
3816 {
3817     int tout = 50;
3818
3819     if (!sc->port.pmf) {
3820         return (0);
3821     }
3822
3823     /*
3824      * (assumption: No Attention from MCP at this stage)
3825      * PMF probably in the middle of TX disable/enable transaction
3826      * 1. Sync IRS for default SB
3827      * 2. Sync SP queue - this guarantees us that attention handling started
3828      * 3. Wait, that TX disable/enable transaction completes
3829      *
3830      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3831      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3832      * received completion for the transaction the state is TX_STOPPED.
3833      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3834      * transaction.
3835      */
3836
3837     /* XXX make sure default SB ISR is done */
3838     /* need a way to synchronize an irq (intr_mtx?) */
3839
3840     /* XXX flush any work queues */
3841
3842     while (ecore_func_get_state(sc, &sc->func_obj) !=
3843            ECORE_F_STATE_STARTED && tout--) {
3844         DELAY(20000);
3845     }
3846
3847     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3848         /*
3849          * Failed to complete the transaction in a "good way"
3850          * Force both transactions with CLR bit.
3851          */
3852         struct ecore_func_state_params func_params = { NULL };
3853
3854         BLOGE(sc, "Unexpected function state! "
3855                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3856
3857         func_params.f_obj = &sc->func_obj;
3858         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3859
3860         /* STARTED-->TX_STOPPED */
3861         func_params.cmd = ECORE_F_CMD_TX_STOP;
3862         ecore_func_state_change(sc, &func_params);
3863
3864         /* TX_STOPPED-->STARTED */
3865         func_params.cmd = ECORE_F_CMD_TX_START;
3866         return (ecore_func_state_change(sc, &func_params));
3867     }
3868
3869     return (0);
3870 }
3871
3872 static int
3873 bxe_stop_queue(struct bxe_softc *sc,
3874                int              index)
3875 {
3876     struct bxe_fastpath *fp = &sc->fp[index];
3877     struct ecore_queue_state_params q_params = { NULL };
3878     int rc;
3879
3880     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3881
3882     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3883     /* We want to wait for completion in this context */
3884     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3885
3886     /* Stop the primary connection: */
3887
3888     /* ...halt the connection */
3889     q_params.cmd = ECORE_Q_CMD_HALT;
3890     rc = ecore_queue_state_change(sc, &q_params);
3891     if (rc) {
3892         return (rc);
3893     }
3894
3895     /* ...terminate the connection */
3896     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3897     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3898     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3899     rc = ecore_queue_state_change(sc, &q_params);
3900     if (rc) {
3901         return (rc);
3902     }
3903
3904     /* ...delete cfc entry */
3905     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3906     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3907     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3908     return (ecore_queue_state_change(sc, &q_params));
3909 }
3910
3911 /* wait for the outstanding SP commands */
3912 static inline uint8_t
3913 bxe_wait_sp_comp(struct bxe_softc *sc,
3914                  unsigned long    mask)
3915 {
3916     unsigned long tmp;
3917     int tout = 5000; /* wait for 5 secs tops */
3918
3919     while (tout--) {
3920         mb();
3921         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3922             return (TRUE);
3923         }
3924
3925         DELAY(1000);
3926     }
3927
3928     mb();
3929
3930     tmp = atomic_load_acq_long(&sc->sp_state);
3931     if (tmp & mask) {
3932         BLOGE(sc, "Filtering completion timed out: "
3933                   "sp_state 0x%lx, mask 0x%lx\n",
3934               tmp, mask);
3935         return (FALSE);
3936     }
3937
3938     return (FALSE);
3939 }
3940
3941 static int
3942 bxe_func_stop(struct bxe_softc *sc)
3943 {
3944     struct ecore_func_state_params func_params = { NULL };
3945     int rc;
3946
3947     /* prepare parameters for function state transitions */
3948     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3949     func_params.f_obj = &sc->func_obj;
3950     func_params.cmd = ECORE_F_CMD_STOP;
3951
3952     /*
3953      * Try to stop the function the 'good way'. If it fails (in case
3954      * of a parity error during bxe_chip_cleanup()) and we are
3955      * not in a debug mode, perform a state transaction in order to
3956      * enable further HW_RESET transaction.
3957      */
3958     rc = ecore_func_state_change(sc, &func_params);
3959     if (rc) {
3960         BLOGE(sc, "FUNC_STOP ramrod failed. "
3961                   "Running a dry transaction (%d)\n", rc);
3962         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3963         return (ecore_func_state_change(sc, &func_params));
3964     }
3965
3966     return (0);
3967 }
3968
3969 static int
3970 bxe_reset_hw(struct bxe_softc *sc,
3971              uint32_t         load_code)
3972 {
3973     struct ecore_func_state_params func_params = { NULL };
3974
3975     /* Prepare parameters for function state transitions */
3976     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3977
3978     func_params.f_obj = &sc->func_obj;
3979     func_params.cmd = ECORE_F_CMD_HW_RESET;
3980
3981     func_params.params.hw_init.load_phase = load_code;
3982
3983     return (ecore_func_state_change(sc, &func_params));
3984 }
3985
3986 static void
3987 bxe_int_disable_sync(struct bxe_softc *sc,
3988                      int              disable_hw)
3989 {
3990     if (disable_hw) {
3991         /* prevent the HW from sending interrupts */
3992         bxe_int_disable(sc);
3993     }
3994
3995     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
3996     /* make sure all ISRs are done */
3997
3998     /* XXX make sure sp_task is not running */
3999     /* cancel and flush work queues */
4000 }
4001
4002 static void
4003 bxe_chip_cleanup(struct bxe_softc *sc,
4004                  uint32_t         unload_mode,
4005                  uint8_t          keep_link)
4006 {
4007     int port = SC_PORT(sc);
4008     struct ecore_mcast_ramrod_params rparam = { NULL };
4009     uint32_t reset_code;
4010     int i, rc = 0;
4011
4012     bxe_drain_tx_queues(sc);
4013
4014     /* give HW time to discard old tx messages */
4015     DELAY(1000);
4016
4017     /* Clean all ETH MACs */
4018     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4019     if (rc < 0) {
4020         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4021     }
4022
4023     /* Clean up UC list  */
4024     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4025     if (rc < 0) {
4026         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4027     }
4028
4029     /* Disable LLH */
4030     if (!CHIP_IS_E1(sc)) {
4031         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4032     }
4033
4034     /* Set "drop all" to stop Rx */
4035
4036     /*
4037      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4038      * a race between the completion code and this code.
4039      */
4040     BXE_MCAST_LOCK(sc);
4041
4042     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4043         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4044     } else {
4045         bxe_set_storm_rx_mode(sc);
4046     }
4047
4048     /* Clean up multicast configuration */
4049     rparam.mcast_obj = &sc->mcast_obj;
4050     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4051     if (rc < 0) {
4052         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4053     }
4054
4055     BXE_MCAST_UNLOCK(sc);
4056
4057     // XXX bxe_iov_chip_cleanup(sc);
4058
4059     /*
4060      * Send the UNLOAD_REQUEST to the MCP. This will return if
4061      * this function should perform FUNCTION, PORT, or COMMON HW
4062      * reset.
4063      */
4064     reset_code = bxe_send_unload_req(sc, unload_mode);
4065
4066     /*
4067      * (assumption: No Attention from MCP at this stage)
4068      * PMF probably in the middle of TX disable/enable transaction
4069      */
4070     rc = bxe_func_wait_started(sc);
4071     if (rc) {
4072         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4073     }
4074
4075     /*
4076      * Close multi and leading connections
4077      * Completions for ramrods are collected in a synchronous way
4078      */
4079     for (i = 0; i < sc->num_queues; i++) {
4080         if (bxe_stop_queue(sc, i)) {
4081             goto unload_error;
4082         }
4083     }
4084
4085     /*
4086      * If SP settings didn't get completed so far - something
4087      * very wrong has happen.
4088      */
4089     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4090         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4091     }
4092
4093 unload_error:
4094
4095     rc = bxe_func_stop(sc);
4096     if (rc) {
4097         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4098     }
4099
4100     /* disable HW interrupts */
4101     bxe_int_disable_sync(sc, TRUE);
4102
4103     /* detach interrupts */
4104     bxe_interrupt_detach(sc);
4105
4106     /* Reset the chip */
4107     rc = bxe_reset_hw(sc, reset_code);
4108     if (rc) {
4109         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4110     }
4111
4112     /* Report UNLOAD_DONE to MCP */
4113     bxe_send_unload_done(sc, keep_link);
4114 }
4115
4116 static void
4117 bxe_disable_close_the_gate(struct bxe_softc *sc)
4118 {
4119     uint32_t val;
4120     int port = SC_PORT(sc);
4121
4122     BLOGD(sc, DBG_LOAD,
4123           "Disabling 'close the gates'\n");
4124
4125     if (CHIP_IS_E1(sc)) {
4126         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4127                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4128         val = REG_RD(sc, addr);
4129         val &= ~(0x300);
4130         REG_WR(sc, addr, val);
4131     } else {
4132         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4133         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4134                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4135         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4136     }
4137 }
4138
4139 /*
4140  * Cleans the object that have internal lists without sending
4141  * ramrods. Should be run when interrutps are disabled.
4142  */
4143 static void
4144 bxe_squeeze_objects(struct bxe_softc *sc)
4145 {
4146     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4147     struct ecore_mcast_ramrod_params rparam = { NULL };
4148     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4149     int rc;
4150
4151     /* Cleanup MACs' object first... */
4152
4153     /* Wait for completion of requested */
4154     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4155     /* Perform a dry cleanup */
4156     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4157
4158     /* Clean ETH primary MAC */
4159     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4160     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4161                              &ramrod_flags);
4162     if (rc != 0) {
4163         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4164     }
4165
4166     /* Cleanup UC list */
4167     vlan_mac_flags = 0;
4168     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4169     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4170                              &ramrod_flags);
4171     if (rc != 0) {
4172         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4173     }
4174
4175     /* Now clean mcast object... */
4176
4177     rparam.mcast_obj = &sc->mcast_obj;
4178     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4179
4180     /* Add a DEL command... */
4181     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4182     if (rc < 0) {
4183         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4184     }
4185
4186     /* now wait until all pending commands are cleared */
4187
4188     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4189     while (rc != 0) {
4190         if (rc < 0) {
4191             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4192             return;
4193         }
4194
4195         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4196     }
4197 }
4198
4199 /* stop the controller */
4200 static __noinline int
4201 bxe_nic_unload(struct bxe_softc *sc,
4202                uint32_t         unload_mode,
4203                uint8_t          keep_link)
4204 {
4205     uint8_t global = FALSE;
4206     uint32_t val;
4207
4208     BXE_CORE_LOCK_ASSERT(sc);
4209
4210     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4211
4212     /* mark driver as unloaded in shmem2 */
4213     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4214         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4215         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4216                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4217     }
4218
4219     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4220         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4221         /*
4222          * We can get here if the driver has been unloaded
4223          * during parity error recovery and is either waiting for a
4224          * leader to complete or for other functions to unload and
4225          * then ifconfig down has been issued. In this case we want to
4226          * unload and let other functions to complete a recovery
4227          * process.
4228          */
4229         sc->recovery_state = BXE_RECOVERY_DONE;
4230         sc->is_leader = 0;
4231         bxe_release_leader_lock(sc);
4232         mb();
4233
4234         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4235         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4236             " state = 0x%x\n", sc->recovery_state, sc->state);
4237         return (-1);
4238     }
4239
4240     /*
4241      * Nothing to do during unload if previous bxe_nic_load()
4242      * did not completed succesfully - all resourses are released.
4243      */
4244     if ((sc->state == BXE_STATE_CLOSED) ||
4245         (sc->state == BXE_STATE_ERROR)) {
4246         return (0);
4247     }
4248
4249     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4250     mb();
4251
4252     /* stop tx */
4253     bxe_tx_disable(sc);
4254
4255     sc->rx_mode = BXE_RX_MODE_NONE;
4256     /* XXX set rx mode ??? */
4257
4258     if (IS_PF(sc) && !sc->grcdump_done) {
4259         /* set ALWAYS_ALIVE bit in shmem */
4260         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4261
4262         bxe_drv_pulse(sc);
4263
4264         bxe_stats_handle(sc, STATS_EVENT_STOP);
4265         bxe_save_statistics(sc);
4266     }
4267
4268     /* wait till consumers catch up with producers in all queues */
4269     bxe_drain_tx_queues(sc);
4270
4271     /* if VF indicate to PF this function is going down (PF will delete sp
4272      * elements and clear initializations
4273      */
4274     if (IS_VF(sc)) {
4275         ; /* bxe_vfpf_close_vf(sc); */
4276     } else if (unload_mode != UNLOAD_RECOVERY) {
4277         /* if this is a normal/close unload need to clean up chip */
4278         if (!sc->grcdump_done)
4279             bxe_chip_cleanup(sc, unload_mode, keep_link);
4280     } else {
4281         /* Send the UNLOAD_REQUEST to the MCP */
4282         bxe_send_unload_req(sc, unload_mode);
4283
4284         /*
4285          * Prevent transactions to host from the functions on the
4286          * engine that doesn't reset global blocks in case of global
4287          * attention once gloabl blocks are reset and gates are opened
4288          * (the engine which leader will perform the recovery
4289          * last).
4290          */
4291         if (!CHIP_IS_E1x(sc)) {
4292             bxe_pf_disable(sc);
4293         }
4294
4295         /* disable HW interrupts */
4296         bxe_int_disable_sync(sc, TRUE);
4297
4298         /* detach interrupts */
4299         bxe_interrupt_detach(sc);
4300
4301         /* Report UNLOAD_DONE to MCP */
4302         bxe_send_unload_done(sc, FALSE);
4303     }
4304
4305     /*
4306      * At this stage no more interrupts will arrive so we may safely clean
4307      * the queue'able objects here in case they failed to get cleaned so far.
4308      */
4309     if (IS_PF(sc)) {
4310         bxe_squeeze_objects(sc);
4311     }
4312
4313     /* There should be no more pending SP commands at this stage */
4314     sc->sp_state = 0;
4315
4316     sc->port.pmf = 0;
4317
4318     bxe_free_fp_buffers(sc);
4319
4320     if (IS_PF(sc)) {
4321         bxe_free_mem(sc);
4322     }
4323
4324     bxe_free_fw_stats_mem(sc);
4325
4326     sc->state = BXE_STATE_CLOSED;
4327
4328     /*
4329      * Check if there are pending parity attentions. If there are - set
4330      * RECOVERY_IN_PROGRESS.
4331      */
4332     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4333         bxe_set_reset_in_progress(sc);
4334
4335         /* Set RESET_IS_GLOBAL if needed */
4336         if (global) {
4337             bxe_set_reset_global(sc);
4338         }
4339     }
4340
4341     /*
4342      * The last driver must disable a "close the gate" if there is no
4343      * parity attention or "process kill" pending.
4344      */
4345     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4346         bxe_reset_is_done(sc, SC_PATH(sc))) {
4347         bxe_disable_close_the_gate(sc);
4348     }
4349
4350     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4351
4352     return (0);
4353 }
4354
4355 /*
4356  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4357  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4358  */
4359 static int
4360 bxe_ifmedia_update(struct ifnet *ifp)
4361 {
4362     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4363     struct ifmedia *ifm;
4364
4365     ifm = &sc->ifmedia;
4366
4367     /* We only support Ethernet media type. */
4368     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4369         return (EINVAL);
4370     }
4371
4372     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4373     case IFM_AUTO:
4374          break;
4375     case IFM_10G_CX4:
4376     case IFM_10G_SR:
4377     case IFM_10G_T:
4378     case IFM_10G_TWINAX:
4379     default:
4380         /* We don't support changing the media type. */
4381         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4382               IFM_SUBTYPE(ifm->ifm_media));
4383         return (EINVAL);
4384     }
4385
4386     return (0);
4387 }
4388
4389 /*
4390  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4391  */
4392 static void
4393 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4394 {
4395     struct bxe_softc *sc = ifp->if_softc;
4396
4397     /* Report link down if the driver isn't running. */
4398     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4399         ifmr->ifm_active |= IFM_NONE;
4400         return;
4401     }
4402
4403     /* Setup the default interface info. */
4404     ifmr->ifm_status = IFM_AVALID;
4405     ifmr->ifm_active = IFM_ETHER;
4406
4407     if (sc->link_vars.link_up) {
4408         ifmr->ifm_status |= IFM_ACTIVE;
4409     } else {
4410         ifmr->ifm_active |= IFM_NONE;
4411         return;
4412     }
4413
4414     ifmr->ifm_active |= sc->media;
4415
4416     if (sc->link_vars.duplex == DUPLEX_FULL) {
4417         ifmr->ifm_active |= IFM_FDX;
4418     } else {
4419         ifmr->ifm_active |= IFM_HDX;
4420     }
4421 }
4422
4423 static int
4424 bxe_ioctl_nvram(struct bxe_softc *sc,
4425                 uint32_t         priv_op,
4426                 struct ifreq     *ifr)
4427 {
4428     struct bxe_nvram_data nvdata_base;
4429     struct bxe_nvram_data *nvdata;
4430     int len;
4431     int error = 0;
4432
4433     copyin(ifr->ifr_data, &nvdata_base, sizeof(nvdata_base));
4434
4435     len = (sizeof(struct bxe_nvram_data) +
4436            nvdata_base.len -
4437            sizeof(uint32_t));
4438
4439     if (len > sizeof(struct bxe_nvram_data)) {
4440         if ((nvdata = (struct bxe_nvram_data *)
4441                  malloc(len, M_DEVBUF,
4442                         (M_NOWAIT | M_ZERO))) == NULL) {
4443             BLOGE(sc, "BXE_IOC_RD_NVRAM malloc failed priv_op 0x%x "
4444                 " len = 0x%x\n", priv_op, len);
4445             return (1);
4446         }
4447         memcpy(nvdata, &nvdata_base, sizeof(struct bxe_nvram_data));
4448     } else {
4449         nvdata = &nvdata_base;
4450     }
4451
4452     if (priv_op == BXE_IOC_RD_NVRAM) {
4453         BLOGD(sc, DBG_IOCTL, "IOC_RD_NVRAM 0x%x %d\n",
4454               nvdata->offset, nvdata->len);
4455         error = bxe_nvram_read(sc,
4456                                nvdata->offset,
4457                                (uint8_t *)nvdata->value,
4458                                nvdata->len);
4459         copyout(nvdata, ifr->ifr_data, len);
4460     } else { /* BXE_IOC_WR_NVRAM */
4461         BLOGD(sc, DBG_IOCTL, "IOC_WR_NVRAM 0x%x %d\n",
4462               nvdata->offset, nvdata->len);
4463         copyin(ifr->ifr_data, nvdata, len);
4464         error = bxe_nvram_write(sc,
4465                                 nvdata->offset,
4466                                 (uint8_t *)nvdata->value,
4467                                 nvdata->len);
4468     }
4469
4470     if (len > sizeof(struct bxe_nvram_data)) {
4471         free(nvdata, M_DEVBUF);
4472     }
4473
4474     return (error);
4475 }
4476
4477 static int
4478 bxe_ioctl_stats_show(struct bxe_softc *sc,
4479                      uint32_t         priv_op,
4480                      struct ifreq     *ifr)
4481 {
4482     const size_t str_size   = (BXE_NUM_ETH_STATS * STAT_NAME_LEN);
4483     const size_t stats_size = (BXE_NUM_ETH_STATS * sizeof(uint64_t));
4484     caddr_t p_tmp;
4485     uint32_t *offset;
4486     int i;
4487
4488     switch (priv_op)
4489     {
4490     case BXE_IOC_STATS_SHOW_NUM:
4491         memset(ifr->ifr_data, 0, sizeof(union bxe_stats_show_data));
4492         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.num =
4493             BXE_NUM_ETH_STATS;
4494         ((union bxe_stats_show_data *)ifr->ifr_data)->desc.len =
4495             STAT_NAME_LEN;
4496         return (0);
4497
4498     case BXE_IOC_STATS_SHOW_STR:
4499         memset(ifr->ifr_data, 0, str_size);
4500         p_tmp = ifr->ifr_data;
4501         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4502             strcpy(p_tmp, bxe_eth_stats_arr[i].string);
4503             p_tmp += STAT_NAME_LEN;
4504         }
4505         return (0);
4506
4507     case BXE_IOC_STATS_SHOW_CNT:
4508         memset(ifr->ifr_data, 0, stats_size);
4509         p_tmp = ifr->ifr_data;
4510         for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
4511             offset = ((uint32_t *)&sc->eth_stats +
4512                       bxe_eth_stats_arr[i].offset);
4513             switch (bxe_eth_stats_arr[i].size) {
4514             case 4:
4515                 *((uint64_t *)p_tmp) = (uint64_t)*offset;
4516                 break;
4517             case 8:
4518                 *((uint64_t *)p_tmp) = HILO_U64(*offset, *(offset + 1));
4519                 break;
4520             default:
4521                 *((uint64_t *)p_tmp) = 0;
4522             }
4523             p_tmp += sizeof(uint64_t);
4524         }
4525         return (0);
4526
4527     default:
4528         return (-1);
4529     }
4530 }
4531
4532 static void
4533 bxe_handle_chip_tq(void *context,
4534                    int  pending)
4535 {
4536     struct bxe_softc *sc = (struct bxe_softc *)context;
4537     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4538
4539     switch (work)
4540     {
4541     case CHIP_TQ_REINIT:
4542         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4543             /* restart the interface */
4544             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4545             bxe_periodic_stop(sc);
4546             BXE_CORE_LOCK(sc);
4547             bxe_stop_locked(sc);
4548             bxe_init_locked(sc);
4549             BXE_CORE_UNLOCK(sc);
4550         }
4551         break;
4552
4553     default:
4554         break;
4555     }
4556 }
4557
4558 /*
4559  * Handles any IOCTL calls from the operating system.
4560  *
4561  * Returns:
4562  *   0 = Success, >0 Failure
4563  */
4564 static int
4565 bxe_ioctl(struct ifnet *ifp,
4566           u_long       command,
4567           caddr_t      data)
4568 {
4569     struct bxe_softc *sc = ifp->if_softc;
4570     struct ifreq *ifr = (struct ifreq *)data;
4571     struct bxe_nvram_data *nvdata;
4572     uint32_t priv_op;
4573     int mask = 0;
4574     int reinit = 0;
4575     int error = 0;
4576
4577     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4578     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4579
4580     switch (command)
4581     {
4582     case SIOCSIFMTU:
4583         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4584               ifr->ifr_mtu);
4585
4586         if (sc->mtu == ifr->ifr_mtu) {
4587             /* nothing to change */
4588             break;
4589         }
4590
4591         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4592             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4593                   ifr->ifr_mtu, mtu_min, mtu_max);
4594             error = EINVAL;
4595             break;
4596         }
4597
4598         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4599                              (unsigned long)ifr->ifr_mtu);
4600         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4601                               (unsigned long)ifr->ifr_mtu);
4602
4603         reinit = 1;
4604         break;
4605
4606     case SIOCSIFFLAGS:
4607         /* toggle the interface state up or down */
4608         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4609
4610         BXE_CORE_LOCK(sc);
4611         /* check if the interface is up */
4612         if (ifp->if_flags & IFF_UP) {
4613             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4614                 /* set the receive mode flags */
4615                 bxe_set_rx_mode(sc);
4616             } else {
4617                 bxe_init_locked(sc);
4618             }
4619         } else {
4620             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4621                 bxe_periodic_stop(sc);
4622                 bxe_stop_locked(sc);
4623             }
4624         }
4625         BXE_CORE_UNLOCK(sc);
4626
4627         break;
4628
4629     case SIOCADDMULTI:
4630     case SIOCDELMULTI:
4631         /* add/delete multicast addresses */
4632         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4633
4634         /* check if the interface is up */
4635         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4636             /* set the receive mode flags */
4637             BXE_CORE_LOCK(sc);
4638             bxe_set_rx_mode(sc);
4639             BXE_CORE_UNLOCK(sc); 
4640         }
4641
4642         break;
4643
4644     case SIOCSIFCAP:
4645         /* find out which capabilities have changed */
4646         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4647
4648         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4649               mask);
4650
4651         /* toggle the LRO capabilites enable flag */
4652         if (mask & IFCAP_LRO) {
4653             ifp->if_capenable ^= IFCAP_LRO;
4654             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4655                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4656             reinit = 1;
4657         }
4658
4659         /* toggle the TXCSUM checksum capabilites enable flag */
4660         if (mask & IFCAP_TXCSUM) {
4661             ifp->if_capenable ^= IFCAP_TXCSUM;
4662             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4663                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4664             if (ifp->if_capenable & IFCAP_TXCSUM) {
4665                 ifp->if_hwassist = (CSUM_IP       |
4666                                     CSUM_TCP      |
4667                                     CSUM_UDP      |
4668                                     CSUM_TSO      |
4669                                     CSUM_TCP_IPV6 |
4670                                     CSUM_UDP_IPV6);
4671             } else {
4672                 ifp->if_hwassist = 0;
4673             }
4674         }
4675
4676         /* toggle the RXCSUM checksum capabilities enable flag */
4677         if (mask & IFCAP_RXCSUM) {
4678             ifp->if_capenable ^= IFCAP_RXCSUM;
4679             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4680                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4681             if (ifp->if_capenable & IFCAP_RXCSUM) {
4682                 ifp->if_hwassist = (CSUM_IP       |
4683                                     CSUM_TCP      |
4684                                     CSUM_UDP      |
4685                                     CSUM_TSO      |
4686                                     CSUM_TCP_IPV6 |
4687                                     CSUM_UDP_IPV6);
4688             } else {
4689                 ifp->if_hwassist = 0;
4690             }
4691         }
4692
4693         /* toggle TSO4 capabilities enabled flag */
4694         if (mask & IFCAP_TSO4) {
4695             ifp->if_capenable ^= IFCAP_TSO4;
4696             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4697                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4698         }
4699
4700         /* toggle TSO6 capabilities enabled flag */
4701         if (mask & IFCAP_TSO6) {
4702             ifp->if_capenable ^= IFCAP_TSO6;
4703             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4704                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4705         }
4706
4707         /* toggle VLAN_HWTSO capabilities enabled flag */
4708         if (mask & IFCAP_VLAN_HWTSO) {
4709             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4710             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4711                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4712         }
4713
4714         /* toggle VLAN_HWCSUM capabilities enabled flag */
4715         if (mask & IFCAP_VLAN_HWCSUM) {
4716             /* XXX investigate this... */
4717             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4718             error = EINVAL;
4719         }
4720
4721         /* toggle VLAN_MTU capabilities enable flag */
4722         if (mask & IFCAP_VLAN_MTU) {
4723             /* XXX investigate this... */
4724             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4725             error = EINVAL;
4726         }
4727
4728         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4729         if (mask & IFCAP_VLAN_HWTAGGING) {
4730             /* XXX investigate this... */
4731             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4732             error = EINVAL;
4733         }
4734
4735         /* toggle VLAN_HWFILTER capabilities enabled flag */
4736         if (mask & IFCAP_VLAN_HWFILTER) {
4737             /* XXX investigate this... */
4738             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4739             error = EINVAL;
4740         }
4741
4742         /* XXX not yet...
4743          * IFCAP_WOL_MAGIC
4744          */
4745
4746         break;
4747
4748     case SIOCSIFMEDIA:
4749     case SIOCGIFMEDIA:
4750         /* set/get interface media */
4751         BLOGD(sc, DBG_IOCTL,
4752               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4753               (command & 0xff));
4754         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4755         break;
4756
4757     case SIOCGPRIVATE_0:
4758         copyin(ifr->ifr_data, &priv_op, sizeof(priv_op));
4759
4760         switch (priv_op)
4761         {
4762         case BXE_IOC_RD_NVRAM:
4763         case BXE_IOC_WR_NVRAM:
4764             nvdata = (struct bxe_nvram_data *)ifr->ifr_data;
4765             BLOGD(sc, DBG_IOCTL,
4766                   "Received Private NVRAM ioctl addr=0x%x size=%u\n",
4767                   nvdata->offset, nvdata->len);
4768             error = bxe_ioctl_nvram(sc, priv_op, ifr);
4769             break;
4770
4771         case BXE_IOC_STATS_SHOW_NUM:
4772         case BXE_IOC_STATS_SHOW_STR:
4773         case BXE_IOC_STATS_SHOW_CNT:
4774             BLOGD(sc, DBG_IOCTL, "Received Private Stats ioctl (%d)\n",
4775                   priv_op);
4776             error = bxe_ioctl_stats_show(sc, priv_op, ifr);
4777             break;
4778
4779         default:
4780             BLOGW(sc, "Received Private Unknown ioctl (%d)\n", priv_op);
4781             error = EINVAL;
4782             break;
4783         }
4784
4785         break;
4786
4787     default:
4788         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4789               (command & 0xff));
4790         error = ether_ioctl(ifp, command, data);
4791         break;
4792     }
4793
4794     if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4795         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4796               "Re-initializing hardware from IOCTL change\n");
4797         bxe_periodic_stop(sc);
4798         BXE_CORE_LOCK(sc);
4799         bxe_stop_locked(sc);
4800         bxe_init_locked(sc);
4801         BXE_CORE_UNLOCK(sc);
4802     }
4803
4804     return (error);
4805 }
4806
4807 static __noinline void
4808 bxe_dump_mbuf(struct bxe_softc *sc,
4809               struct mbuf      *m,
4810               uint8_t          contents)
4811 {
4812     char * type;
4813     int i = 0;
4814
4815     if (!(sc->debug & DBG_MBUF)) {
4816         return;
4817     }
4818
4819     if (m == NULL) {
4820         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4821         return;
4822     }
4823
4824     while (m) {
4825         BLOGD(sc, DBG_MBUF,
4826               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4827               i, m, m->m_len, m->m_flags,
4828               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4829
4830         if (m->m_flags & M_PKTHDR) {
4831              BLOGD(sc, DBG_MBUF,
4832                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4833                    i, m->m_pkthdr.len, m->m_flags,
4834                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4835                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4836                    "\22M_PROMISC\23M_NOFREE",
4837                    (int)m->m_pkthdr.csum_flags,
4838                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4839                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4840                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4841                    "\14CSUM_PSEUDO_HDR");
4842         }
4843
4844         if (m->m_flags & M_EXT) {
4845             switch (m->m_ext.ext_type) {
4846             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4847             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4848             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4849             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4850             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4851             case EXT_PACKET:     type = "EXT_PACKET";     break;
4852             case EXT_MBUF:       type = "EXT_MBUF";       break;
4853             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4854             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4855             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4856             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4857             default:             type = "UNKNOWN";        break;
4858             }
4859
4860             BLOGD(sc, DBG_MBUF,
4861                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4862                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4863         }
4864
4865         if (contents) {
4866             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4867         }
4868
4869         m = m->m_next;
4870         i++;
4871     }
4872 }
4873
4874 /*
4875  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4876  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4877  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4878  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4879  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4880  */
4881 static int
4882 bxe_chktso_window(struct bxe_softc  *sc,
4883                   int               nsegs,
4884                   bus_dma_segment_t *segs,
4885                   struct mbuf       *m)
4886 {
4887     uint32_t num_wnds, wnd_size, wnd_sum;
4888     int32_t frag_idx, wnd_idx;
4889     unsigned short lso_mss;
4890     int defrag;
4891
4892     defrag = 0;
4893     wnd_sum = 0;
4894     wnd_size = 10;
4895     num_wnds = nsegs - wnd_size;
4896     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4897
4898     /*
4899      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4900      * first window sum of data while skipping the first assuming it is the
4901      * header in FreeBSD.
4902      */
4903     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4904         wnd_sum += htole16(segs[frag_idx].ds_len);
4905     }
4906
4907     /* check the first 10 bd window size */
4908     if (wnd_sum < lso_mss) {
4909         return (1);
4910     }
4911
4912     /* run through the windows */
4913     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4914         /* subtract the first mbuf->m_len of the last wndw(-header) */
4915         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4916         /* add the next mbuf len to the len of our new window */
4917         wnd_sum += htole16(segs[frag_idx].ds_len);
4918         if (wnd_sum < lso_mss) {
4919             return (1);
4920         }
4921     }
4922
4923     return (0);
4924 }
4925
4926 static uint8_t
4927 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4928                     struct mbuf         *m,
4929                     uint32_t            *parsing_data)
4930 {
4931     struct ether_vlan_header *eh = NULL;
4932     struct ip *ip4 = NULL;
4933     struct ip6_hdr *ip6 = NULL;
4934     caddr_t ip = NULL;
4935     struct tcphdr *th = NULL;
4936     int e_hlen, ip_hlen, l4_off;
4937     uint16_t proto;
4938
4939     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4940         /* no L4 checksum offload needed */
4941         return (0);
4942     }
4943
4944     /* get the Ethernet header */
4945     eh = mtod(m, struct ether_vlan_header *);
4946
4947     /* handle VLAN encapsulation if present */
4948     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4949         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4950         proto  = ntohs(eh->evl_proto);
4951     } else {
4952         e_hlen = ETHER_HDR_LEN;
4953         proto  = ntohs(eh->evl_encap_proto);
4954     }
4955
4956     switch (proto) {
4957     case ETHERTYPE_IP:
4958         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4959         ip4 = (m->m_len < sizeof(struct ip)) ?
4960                   (struct ip *)m->m_next->m_data :
4961                   (struct ip *)(m->m_data + e_hlen);
4962         /* ip_hl is number of 32-bit words */
4963         ip_hlen = (ip4->ip_hl << 2);
4964         ip = (caddr_t)ip4;
4965         break;
4966     case ETHERTYPE_IPV6:
4967         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4968         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4969                   (struct ip6_hdr *)m->m_next->m_data :
4970                   (struct ip6_hdr *)(m->m_data + e_hlen);
4971         /* XXX cannot support offload with IPv6 extensions */
4972         ip_hlen = sizeof(struct ip6_hdr);
4973         ip = (caddr_t)ip6;
4974         break;
4975     default:
4976         /* We can't offload in this case... */
4977         /* XXX error stat ??? */
4978         return (0);
4979     }
4980
4981     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4982     l4_off = (e_hlen + ip_hlen);
4983
4984     *parsing_data |=
4985         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4986          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4987
4988     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4989                                   CSUM_TSO |
4990                                   CSUM_TCP_IPV6)) {
4991         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4992         th = (struct tcphdr *)(ip + ip_hlen);
4993         /* th_off is number of 32-bit words */
4994         *parsing_data |= ((th->th_off <<
4995                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4996                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4997         return (l4_off + (th->th_off << 2)); /* entire header length */
4998     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4999                                          CSUM_UDP_IPV6)) {
5000         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5001         return (l4_off + sizeof(struct udphdr)); /* entire header length */
5002     } else {
5003         /* XXX error stat ??? */
5004         return (0);
5005     }
5006 }
5007
5008 static uint8_t
5009 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
5010                  struct mbuf                *m,
5011                  struct eth_tx_parse_bd_e1x *pbd)
5012 {
5013     struct ether_vlan_header *eh = NULL;
5014     struct ip *ip4 = NULL;
5015     struct ip6_hdr *ip6 = NULL;
5016     caddr_t ip = NULL;
5017     struct tcphdr *th = NULL;
5018     struct udphdr *uh = NULL;
5019     int e_hlen, ip_hlen;
5020     uint16_t proto;
5021     uint8_t hlen;
5022     uint16_t tmp_csum;
5023     uint32_t *tmp_uh;
5024
5025     /* get the Ethernet header */
5026     eh = mtod(m, struct ether_vlan_header *);
5027
5028     /* handle VLAN encapsulation if present */
5029     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
5030         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
5031         proto  = ntohs(eh->evl_proto);
5032     } else {
5033         e_hlen = ETHER_HDR_LEN;
5034         proto  = ntohs(eh->evl_encap_proto);
5035     }
5036
5037     switch (proto) {
5038     case ETHERTYPE_IP:
5039         /* get the IP header, if mbuf len < 20 then header in next mbuf */
5040         ip4 = (m->m_len < sizeof(struct ip)) ?
5041                   (struct ip *)m->m_next->m_data :
5042                   (struct ip *)(m->m_data + e_hlen);
5043         /* ip_hl is number of 32-bit words */
5044         ip_hlen = (ip4->ip_hl << 1);
5045         ip = (caddr_t)ip4;
5046         break;
5047     case ETHERTYPE_IPV6:
5048         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
5049         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
5050                   (struct ip6_hdr *)m->m_next->m_data :
5051                   (struct ip6_hdr *)(m->m_data + e_hlen);
5052         /* XXX cannot support offload with IPv6 extensions */
5053         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
5054         ip = (caddr_t)ip6;
5055         break;
5056     default:
5057         /* We can't offload in this case... */
5058         /* XXX error stat ??? */
5059         return (0);
5060     }
5061
5062     hlen = (e_hlen >> 1);
5063
5064     /* note that rest of global_data is indirectly zeroed here */
5065     if (m->m_flags & M_VLANTAG) {
5066         pbd->global_data =
5067             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
5068     } else {
5069         pbd->global_data = htole16(hlen);
5070     }
5071
5072     pbd->ip_hlen_w = ip_hlen;
5073
5074     hlen += pbd->ip_hlen_w;
5075
5076     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
5077
5078     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5079                                   CSUM_TSO |
5080                                   CSUM_TCP_IPV6)) {
5081         th = (struct tcphdr *)(ip + (ip_hlen << 1));
5082         /* th_off is number of 32-bit words */
5083         hlen += (uint16_t)(th->th_off << 1);
5084     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5085                                          CSUM_UDP_IPV6)) {
5086         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5087         hlen += (sizeof(struct udphdr) / 2);
5088     } else {
5089         /* valid case as only CSUM_IP was set */
5090         return (0);
5091     }
5092
5093     pbd->total_hlen_w = htole16(hlen);
5094
5095     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5096                                   CSUM_TSO |
5097                                   CSUM_TCP_IPV6)) {
5098         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5099         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5100     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5101                                          CSUM_UDP_IPV6)) {
5102         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5103
5104         /*
5105          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5106          * checksums and does not know anything about the UDP header and where
5107          * the checksum field is located. It only knows about TCP. Therefore
5108          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5109          * offload. Since the checksum field offset for TCP is 16 bytes and
5110          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5111          * bytes less than the start of the UDP header. This allows the
5112          * hardware to write the checksum in the correct spot. But the
5113          * hardware will compute a checksum which includes the last 10 bytes
5114          * of the IP header. To correct this we tweak the stack computed
5115          * pseudo checksum by folding in the calculation of the inverse
5116          * checksum for those final 10 bytes of the IP header. This allows
5117          * the correct checksum to be computed by the hardware.
5118          */
5119
5120         /* set pointer 10 bytes before UDP header */
5121         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5122
5123         /* calculate a pseudo header checksum over the first 10 bytes */
5124         tmp_csum = in_pseudo(*tmp_uh,
5125                              *(tmp_uh + 1),
5126                              *(uint16_t *)(tmp_uh + 2));
5127
5128         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5129     }
5130
5131     return (hlen * 2); /* entire header length, number of bytes */
5132 }
5133
5134 static void
5135 bxe_set_pbd_lso_e2(struct mbuf *m,
5136                    uint32_t    *parsing_data)
5137 {
5138     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5139                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5140                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5141
5142     /* XXX test for IPv6 with extension header... */
5143 }
5144
5145 static void
5146 bxe_set_pbd_lso(struct mbuf                *m,
5147                 struct eth_tx_parse_bd_e1x *pbd)
5148 {
5149     struct ether_vlan_header *eh = NULL;
5150     struct ip *ip = NULL;
5151     struct tcphdr *th = NULL;
5152     int e_hlen;
5153
5154     /* get the Ethernet header */
5155     eh = mtod(m, struct ether_vlan_header *);
5156
5157     /* handle VLAN encapsulation if present */
5158     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5159                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5160
5161     /* get the IP and TCP header, with LSO entire header in first mbuf */
5162     /* XXX assuming IPv4 */
5163     ip = (struct ip *)(m->m_data + e_hlen);
5164     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5165
5166     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5167     pbd->tcp_send_seq = ntohl(th->th_seq);
5168     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5169
5170 #if 1
5171         /* XXX IPv4 */
5172         pbd->ip_id = ntohs(ip->ip_id);
5173         pbd->tcp_pseudo_csum =
5174             ntohs(in_pseudo(ip->ip_src.s_addr,
5175                             ip->ip_dst.s_addr,
5176                             htons(IPPROTO_TCP)));
5177 #else
5178         /* XXX IPv6 */
5179         pbd->tcp_pseudo_csum =
5180             ntohs(in_pseudo(&ip6->ip6_src,
5181                             &ip6->ip6_dst,
5182                             htons(IPPROTO_TCP)));
5183 #endif
5184
5185     pbd->global_data |=
5186         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5187 }
5188
5189 /*
5190  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5191  * visible to the controller.
5192  *
5193  * If an mbuf is submitted to this routine and cannot be given to the
5194  * controller (e.g. it has too many fragments) then the function may free
5195  * the mbuf and return to the caller.
5196  *
5197  * Returns:
5198  *   0 = Success, !0 = Failure
5199  *   Note the side effect that an mbuf may be freed if it causes a problem.
5200  */
5201 static int
5202 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5203 {
5204     bus_dma_segment_t segs[32];
5205     struct mbuf *m0;
5206     struct bxe_sw_tx_bd *tx_buf;
5207     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5208     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5209     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5210     struct eth_tx_bd *tx_data_bd;
5211     struct eth_tx_bd *tx_total_pkt_size_bd;
5212     struct eth_tx_start_bd *tx_start_bd;
5213     uint16_t bd_prod, pkt_prod, total_pkt_size;
5214     uint8_t mac_type;
5215     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5216     struct bxe_softc *sc;
5217     uint16_t tx_bd_avail;
5218     struct ether_vlan_header *eh;
5219     uint32_t pbd_e2_parsing_data = 0;
5220     uint8_t hlen = 0;
5221     int tmp_bd;
5222     int i;
5223
5224     sc = fp->sc;
5225
5226     M_ASSERTPKTHDR(*m_head);
5227
5228     m0 = *m_head;
5229     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5230     tx_start_bd = NULL;
5231     tx_data_bd = NULL;
5232     tx_total_pkt_size_bd = NULL;
5233
5234     /* get the H/W pointer for packets and BDs */
5235     pkt_prod = fp->tx_pkt_prod;
5236     bd_prod = fp->tx_bd_prod;
5237
5238     mac_type = UNICAST_ADDRESS;
5239
5240     /* map the mbuf into the next open DMAable memory */
5241     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5242     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5243                                     tx_buf->m_map, m0,
5244                                     segs, &nsegs, BUS_DMA_NOWAIT);
5245
5246     /* mapping errors */
5247     if(__predict_false(error != 0)) {
5248         fp->eth_q_stats.tx_dma_mapping_failure++;
5249         if (error == ENOMEM) {
5250             /* resource issue, try again later */
5251             rc = ENOMEM;
5252         } else if (error == EFBIG) {
5253             /* possibly recoverable with defragmentation */
5254             fp->eth_q_stats.mbuf_defrag_attempts++;
5255             m0 = m_defrag(*m_head, M_DONTWAIT);
5256             if (m0 == NULL) {
5257                 fp->eth_q_stats.mbuf_defrag_failures++;
5258                 rc = ENOBUFS;
5259             } else {
5260                 /* defrag successful, try mapping again */
5261                 *m_head = m0;
5262                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5263                                                 tx_buf->m_map, m0,
5264                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5265                 if (error) {
5266                     fp->eth_q_stats.tx_dma_mapping_failure++;
5267                     rc = error;
5268                 }
5269             }
5270         } else {
5271             /* unknown, unrecoverable mapping error */
5272             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5273             bxe_dump_mbuf(sc, m0, FALSE);
5274             rc = error;
5275         }
5276
5277         goto bxe_tx_encap_continue;
5278     }
5279
5280     tx_bd_avail = bxe_tx_avail(sc, fp);
5281
5282     /* make sure there is enough room in the send queue */
5283     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5284         /* Recoverable, try again later. */
5285         fp->eth_q_stats.tx_hw_queue_full++;
5286         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5287         rc = ENOMEM;
5288         goto bxe_tx_encap_continue;
5289     }
5290
5291     /* capture the current H/W TX chain high watermark */
5292     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5293                         (TX_BD_USABLE - tx_bd_avail))) {
5294         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5295     }
5296
5297     /* make sure it fits in the packet window */
5298     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5299         /*
5300          * The mbuf may be to big for the controller to handle. If the frame
5301          * is a TSO frame we'll need to do an additional check.
5302          */
5303         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5304             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5305                 goto bxe_tx_encap_continue; /* OK to send */
5306             } else {
5307                 fp->eth_q_stats.tx_window_violation_tso++;
5308             }
5309         } else {
5310             fp->eth_q_stats.tx_window_violation_std++;
5311         }
5312
5313         /* lets try to defragment this mbuf and remap it */
5314         fp->eth_q_stats.mbuf_defrag_attempts++;
5315         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5316
5317         m0 = m_defrag(*m_head, M_DONTWAIT);
5318         if (m0 == NULL) {
5319             fp->eth_q_stats.mbuf_defrag_failures++;
5320             /* Ugh, just drop the frame... :( */
5321             rc = ENOBUFS;
5322         } else {
5323             /* defrag successful, try mapping again */
5324             *m_head = m0;
5325             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5326                                             tx_buf->m_map, m0,
5327                                             segs, &nsegs, BUS_DMA_NOWAIT);
5328             if (error) {
5329                 fp->eth_q_stats.tx_dma_mapping_failure++;
5330                 /* No sense in trying to defrag/copy chain, drop it. :( */
5331                 rc = error;
5332             }
5333             else {
5334                 /* if the chain is still too long then drop it */
5335                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5336                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5337                     rc = ENODEV;
5338                 }
5339             }
5340         }
5341     }
5342
5343 bxe_tx_encap_continue:
5344
5345     /* Check for errors */
5346     if (rc) {
5347         if (rc == ENOMEM) {
5348             /* recoverable try again later  */
5349         } else {
5350             fp->eth_q_stats.tx_soft_errors++;
5351             fp->eth_q_stats.mbuf_alloc_tx--;
5352             m_freem(*m_head);
5353             *m_head = NULL;
5354         }
5355
5356         return (rc);
5357     }
5358
5359     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5360     if (m0->m_flags & M_BCAST) {
5361         mac_type = BROADCAST_ADDRESS;
5362     } else if (m0->m_flags & M_MCAST) {
5363         mac_type = MULTICAST_ADDRESS;
5364     }
5365
5366     /* store the mbuf into the mbuf ring */
5367     tx_buf->m        = m0;
5368     tx_buf->first_bd = fp->tx_bd_prod;
5369     tx_buf->flags    = 0;
5370
5371     /* prepare the first transmit (start) BD for the mbuf */
5372     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5373
5374     BLOGD(sc, DBG_TX,
5375           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5376           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5377
5378     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5379     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5380     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5381     total_pkt_size += tx_start_bd->nbytes;
5382     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5383
5384     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5385
5386     /* all frames have at least Start BD + Parsing BD */
5387     nbds = nsegs + 1;
5388     tx_start_bd->nbd = htole16(nbds);
5389
5390     if (m0->m_flags & M_VLANTAG) {
5391         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5392         tx_start_bd->bd_flags.as_bitfield |=
5393             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5394     } else {
5395         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5396         if (IS_VF(sc)) {
5397             /* map ethernet header to find type and header length */
5398             eh = mtod(m0, struct ether_vlan_header *);
5399             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5400         } else {
5401             /* used by FW for packet accounting */
5402             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5403         }
5404     }
5405
5406     /*
5407      * add a parsing BD from the chain. The parsing BD is always added
5408      * though it is only used for TSO and chksum
5409      */
5410     bd_prod = TX_BD_NEXT(bd_prod);
5411
5412     if (m0->m_pkthdr.csum_flags) {
5413         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5414             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5415             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5416         }
5417
5418         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5419             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5420                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5421         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5422             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5423                                                   ETH_TX_BD_FLAGS_IS_UDP |
5424                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5425         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5426                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5427             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5428         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5429             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5430                                                   ETH_TX_BD_FLAGS_IS_UDP);
5431         }
5432     }
5433
5434     if (!CHIP_IS_E1x(sc)) {
5435         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5436         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5437
5438         if (m0->m_pkthdr.csum_flags) {
5439             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5440         }
5441
5442         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5443                  mac_type);
5444     } else {
5445         uint16_t global_data = 0;
5446
5447         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5448         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5449
5450         if (m0->m_pkthdr.csum_flags) {
5451             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5452         }
5453
5454         SET_FLAG(global_data,
5455                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5456         pbd_e1x->global_data |= htole16(global_data);
5457     }
5458
5459     /* setup the parsing BD with TSO specific info */
5460     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5461         fp->eth_q_stats.tx_ofld_frames_lso++;
5462         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5463
5464         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5465             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5466
5467             /* split the first BD into header/data making the fw job easy */
5468             nbds++;
5469             tx_start_bd->nbd = htole16(nbds);
5470             tx_start_bd->nbytes = htole16(hlen);
5471
5472             bd_prod = TX_BD_NEXT(bd_prod);
5473
5474             /* new transmit BD after the tx_parse_bd */
5475             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5476             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5477             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5478             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5479             if (tx_total_pkt_size_bd == NULL) {
5480                 tx_total_pkt_size_bd = tx_data_bd;
5481             }
5482
5483             BLOGD(sc, DBG_TX,
5484                   "TSO split header size is %d (%x:%x) nbds %d\n",
5485                   le16toh(tx_start_bd->nbytes),
5486                   le32toh(tx_start_bd->addr_hi),
5487                   le32toh(tx_start_bd->addr_lo),
5488                   nbds);
5489         }
5490
5491         if (!CHIP_IS_E1x(sc)) {
5492             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5493         } else {
5494             bxe_set_pbd_lso(m0, pbd_e1x);
5495         }
5496     }
5497
5498     if (pbd_e2_parsing_data) {
5499         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5500     }
5501
5502     /* prepare remaining BDs, start tx bd contains first seg/frag */
5503     for (i = 1; i < nsegs ; i++) {
5504         bd_prod = TX_BD_NEXT(bd_prod);
5505         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5506         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5507         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5508         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5509         if (tx_total_pkt_size_bd == NULL) {
5510             tx_total_pkt_size_bd = tx_data_bd;
5511         }
5512         total_pkt_size += tx_data_bd->nbytes;
5513     }
5514
5515     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5516
5517     if (tx_total_pkt_size_bd != NULL) {
5518         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5519     }
5520
5521     if (__predict_false(sc->debug & DBG_TX)) {
5522         tmp_bd = tx_buf->first_bd;
5523         for (i = 0; i < nbds; i++)
5524         {
5525             if (i == 0) {
5526                 BLOGD(sc, DBG_TX,
5527                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5528                       "bd_flags=0x%x hdr_nbds=%d\n",
5529                       tx_start_bd,
5530                       tmp_bd,
5531                       le16toh(tx_start_bd->nbd),
5532                       le16toh(tx_start_bd->vlan_or_ethertype),
5533                       tx_start_bd->bd_flags.as_bitfield,
5534                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5535             } else if (i == 1) {
5536                 if (pbd_e1x) {
5537                     BLOGD(sc, DBG_TX,
5538                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5539                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5540                           "tcp_seq=%u total_hlen_w=%u\n",
5541                           pbd_e1x,
5542                           tmp_bd,
5543                           pbd_e1x->global_data,
5544                           pbd_e1x->ip_hlen_w,
5545                           pbd_e1x->ip_id,
5546                           pbd_e1x->lso_mss,
5547                           pbd_e1x->tcp_flags,
5548                           pbd_e1x->tcp_pseudo_csum,
5549                           pbd_e1x->tcp_send_seq,
5550                           le16toh(pbd_e1x->total_hlen_w));
5551                 } else { /* if (pbd_e2) */
5552                     BLOGD(sc, DBG_TX,
5553                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5554                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5555                           pbd_e2,
5556                           tmp_bd,
5557                           pbd_e2->data.mac_addr.dst_hi,
5558                           pbd_e2->data.mac_addr.dst_mid,
5559                           pbd_e2->data.mac_addr.dst_lo,
5560                           pbd_e2->data.mac_addr.src_hi,
5561                           pbd_e2->data.mac_addr.src_mid,
5562                           pbd_e2->data.mac_addr.src_lo,
5563                           pbd_e2->parsing_data);
5564                 }
5565             }
5566
5567             if (i != 1) { /* skip parse db as it doesn't hold data */
5568                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5569                 BLOGD(sc, DBG_TX,
5570                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5571                       tx_data_bd,
5572                       tmp_bd,
5573                       le16toh(tx_data_bd->nbytes),
5574                       le32toh(tx_data_bd->addr_hi),
5575                       le32toh(tx_data_bd->addr_lo));
5576             }
5577
5578             tmp_bd = TX_BD_NEXT(tmp_bd);
5579         }
5580     }
5581
5582     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5583
5584     /* update TX BD producer index value for next TX */
5585     bd_prod = TX_BD_NEXT(bd_prod);
5586
5587     /*
5588      * If the chain of tx_bd's describing this frame is adjacent to or spans
5589      * an eth_tx_next_bd element then we need to increment the nbds value.
5590      */
5591     if (TX_BD_IDX(bd_prod) < nbds) {
5592         nbds++;
5593     }
5594
5595     /* don't allow reordering of writes for nbd and packets */
5596     mb();
5597
5598     fp->tx_db.data.prod += nbds;
5599
5600     /* producer points to the next free tx_bd at this point */
5601     fp->tx_pkt_prod++;
5602     fp->tx_bd_prod = bd_prod;
5603
5604     DOORBELL(sc, fp->index, fp->tx_db.raw);
5605
5606     fp->eth_q_stats.tx_pkts++;
5607
5608     /* Prevent speculative reads from getting ahead of the status block. */
5609     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5610                       0, 0, BUS_SPACE_BARRIER_READ);
5611
5612     /* Prevent speculative reads from getting ahead of the doorbell. */
5613     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5614                       0, 0, BUS_SPACE_BARRIER_READ);
5615
5616     return (0);
5617 }
5618
5619 static void
5620 bxe_tx_start_locked(struct bxe_softc    *sc,
5621                     struct ifnet        *ifp,
5622                     struct bxe_fastpath *fp)
5623 {
5624     struct mbuf *m = NULL;
5625     int tx_count = 0;
5626     uint16_t tx_bd_avail;
5627
5628     BXE_FP_TX_LOCK_ASSERT(fp);
5629
5630     /* keep adding entries while there are frames to send */
5631     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5632
5633         /*
5634          * check for any frames to send
5635          * dequeue can still be NULL even if queue is not empty
5636          */
5637         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5638         if (__predict_false(m == NULL)) {
5639             break;
5640         }
5641
5642         /* the mbuf now belongs to us */
5643         fp->eth_q_stats.mbuf_alloc_tx++;
5644
5645         /*
5646          * Put the frame into the transmit ring. If we don't have room,
5647          * place the mbuf back at the head of the TX queue, set the
5648          * OACTIVE flag, and wait for the NIC to drain the chain.
5649          */
5650         if (__predict_false(bxe_tx_encap(fp, &m))) {
5651             fp->eth_q_stats.tx_encap_failures++;
5652             if (m != NULL) {
5653                 /* mark the TX queue as full and return the frame */
5654                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5655                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5656                 fp->eth_q_stats.mbuf_alloc_tx--;
5657                 fp->eth_q_stats.tx_queue_xoff++;
5658             }
5659
5660             /* stop looking for more work */
5661             break;
5662         }
5663
5664         /* the frame was enqueued successfully */
5665         tx_count++;
5666
5667         /* send a copy of the frame to any BPF listeners. */
5668         BPF_MTAP(ifp, m);
5669
5670         tx_bd_avail = bxe_tx_avail(sc, fp);
5671
5672         /* handle any completions if we're running low */
5673         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5674             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5675             bxe_txeof(sc, fp);
5676             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5677                 break;
5678             }
5679         }
5680     }
5681
5682     /* all TX packets were dequeued and/or the tx ring is full */
5683     if (tx_count > 0) {
5684         /* reset the TX watchdog timeout timer */
5685         fp->watchdog_timer = BXE_TX_TIMEOUT;
5686     }
5687 }
5688
5689 /* Legacy (non-RSS) dispatch routine */
5690 static void
5691 bxe_tx_start(struct ifnet *ifp)
5692 {
5693     struct bxe_softc *sc;
5694     struct bxe_fastpath *fp;
5695
5696     sc = ifp->if_softc;
5697
5698     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5699         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5700         return;
5701     }
5702
5703     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5704         BLOGW(sc, "Interface TX queue is full, ignoring transmit request\n");
5705         return;
5706     }
5707
5708     if (!sc->link_vars.link_up) {
5709         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5710         return;
5711     }
5712
5713     fp = &sc->fp[0];
5714
5715     BXE_FP_TX_LOCK(fp);
5716     bxe_tx_start_locked(sc, ifp, fp);
5717     BXE_FP_TX_UNLOCK(fp);
5718 }
5719
5720 #if __FreeBSD_version >= 800000
5721
5722 static int
5723 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5724                        struct ifnet        *ifp,
5725                        struct bxe_fastpath *fp,
5726                        struct mbuf         *m)
5727 {
5728     struct buf_ring *tx_br = fp->tx_br;
5729     struct mbuf *next;
5730     int depth, rc, tx_count;
5731     uint16_t tx_bd_avail;
5732
5733     rc = tx_count = 0;
5734
5735     BXE_FP_TX_LOCK_ASSERT(fp);
5736
5737     if (!tx_br) {
5738         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5739         return (EINVAL);
5740     }
5741
5742     if (!sc->link_vars.link_up ||
5743         (ifp->if_drv_flags &
5744         (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
5745         rc = drbr_enqueue(ifp, tx_br, m);
5746         goto bxe_tx_mq_start_locked_exit;
5747     }
5748
5749     /* fetch the depth of the driver queue */
5750     depth = drbr_inuse(ifp, tx_br);
5751     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5752         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5753     }
5754
5755     if (m == NULL) {
5756         /* no new work, check for pending frames */
5757         next = drbr_dequeue(ifp, tx_br);
5758     } else if (drbr_needs_enqueue(ifp, tx_br)) {
5759         /* have both new and pending work, maintain packet order */
5760         rc = drbr_enqueue(ifp, tx_br, m);
5761         if (rc != 0) {
5762             fp->eth_q_stats.tx_soft_errors++;
5763             goto bxe_tx_mq_start_locked_exit;
5764         }
5765         next = drbr_dequeue(ifp, tx_br);
5766     } else {
5767         /* new work only and nothing pending */
5768         next = m;
5769     }
5770
5771     /* keep adding entries while there are frames to send */
5772     while (next != NULL) {
5773
5774         /* the mbuf now belongs to us */
5775         fp->eth_q_stats.mbuf_alloc_tx++;
5776
5777         /*
5778          * Put the frame into the transmit ring. If we don't have room,
5779          * place the mbuf back at the head of the TX queue, set the
5780          * OACTIVE flag, and wait for the NIC to drain the chain.
5781          */
5782         rc = bxe_tx_encap(fp, &next);
5783         if (__predict_false(rc != 0)) {
5784             fp->eth_q_stats.tx_encap_failures++;
5785             if (next != NULL) {
5786                 /* mark the TX queue as full and save the frame */
5787                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5788                 /* XXX this may reorder the frame */
5789                 rc = drbr_enqueue(ifp, tx_br, next);
5790                 fp->eth_q_stats.mbuf_alloc_tx--;
5791                 fp->eth_q_stats.tx_frames_deferred++;
5792             }
5793
5794             /* stop looking for more work */
5795             break;
5796         }
5797
5798         /* the transmit frame was enqueued successfully */
5799         tx_count++;
5800
5801         /* send a copy of the frame to any BPF listeners */
5802         BPF_MTAP(ifp, next);
5803
5804         tx_bd_avail = bxe_tx_avail(sc, fp);
5805
5806         /* handle any completions if we're running low */
5807         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5808             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5809             bxe_txeof(sc, fp);
5810             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5811                 break;
5812             }
5813         }
5814
5815         next = drbr_dequeue(ifp, tx_br);
5816     }
5817
5818     /* all TX packets were dequeued and/or the tx ring is full */
5819     if (tx_count > 0) {
5820         /* reset the TX watchdog timeout timer */
5821         fp->watchdog_timer = BXE_TX_TIMEOUT;
5822     }
5823
5824 bxe_tx_mq_start_locked_exit:
5825
5826     return (rc);
5827 }
5828
5829 /* Multiqueue (TSS) dispatch routine. */
5830 static int
5831 bxe_tx_mq_start(struct ifnet *ifp,
5832                 struct mbuf  *m)
5833 {
5834     struct bxe_softc *sc = ifp->if_softc;
5835     struct bxe_fastpath *fp;
5836     int fp_index, rc;
5837
5838     fp_index = 0; /* default is the first queue */
5839
5840     /* change the queue if using flow ID */
5841     if ((m->m_flags & M_FLOWID) != 0) {
5842         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5843     }
5844
5845     fp = &sc->fp[fp_index];
5846
5847     if (BXE_FP_TX_TRYLOCK(fp)) {
5848         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5849         BXE_FP_TX_UNLOCK(fp);
5850     } else
5851         rc = drbr_enqueue(ifp, fp->tx_br, m);
5852
5853     return (rc);
5854 }
5855
5856 static void
5857 bxe_mq_flush(struct ifnet *ifp)
5858 {
5859     struct bxe_softc *sc = ifp->if_softc;
5860     struct bxe_fastpath *fp;
5861     struct mbuf *m;
5862     int i;
5863
5864     for (i = 0; i < sc->num_queues; i++) {
5865         fp = &sc->fp[i];
5866
5867         if (fp->state != BXE_FP_STATE_OPEN) {
5868             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5869                   fp->index, fp->state);
5870             continue;
5871         }
5872
5873         if (fp->tx_br != NULL) {
5874             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5875             BXE_FP_TX_LOCK(fp);
5876             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5877                 m_freem(m);
5878             }
5879             BXE_FP_TX_UNLOCK(fp);
5880         }
5881     }
5882
5883     if_qflush(ifp);
5884 }
5885
5886 #endif /* FreeBSD_version >= 800000 */
5887
5888 static uint16_t
5889 bxe_cid_ilt_lines(struct bxe_softc *sc)
5890 {
5891     if (IS_SRIOV(sc)) {
5892         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5893     }
5894     return (L2_ILT_LINES(sc));
5895 }
5896
5897 static void
5898 bxe_ilt_set_info(struct bxe_softc *sc)
5899 {
5900     struct ilt_client_info *ilt_client;
5901     struct ecore_ilt *ilt = sc->ilt;
5902     uint16_t line = 0;
5903
5904     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5905     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5906
5907     /* CDU */
5908     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5909     ilt_client->client_num = ILT_CLIENT_CDU;
5910     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5911     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5912     ilt_client->start = line;
5913     line += bxe_cid_ilt_lines(sc);
5914
5915     if (CNIC_SUPPORT(sc)) {
5916         line += CNIC_ILT_LINES;
5917     }
5918
5919     ilt_client->end = (line - 1);
5920
5921     BLOGD(sc, DBG_LOAD,
5922           "ilt client[CDU]: start %d, end %d, "
5923           "psz 0x%x, flags 0x%x, hw psz %d\n",
5924           ilt_client->start, ilt_client->end,
5925           ilt_client->page_size,
5926           ilt_client->flags,
5927           ilog2(ilt_client->page_size >> 12));
5928
5929     /* QM */
5930     if (QM_INIT(sc->qm_cid_count)) {
5931         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5932         ilt_client->client_num = ILT_CLIENT_QM;
5933         ilt_client->page_size = QM_ILT_PAGE_SZ;
5934         ilt_client->flags = 0;
5935         ilt_client->start = line;
5936
5937         /* 4 bytes for each cid */
5938         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5939                              QM_ILT_PAGE_SZ);
5940
5941         ilt_client->end = (line - 1);
5942
5943         BLOGD(sc, DBG_LOAD,
5944               "ilt client[QM]: start %d, end %d, "
5945               "psz 0x%x, flags 0x%x, hw psz %d\n",
5946               ilt_client->start, ilt_client->end,
5947               ilt_client->page_size, ilt_client->flags,
5948               ilog2(ilt_client->page_size >> 12));
5949     }
5950
5951     if (CNIC_SUPPORT(sc)) {
5952         /* SRC */
5953         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5954         ilt_client->client_num = ILT_CLIENT_SRC;
5955         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5956         ilt_client->flags = 0;
5957         ilt_client->start = line;
5958         line += SRC_ILT_LINES;
5959         ilt_client->end = (line - 1);
5960
5961         BLOGD(sc, DBG_LOAD,
5962               "ilt client[SRC]: start %d, end %d, "
5963               "psz 0x%x, flags 0x%x, hw psz %d\n",
5964               ilt_client->start, ilt_client->end,
5965               ilt_client->page_size, ilt_client->flags,
5966               ilog2(ilt_client->page_size >> 12));
5967
5968         /* TM */
5969         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5970         ilt_client->client_num = ILT_CLIENT_TM;
5971         ilt_client->page_size = TM_ILT_PAGE_SZ;
5972         ilt_client->flags = 0;
5973         ilt_client->start = line;
5974         line += TM_ILT_LINES;
5975         ilt_client->end = (line - 1);
5976
5977         BLOGD(sc, DBG_LOAD,
5978               "ilt client[TM]: start %d, end %d, "
5979               "psz 0x%x, flags 0x%x, hw psz %d\n",
5980               ilt_client->start, ilt_client->end,
5981               ilt_client->page_size, ilt_client->flags,
5982               ilog2(ilt_client->page_size >> 12));
5983     }
5984
5985     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5986 }
5987
5988 static void
5989 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5990 {
5991     int i;
5992     uint32_t rx_buf_size;
5993
5994     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5995
5996     for (i = 0; i < sc->num_queues; i++) {
5997         if(rx_buf_size <= MCLBYTES){
5998             sc->fp[i].rx_buf_size = rx_buf_size;
5999             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6000         }else if (rx_buf_size <= MJUMPAGESIZE){
6001             sc->fp[i].rx_buf_size = rx_buf_size;
6002             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6003         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
6004             sc->fp[i].rx_buf_size = MCLBYTES;
6005             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6006         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
6007             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
6008             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
6009         }else {
6010             sc->fp[i].rx_buf_size = MCLBYTES;
6011             sc->fp[i].mbuf_alloc_size = MCLBYTES;
6012         }
6013     }
6014 }
6015
6016 static int
6017 bxe_alloc_ilt_mem(struct bxe_softc *sc)
6018 {
6019     int rc = 0;
6020
6021     if ((sc->ilt =
6022          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
6023                                     M_BXE_ILT,
6024                                     (M_NOWAIT | M_ZERO))) == NULL) {
6025         rc = 1;
6026     }
6027
6028     return (rc);
6029 }
6030
6031 static int
6032 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
6033 {
6034     int rc = 0;
6035
6036     if ((sc->ilt->lines =
6037          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
6038                                     M_BXE_ILT,
6039                                     (M_NOWAIT | M_ZERO))) == NULL) {
6040         rc = 1;
6041     }
6042
6043     return (rc);
6044 }
6045
6046 static void
6047 bxe_free_ilt_mem(struct bxe_softc *sc)
6048 {
6049     if (sc->ilt != NULL) {
6050         free(sc->ilt, M_BXE_ILT);
6051         sc->ilt = NULL;
6052     }
6053 }
6054
6055 static void
6056 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
6057 {
6058     if (sc->ilt->lines != NULL) {
6059         free(sc->ilt->lines, M_BXE_ILT);
6060         sc->ilt->lines = NULL;
6061     }
6062 }
6063
6064 static void
6065 bxe_free_mem(struct bxe_softc *sc)
6066 {
6067     int i;
6068
6069     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6070         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6071         sc->context[i].vcxt = NULL;
6072         sc->context[i].size = 0;
6073     }
6074
6075     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6076
6077     bxe_free_ilt_lines_mem(sc);
6078
6079 }
6080
6081 static int
6082 bxe_alloc_mem(struct bxe_softc *sc)
6083 {
6084     int context_size;
6085     int allocated;
6086     int i;
6087
6088     /*
6089      * Allocate memory for CDU context:
6090      * This memory is allocated separately and not in the generic ILT
6091      * functions because CDU differs in few aspects:
6092      * 1. There can be multiple entities allocating memory for context -
6093      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6094      * its own ILT lines.
6095      * 2. Since CDU page-size is not a single 4KB page (which is the case
6096      * for the other ILT clients), to be efficient we want to support
6097      * allocation of sub-page-size in the last entry.
6098      * 3. Context pointers are used by the driver to pass to FW / update
6099      * the context (for the other ILT clients the pointers are used just to
6100      * free the memory during unload).
6101      */
6102     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6103     for (i = 0, allocated = 0; allocated < context_size; i++) {
6104         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6105                                   (context_size - allocated));
6106
6107         if (bxe_dma_alloc(sc, sc->context[i].size,
6108                           &sc->context[i].vcxt_dma,
6109                           "cdu context") != 0) {
6110             bxe_free_mem(sc);
6111             return (-1);
6112         }
6113
6114         sc->context[i].vcxt =
6115             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6116
6117         allocated += sc->context[i].size;
6118     }
6119
6120     bxe_alloc_ilt_lines_mem(sc);
6121
6122     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6123           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6124     {
6125         for (i = 0; i < 4; i++) {
6126             BLOGD(sc, DBG_LOAD,
6127                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6128                   i,
6129                   sc->ilt->clients[i].page_size,
6130                   sc->ilt->clients[i].start,
6131                   sc->ilt->clients[i].end,
6132                   sc->ilt->clients[i].client_num,
6133                   sc->ilt->clients[i].flags);
6134         }
6135     }
6136     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6137         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6138         bxe_free_mem(sc);
6139         return (-1);
6140     }
6141
6142     return (0);
6143 }
6144
6145 static void
6146 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6147 {
6148     struct bxe_softc *sc;
6149     int i;
6150
6151     sc = fp->sc;
6152
6153     if (fp->rx_mbuf_tag == NULL) {
6154         return;
6155     }
6156
6157     /* free all mbufs and unload all maps */
6158     for (i = 0; i < RX_BD_TOTAL; i++) {
6159         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6160             bus_dmamap_sync(fp->rx_mbuf_tag,
6161                             fp->rx_mbuf_chain[i].m_map,
6162                             BUS_DMASYNC_POSTREAD);
6163             bus_dmamap_unload(fp->rx_mbuf_tag,
6164                               fp->rx_mbuf_chain[i].m_map);
6165         }
6166
6167         if (fp->rx_mbuf_chain[i].m != NULL) {
6168             m_freem(fp->rx_mbuf_chain[i].m);
6169             fp->rx_mbuf_chain[i].m = NULL;
6170             fp->eth_q_stats.mbuf_alloc_rx--;
6171         }
6172     }
6173 }
6174
6175 static void
6176 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6177 {
6178     struct bxe_softc *sc;
6179     int i, max_agg_queues;
6180
6181     sc = fp->sc;
6182
6183     if (fp->rx_mbuf_tag == NULL) {
6184         return;
6185     }
6186
6187     max_agg_queues = MAX_AGG_QS(sc);
6188
6189     /* release all mbufs and unload all DMA maps in the TPA pool */
6190     for (i = 0; i < max_agg_queues; i++) {
6191         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6192             bus_dmamap_sync(fp->rx_mbuf_tag,
6193                             fp->rx_tpa_info[i].bd.m_map,
6194                             BUS_DMASYNC_POSTREAD);
6195             bus_dmamap_unload(fp->rx_mbuf_tag,
6196                               fp->rx_tpa_info[i].bd.m_map);
6197         }
6198
6199         if (fp->rx_tpa_info[i].bd.m != NULL) {
6200             m_freem(fp->rx_tpa_info[i].bd.m);
6201             fp->rx_tpa_info[i].bd.m = NULL;
6202             fp->eth_q_stats.mbuf_alloc_tpa--;
6203         }
6204     }
6205 }
6206
6207 static void
6208 bxe_free_sge_chain(struct bxe_fastpath *fp)
6209 {
6210     struct bxe_softc *sc;
6211     int i;
6212
6213     sc = fp->sc;
6214
6215     if (fp->rx_sge_mbuf_tag == NULL) {
6216         return;
6217     }
6218
6219     /* rree all mbufs and unload all maps */
6220     for (i = 0; i < RX_SGE_TOTAL; i++) {
6221         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6222             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6223                             fp->rx_sge_mbuf_chain[i].m_map,
6224                             BUS_DMASYNC_POSTREAD);
6225             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6226                               fp->rx_sge_mbuf_chain[i].m_map);
6227         }
6228
6229         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6230             m_freem(fp->rx_sge_mbuf_chain[i].m);
6231             fp->rx_sge_mbuf_chain[i].m = NULL;
6232             fp->eth_q_stats.mbuf_alloc_sge--;
6233         }
6234     }
6235 }
6236
6237 static void
6238 bxe_free_fp_buffers(struct bxe_softc *sc)
6239 {
6240     struct bxe_fastpath *fp;
6241     int i;
6242
6243     for (i = 0; i < sc->num_queues; i++) {
6244         fp = &sc->fp[i];
6245
6246 #if __FreeBSD_version >= 800000
6247         if (fp->tx_br != NULL) {
6248             /* just in case bxe_mq_flush() wasn't called */
6249             if (mtx_initialized(&fp->tx_mtx)) {
6250                 struct mbuf *m;
6251
6252                 BXE_FP_TX_LOCK(fp);
6253                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6254                     m_freem(m);
6255                 BXE_FP_TX_UNLOCK(fp);
6256             }
6257             buf_ring_free(fp->tx_br, M_DEVBUF);
6258             fp->tx_br = NULL;
6259         }
6260 #endif
6261
6262         /* free all RX buffers */
6263         bxe_free_rx_bd_chain(fp);
6264         bxe_free_tpa_pool(fp);
6265         bxe_free_sge_chain(fp);
6266
6267         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6268             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6269                   fp->eth_q_stats.mbuf_alloc_rx);
6270         }
6271
6272         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6273             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6274                   fp->eth_q_stats.mbuf_alloc_sge);
6275         }
6276
6277         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6278             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6279                   fp->eth_q_stats.mbuf_alloc_tpa);
6280         }
6281
6282         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6283             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6284                   fp->eth_q_stats.mbuf_alloc_tx);
6285         }
6286
6287         /* XXX verify all mbufs were reclaimed */
6288
6289         if (mtx_initialized(&fp->tx_mtx)) {
6290             mtx_destroy(&fp->tx_mtx);
6291         }
6292
6293         if (mtx_initialized(&fp->rx_mtx)) {
6294             mtx_destroy(&fp->rx_mtx);
6295         }
6296     }
6297 }
6298
6299 static int
6300 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6301                      uint16_t            prev_index,
6302                      uint16_t            index)
6303 {
6304     struct bxe_sw_rx_bd *rx_buf;
6305     struct eth_rx_bd *rx_bd;
6306     bus_dma_segment_t segs[1];
6307     bus_dmamap_t map;
6308     struct mbuf *m;
6309     int nsegs, rc;
6310
6311     rc = 0;
6312
6313     /* allocate the new RX BD mbuf */
6314     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6315     if (__predict_false(m == NULL)) {
6316         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6317         return (ENOBUFS);
6318     }
6319
6320     fp->eth_q_stats.mbuf_alloc_rx++;
6321
6322     /* initialize the mbuf buffer length */
6323     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6324
6325     /* map the mbuf into non-paged pool */
6326     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6327                                  fp->rx_mbuf_spare_map,
6328                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6329     if (__predict_false(rc != 0)) {
6330         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6331         m_freem(m);
6332         fp->eth_q_stats.mbuf_alloc_rx--;
6333         return (rc);
6334     }
6335
6336     /* all mbufs must map to a single segment */
6337     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6338
6339     /* release any existing RX BD mbuf mappings */
6340
6341     if (prev_index != index) {
6342         rx_buf = &fp->rx_mbuf_chain[prev_index];
6343
6344         if (rx_buf->m_map != NULL) {
6345             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6346                             BUS_DMASYNC_POSTREAD);
6347             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6348         }
6349
6350         /*
6351          * We only get here from bxe_rxeof() when the maximum number
6352          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6353          * holds the mbuf in the prev_index so it's OK to NULL it out
6354          * here without concern of a memory leak.
6355          */
6356         fp->rx_mbuf_chain[prev_index].m = NULL;
6357     }
6358
6359     rx_buf = &fp->rx_mbuf_chain[index];
6360
6361     if (rx_buf->m_map != NULL) {
6362         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6363                         BUS_DMASYNC_POSTREAD);
6364         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6365     }
6366
6367     /* save the mbuf and mapping info for a future packet */
6368     map = (prev_index != index) ?
6369               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6370     rx_buf->m_map = fp->rx_mbuf_spare_map;
6371     fp->rx_mbuf_spare_map = map;
6372     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6373                     BUS_DMASYNC_PREREAD);
6374     rx_buf->m = m;
6375
6376     rx_bd = &fp->rx_chain[index];
6377     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6378     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6379
6380     return (rc);
6381 }
6382
6383 static int
6384 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6385                       int                 queue)
6386 {
6387     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6388     bus_dma_segment_t segs[1];
6389     bus_dmamap_t map;
6390     struct mbuf *m;
6391     int nsegs;
6392     int rc = 0;
6393
6394     /* allocate the new TPA mbuf */
6395     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6396     if (__predict_false(m == NULL)) {
6397         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6398         return (ENOBUFS);
6399     }
6400
6401     fp->eth_q_stats.mbuf_alloc_tpa++;
6402
6403     /* initialize the mbuf buffer length */
6404     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6405
6406     /* map the mbuf into non-paged pool */
6407     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6408                                  fp->rx_tpa_info_mbuf_spare_map,
6409                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6410     if (__predict_false(rc != 0)) {
6411         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6412         m_free(m);
6413         fp->eth_q_stats.mbuf_alloc_tpa--;
6414         return (rc);
6415     }
6416
6417     /* all mbufs must map to a single segment */
6418     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6419
6420     /* release any existing TPA mbuf mapping */
6421     if (tpa_info->bd.m_map != NULL) {
6422         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6423                         BUS_DMASYNC_POSTREAD);
6424         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6425     }
6426
6427     /* save the mbuf and mapping info for the TPA mbuf */
6428     map = tpa_info->bd.m_map;
6429     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6430     fp->rx_tpa_info_mbuf_spare_map = map;
6431     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6432                     BUS_DMASYNC_PREREAD);
6433     tpa_info->bd.m = m;
6434     tpa_info->seg = segs[0];
6435
6436     return (rc);
6437 }
6438
6439 /*
6440  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6441  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6442  * chain.
6443  */
6444 static int
6445 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6446                       uint16_t            index)
6447 {
6448     struct bxe_sw_rx_bd *sge_buf;
6449     struct eth_rx_sge *sge;
6450     bus_dma_segment_t segs[1];
6451     bus_dmamap_t map;
6452     struct mbuf *m;
6453     int nsegs;
6454     int rc = 0;
6455
6456     /* allocate a new SGE mbuf */
6457     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6458     if (__predict_false(m == NULL)) {
6459         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6460         return (ENOMEM);
6461     }
6462
6463     fp->eth_q_stats.mbuf_alloc_sge++;
6464
6465     /* initialize the mbuf buffer length */
6466     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6467
6468     /* map the SGE mbuf into non-paged pool */
6469     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6470                                  fp->rx_sge_mbuf_spare_map,
6471                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6472     if (__predict_false(rc != 0)) {
6473         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6474         m_freem(m);
6475         fp->eth_q_stats.mbuf_alloc_sge--;
6476         return (rc);
6477     }
6478
6479     /* all mbufs must map to a single segment */
6480     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6481
6482     sge_buf = &fp->rx_sge_mbuf_chain[index];
6483
6484     /* release any existing SGE mbuf mapping */
6485     if (sge_buf->m_map != NULL) {
6486         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6487                         BUS_DMASYNC_POSTREAD);
6488         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6489     }
6490
6491     /* save the mbuf and mapping info for a future packet */
6492     map = sge_buf->m_map;
6493     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6494     fp->rx_sge_mbuf_spare_map = map;
6495     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6496                     BUS_DMASYNC_PREREAD);
6497     sge_buf->m = m;
6498
6499     sge = &fp->rx_sge_chain[index];
6500     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6501     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6502
6503     return (rc);
6504 }
6505
6506 static __noinline int
6507 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6508 {
6509     struct bxe_fastpath *fp;
6510     int i, j, rc = 0;
6511     int ring_prod, cqe_ring_prod;
6512     int max_agg_queues;
6513
6514     for (i = 0; i < sc->num_queues; i++) {
6515         fp = &sc->fp[i];
6516
6517 #if __FreeBSD_version >= 800000
6518         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
6519                                    M_DONTWAIT, &fp->tx_mtx);
6520         if (fp->tx_br == NULL) {
6521             BLOGE(sc, "buf_ring alloc fail for fp[%02d]\n", i);
6522             goto bxe_alloc_fp_buffers_error;
6523         }
6524 #endif
6525
6526         ring_prod = cqe_ring_prod = 0;
6527         fp->rx_bd_cons = 0;
6528         fp->rx_cq_cons = 0;
6529
6530         /* allocate buffers for the RX BDs in RX BD chain */
6531         for (j = 0; j < sc->max_rx_bufs; j++) {
6532             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6533             if (rc != 0) {
6534                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6535                       i, rc);
6536                 goto bxe_alloc_fp_buffers_error;
6537             }
6538
6539             ring_prod     = RX_BD_NEXT(ring_prod);
6540             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6541         }
6542
6543         fp->rx_bd_prod = ring_prod;
6544         fp->rx_cq_prod = cqe_ring_prod;
6545         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6546
6547         max_agg_queues = MAX_AGG_QS(sc);
6548
6549         fp->tpa_enable = TRUE;
6550
6551         /* fill the TPA pool */
6552         for (j = 0; j < max_agg_queues; j++) {
6553             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6554             if (rc != 0) {
6555                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6556                           i, j);
6557                 fp->tpa_enable = FALSE;
6558                 goto bxe_alloc_fp_buffers_error;
6559             }
6560
6561             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6562         }
6563
6564         if (fp->tpa_enable) {
6565             /* fill the RX SGE chain */
6566             ring_prod = 0;
6567             for (j = 0; j < RX_SGE_USABLE; j++) {
6568                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6569                 if (rc != 0) {
6570                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6571                               i, ring_prod);
6572                     fp->tpa_enable = FALSE;
6573                     ring_prod = 0;
6574                     goto bxe_alloc_fp_buffers_error;
6575                 }
6576
6577                 ring_prod = RX_SGE_NEXT(ring_prod);
6578             }
6579
6580             fp->rx_sge_prod = ring_prod;
6581         }
6582     }
6583
6584     return (0);
6585
6586 bxe_alloc_fp_buffers_error:
6587
6588     /* unwind what was already allocated */
6589     bxe_free_rx_bd_chain(fp);
6590     bxe_free_tpa_pool(fp);
6591     bxe_free_sge_chain(fp);
6592
6593     return (ENOBUFS);
6594 }
6595
6596 static void
6597 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6598 {
6599     bxe_dma_free(sc, &sc->fw_stats_dma);
6600
6601     sc->fw_stats_num = 0;
6602
6603     sc->fw_stats_req_size = 0;
6604     sc->fw_stats_req = NULL;
6605     sc->fw_stats_req_mapping = 0;
6606
6607     sc->fw_stats_data_size = 0;
6608     sc->fw_stats_data = NULL;
6609     sc->fw_stats_data_mapping = 0;
6610 }
6611
6612 static int
6613 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6614 {
6615     uint8_t num_queue_stats;
6616     int num_groups;
6617
6618     /* number of queues for statistics is number of eth queues */
6619     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6620
6621     /*
6622      * Total number of FW statistics requests =
6623      *   1 for port stats + 1 for PF stats + num of queues
6624      */
6625     sc->fw_stats_num = (2 + num_queue_stats);
6626
6627     /*
6628      * Request is built from stats_query_header and an array of
6629      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6630      * rules. The real number or requests is configured in the
6631      * stats_query_header.
6632      */
6633     num_groups =
6634         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6635          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6636
6637     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6638           sc->fw_stats_num, num_groups);
6639
6640     sc->fw_stats_req_size =
6641         (sizeof(struct stats_query_header) +
6642          (num_groups * sizeof(struct stats_query_cmd_group)));
6643
6644     /*
6645      * Data for statistics requests + stats_counter.
6646      * stats_counter holds per-STORM counters that are incremented when
6647      * STORM has finished with the current request. Memory for FCoE
6648      * offloaded statistics are counted anyway, even if they will not be sent.
6649      * VF stats are not accounted for here as the data of VF stats is stored
6650      * in memory allocated by the VF, not here.
6651      */
6652     sc->fw_stats_data_size =
6653         (sizeof(struct stats_counter) +
6654          sizeof(struct per_port_stats) +
6655          sizeof(struct per_pf_stats) +
6656          /* sizeof(struct fcoe_statistics_params) + */
6657          (sizeof(struct per_queue_stats) * num_queue_stats));
6658
6659     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6660                       &sc->fw_stats_dma, "fw stats") != 0) {
6661         bxe_free_fw_stats_mem(sc);
6662         return (-1);
6663     }
6664
6665     /* set up the shortcuts */
6666
6667     sc->fw_stats_req =
6668         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6669     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6670
6671     sc->fw_stats_data =
6672         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6673                                      sc->fw_stats_req_size);
6674     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6675                                  sc->fw_stats_req_size);
6676
6677     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6678           (uintmax_t)sc->fw_stats_req_mapping);
6679
6680     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6681           (uintmax_t)sc->fw_stats_data_mapping);
6682
6683     return (0);
6684 }
6685
6686 /*
6687  * Bits map:
6688  * 0-7  - Engine0 load counter.
6689  * 8-15 - Engine1 load counter.
6690  * 16   - Engine0 RESET_IN_PROGRESS bit.
6691  * 17   - Engine1 RESET_IN_PROGRESS bit.
6692  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6693  *        function on the engine
6694  * 19   - Engine1 ONE_IS_LOADED.
6695  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6696  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6697  *        for just the one belonging to its engine).
6698  */
6699 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6700 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6701 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6702 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6703 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6704 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6705 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6706 #define BXE_GLOBAL_RESET_BIT      0x00040000
6707
6708 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6709 static void
6710 bxe_set_reset_global(struct bxe_softc *sc)
6711 {
6712     uint32_t val;
6713     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6714     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6715     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6716     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6717 }
6718
6719 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6720 static void
6721 bxe_clear_reset_global(struct bxe_softc *sc)
6722 {
6723     uint32_t val;
6724     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6725     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6726     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6727     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6728 }
6729
6730 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6731 static uint8_t
6732 bxe_reset_is_global(struct bxe_softc *sc)
6733 {
6734     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6735     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6736     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6737 }
6738
6739 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6740 static void
6741 bxe_set_reset_done(struct bxe_softc *sc)
6742 {
6743     uint32_t val;
6744     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6745                                  BXE_PATH0_RST_IN_PROG_BIT;
6746
6747     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6748
6749     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6750     /* Clear the bit */
6751     val &= ~bit;
6752     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6753
6754     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6755 }
6756
6757 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6758 static void
6759 bxe_set_reset_in_progress(struct bxe_softc *sc)
6760 {
6761     uint32_t val;
6762     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6763                                  BXE_PATH0_RST_IN_PROG_BIT;
6764
6765     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6766
6767     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6768     /* Set the bit */
6769     val |= bit;
6770     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6771
6772     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6773 }
6774
6775 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6776 static uint8_t
6777 bxe_reset_is_done(struct bxe_softc *sc,
6778                   int              engine)
6779 {
6780     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6781     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6782                             BXE_PATH0_RST_IN_PROG_BIT;
6783
6784     /* return false if bit is set */
6785     return (val & bit) ? FALSE : TRUE;
6786 }
6787
6788 /* get the load status for an engine, should be run under rtnl lock */
6789 static uint8_t
6790 bxe_get_load_status(struct bxe_softc *sc,
6791                     int              engine)
6792 {
6793     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6794                              BXE_PATH0_LOAD_CNT_MASK;
6795     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6796                               BXE_PATH0_LOAD_CNT_SHIFT;
6797     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6798
6799     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6800
6801     val = ((val & mask) >> shift);
6802
6803     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6804
6805     return (val != 0);
6806 }
6807
6808 /* set pf load mark */
6809 /* XXX needs to be under rtnl lock */
6810 static void
6811 bxe_set_pf_load(struct bxe_softc *sc)
6812 {
6813     uint32_t val;
6814     uint32_t val1;
6815     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6816                                   BXE_PATH0_LOAD_CNT_MASK;
6817     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6818                                    BXE_PATH0_LOAD_CNT_SHIFT;
6819
6820     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6821
6822     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6823     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6824
6825     /* get the current counter value */
6826     val1 = ((val & mask) >> shift);
6827
6828     /* set bit of this PF */
6829     val1 |= (1 << SC_ABS_FUNC(sc));
6830
6831     /* clear the old value */
6832     val &= ~mask;
6833
6834     /* set the new one */
6835     val |= ((val1 << shift) & mask);
6836
6837     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6838
6839     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6840 }
6841
6842 /* clear pf load mark */
6843 /* XXX needs to be under rtnl lock */
6844 static uint8_t
6845 bxe_clear_pf_load(struct bxe_softc *sc)
6846 {
6847     uint32_t val1, val;
6848     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6849                                   BXE_PATH0_LOAD_CNT_MASK;
6850     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6851                                    BXE_PATH0_LOAD_CNT_SHIFT;
6852
6853     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6854     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6855     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6856
6857     /* get the current counter value */
6858     val1 = (val & mask) >> shift;
6859
6860     /* clear bit of that PF */
6861     val1 &= ~(1 << SC_ABS_FUNC(sc));
6862
6863     /* clear the old value */
6864     val &= ~mask;
6865
6866     /* set the new one */
6867     val |= ((val1 << shift) & mask);
6868
6869     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6870     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6871     return (val1 != 0);
6872 }
6873
6874 /* send load requrest to mcp and analyze response */
6875 static int
6876 bxe_nic_load_request(struct bxe_softc *sc,
6877                      uint32_t         *load_code)
6878 {
6879     /* init fw_seq */
6880     sc->fw_seq =
6881         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6882          DRV_MSG_SEQ_NUMBER_MASK);
6883
6884     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6885
6886     /* get the current FW pulse sequence */
6887     sc->fw_drv_pulse_wr_seq =
6888         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6889          DRV_PULSE_SEQ_MASK);
6890
6891     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6892           sc->fw_drv_pulse_wr_seq);
6893
6894     /* load request */
6895     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6896                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6897
6898     /* if the MCP fails to respond we must abort */
6899     if (!(*load_code)) {
6900         BLOGE(sc, "MCP response failure!\n");
6901         return (-1);
6902     }
6903
6904     /* if MCP refused then must abort */
6905     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6906         BLOGE(sc, "MCP refused load request\n");
6907         return (-1);
6908     }
6909
6910     return (0);
6911 }
6912
6913 /*
6914  * Check whether another PF has already loaded FW to chip. In virtualized
6915  * environments a pf from anoth VM may have already initialized the device
6916  * including loading FW.
6917  */
6918 static int
6919 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6920                          uint32_t         load_code)
6921 {
6922     uint32_t my_fw, loaded_fw;
6923
6924     /* is another pf loaded on this engine? */
6925     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6926         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6927         /* build my FW version dword */
6928         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6929                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6930                  (BCM_5710_FW_REVISION_VERSION << 16) +
6931                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6932
6933         /* read loaded FW from chip */
6934         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6935         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6936               loaded_fw, my_fw);
6937
6938         /* abort nic load if version mismatch */
6939         if (my_fw != loaded_fw) {
6940             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6941                   loaded_fw, my_fw);
6942             return (-1);
6943         }
6944     }
6945
6946     return (0);
6947 }
6948
6949 /* mark PMF if applicable */
6950 static void
6951 bxe_nic_load_pmf(struct bxe_softc *sc,
6952                  uint32_t         load_code)
6953 {
6954     uint32_t ncsi_oem_data_addr;
6955
6956     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6957         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6958         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6959         /*
6960          * Barrier here for ordering between the writing to sc->port.pmf here
6961          * and reading it from the periodic task.
6962          */
6963         sc->port.pmf = 1;
6964         mb();
6965     } else {
6966         sc->port.pmf = 0;
6967     }
6968
6969     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6970
6971     /* XXX needed? */
6972     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6973         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6974             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6975             if (ncsi_oem_data_addr) {
6976                 REG_WR(sc,
6977                        (ncsi_oem_data_addr +
6978                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6979                        0);
6980             }
6981         }
6982     }
6983 }
6984
6985 static void
6986 bxe_read_mf_cfg(struct bxe_softc *sc)
6987 {
6988     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6989     int abs_func;
6990     int vn;
6991
6992     if (BXE_NOMCP(sc)) {
6993         return; /* what should be the default bvalue in this case */
6994     }
6995
6996     /*
6997      * The formula for computing the absolute function number is...
6998      * For 2 port configuration (4 functions per port):
6999      *   abs_func = 2 * vn + SC_PORT + SC_PATH
7000      * For 4 port configuration (2 functions per port):
7001      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
7002      */
7003     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
7004         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
7005         if (abs_func >= E1H_FUNC_MAX) {
7006             break;
7007         }
7008         sc->devinfo.mf_info.mf_config[vn] =
7009             MFCFG_RD(sc, func_mf_config[abs_func].config);
7010     }
7011
7012     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
7013         FUNC_MF_CFG_FUNC_DISABLED) {
7014         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
7015         sc->flags |= BXE_MF_FUNC_DIS;
7016     } else {
7017         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
7018         sc->flags &= ~BXE_MF_FUNC_DIS;
7019     }
7020 }
7021
7022 /* acquire split MCP access lock register */
7023 static int bxe_acquire_alr(struct bxe_softc *sc)
7024 {
7025     uint32_t j, val;
7026
7027     for (j = 0; j < 1000; j++) {
7028         val = (1UL << 31);
7029         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
7030         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
7031         if (val & (1L << 31))
7032             break;
7033
7034         DELAY(5000);
7035     }
7036
7037     if (!(val & (1L << 31))) {
7038         BLOGE(sc, "Cannot acquire MCP access lock register\n");
7039         return (-1);
7040     }
7041
7042     return (0);
7043 }
7044
7045 /* release split MCP access lock register */
7046 static void bxe_release_alr(struct bxe_softc *sc)
7047 {
7048     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
7049 }
7050
7051 static void
7052 bxe_fan_failure(struct bxe_softc *sc)
7053 {
7054     int port = SC_PORT(sc);
7055     uint32_t ext_phy_config;
7056
7057     /* mark the failure */
7058     ext_phy_config =
7059         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
7060
7061     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
7062     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
7063     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
7064              ext_phy_config);
7065
7066     /* log the failure */
7067     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
7068               "the card to prevent permanent damage. "
7069               "Please contact OEM Support for assistance\n");
7070
7071     /* XXX */
7072 #if 1
7073     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
7074 #else
7075     /*
7076      * Schedule device reset (unload)
7077      * This is due to some boards consuming sufficient power when driver is
7078      * up to overheat if fan fails.
7079      */
7080     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
7081     schedule_delayed_work(&sc->sp_rtnl_task, 0);
7082 #endif
7083 }
7084
7085 /* this function is called upon a link interrupt */
7086 static void
7087 bxe_link_attn(struct bxe_softc *sc)
7088 {
7089     uint32_t pause_enabled = 0;
7090     struct host_port_stats *pstats;
7091     int cmng_fns;
7092
7093     /* Make sure that we are synced with the current statistics */
7094     bxe_stats_handle(sc, STATS_EVENT_STOP);
7095
7096     elink_link_update(&sc->link_params, &sc->link_vars);
7097
7098     if (sc->link_vars.link_up) {
7099
7100         /* dropless flow control */
7101         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7102             pause_enabled = 0;
7103
7104             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7105                 pause_enabled = 1;
7106             }
7107
7108             REG_WR(sc,
7109                    (BAR_USTRORM_INTMEM +
7110                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7111                    pause_enabled);
7112         }
7113
7114         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7115             pstats = BXE_SP(sc, port_stats);
7116             /* reset old mac stats */
7117             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7118         }
7119
7120         if (sc->state == BXE_STATE_OPEN) {
7121             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7122         }
7123     }
7124
7125     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7126         cmng_fns = bxe_get_cmng_fns_mode(sc);
7127
7128         if (cmng_fns != CMNG_FNS_NONE) {
7129             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7130             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7131         } else {
7132             /* rate shaping and fairness are disabled */
7133             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7134         }
7135     }
7136
7137     bxe_link_report_locked(sc);
7138
7139     if (IS_MF(sc)) {
7140         ; // XXX bxe_link_sync_notify(sc);
7141     }
7142 }
7143
7144 static void
7145 bxe_attn_int_asserted(struct bxe_softc *sc,
7146                       uint32_t         asserted)
7147 {
7148     int port = SC_PORT(sc);
7149     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7150                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7151     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7152                                         NIG_REG_MASK_INTERRUPT_PORT0;
7153     uint32_t aeu_mask;
7154     uint32_t nig_mask = 0;
7155     uint32_t reg_addr;
7156     uint32_t igu_acked;
7157     uint32_t cnt;
7158
7159     if (sc->attn_state & asserted) {
7160         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7161     }
7162
7163     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7164
7165     aeu_mask = REG_RD(sc, aeu_addr);
7166
7167     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7168           aeu_mask, asserted);
7169
7170     aeu_mask &= ~(asserted & 0x3ff);
7171
7172     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7173
7174     REG_WR(sc, aeu_addr, aeu_mask);
7175
7176     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7177
7178     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7179     sc->attn_state |= asserted;
7180     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7181
7182     if (asserted & ATTN_HARD_WIRED_MASK) {
7183         if (asserted & ATTN_NIG_FOR_FUNC) {
7184
7185             bxe_acquire_phy_lock(sc);
7186             /* save nig interrupt mask */
7187             nig_mask = REG_RD(sc, nig_int_mask_addr);
7188
7189             /* If nig_mask is not set, no need to call the update function */
7190             if (nig_mask) {
7191                 REG_WR(sc, nig_int_mask_addr, 0);
7192
7193                 bxe_link_attn(sc);
7194             }
7195
7196             /* handle unicore attn? */
7197         }
7198
7199         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7200             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7201         }
7202
7203         if (asserted & GPIO_2_FUNC) {
7204             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7205         }
7206
7207         if (asserted & GPIO_3_FUNC) {
7208             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7209         }
7210
7211         if (asserted & GPIO_4_FUNC) {
7212             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7213         }
7214
7215         if (port == 0) {
7216             if (asserted & ATTN_GENERAL_ATTN_1) {
7217                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7218                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7219             }
7220             if (asserted & ATTN_GENERAL_ATTN_2) {
7221                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7222                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7223             }
7224             if (asserted & ATTN_GENERAL_ATTN_3) {
7225                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7226                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7227             }
7228         } else {
7229             if (asserted & ATTN_GENERAL_ATTN_4) {
7230                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7231                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7232             }
7233             if (asserted & ATTN_GENERAL_ATTN_5) {
7234                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7235                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7236             }
7237             if (asserted & ATTN_GENERAL_ATTN_6) {
7238                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7239                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7240             }
7241         }
7242     } /* hardwired */
7243
7244     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7245         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7246     } else {
7247         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7248     }
7249
7250     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7251           asserted,
7252           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7253     REG_WR(sc, reg_addr, asserted);
7254
7255     /* now set back the mask */
7256     if (asserted & ATTN_NIG_FOR_FUNC) {
7257         /*
7258          * Verify that IGU ack through BAR was written before restoring
7259          * NIG mask. This loop should exit after 2-3 iterations max.
7260          */
7261         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7262             cnt = 0;
7263
7264             do {
7265                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7266             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7267                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7268
7269             if (!igu_acked) {
7270                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7271             }
7272
7273             mb();
7274         }
7275
7276         REG_WR(sc, nig_int_mask_addr, nig_mask);
7277
7278         bxe_release_phy_lock(sc);
7279     }
7280 }
7281
7282 static void
7283 bxe_print_next_block(struct bxe_softc *sc,
7284                      int              idx,
7285                      const char       *blk)
7286 {
7287     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7288 }
7289
7290 static int
7291 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7292                               uint32_t         sig,
7293                               int              par_num,
7294                               uint8_t          print)
7295 {
7296     uint32_t cur_bit = 0;
7297     int i = 0;
7298
7299     for (i = 0; sig; i++) {
7300         cur_bit = ((uint32_t)0x1 << i);
7301         if (sig & cur_bit) {
7302             switch (cur_bit) {
7303             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7304                 if (print)
7305                     bxe_print_next_block(sc, par_num++, "BRB");
7306                 break;
7307             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7308                 if (print)
7309                     bxe_print_next_block(sc, par_num++, "PARSER");
7310                 break;
7311             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7312                 if (print)
7313                     bxe_print_next_block(sc, par_num++, "TSDM");
7314                 break;
7315             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7316                 if (print)
7317                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7318                 break;
7319             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7320                 if (print)
7321                     bxe_print_next_block(sc, par_num++, "TCM");
7322                 break;
7323             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7324                 if (print)
7325                     bxe_print_next_block(sc, par_num++, "TSEMI");
7326                 break;
7327             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7328                 if (print)
7329                     bxe_print_next_block(sc, par_num++, "XPB");
7330                 break;
7331             }
7332
7333             /* Clear the bit */
7334             sig &= ~cur_bit;
7335         }
7336     }
7337
7338     return (par_num);
7339 }
7340
7341 static int
7342 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7343                               uint32_t         sig,
7344                               int              par_num,
7345                               uint8_t          *global,
7346                               uint8_t          print)
7347 {
7348     int i = 0;
7349     uint32_t cur_bit = 0;
7350     for (i = 0; sig; i++) {
7351         cur_bit = ((uint32_t)0x1 << i);
7352         if (sig & cur_bit) {
7353             switch (cur_bit) {
7354             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7355                 if (print)
7356                     bxe_print_next_block(sc, par_num++, "PBF");
7357                 break;
7358             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7359                 if (print)
7360                     bxe_print_next_block(sc, par_num++, "QM");
7361                 break;
7362             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7363                 if (print)
7364                     bxe_print_next_block(sc, par_num++, "TM");
7365                 break;
7366             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7367                 if (print)
7368                     bxe_print_next_block(sc, par_num++, "XSDM");
7369                 break;
7370             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7371                 if (print)
7372                     bxe_print_next_block(sc, par_num++, "XCM");
7373                 break;
7374             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7375                 if (print)
7376                     bxe_print_next_block(sc, par_num++, "XSEMI");
7377                 break;
7378             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7379                 if (print)
7380                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7381                 break;
7382             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7383                 if (print)
7384                     bxe_print_next_block(sc, par_num++, "NIG");
7385                 break;
7386             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7387                 if (print)
7388                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7389                 *global = TRUE;
7390                 break;
7391             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7392                 if (print)
7393                     bxe_print_next_block(sc, par_num++, "DEBUG");
7394                 break;
7395             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7396                 if (print)
7397                     bxe_print_next_block(sc, par_num++, "USDM");
7398                 break;
7399             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7400                 if (print)
7401                     bxe_print_next_block(sc, par_num++, "UCM");
7402                 break;
7403             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7404                 if (print)
7405                     bxe_print_next_block(sc, par_num++, "USEMI");
7406                 break;
7407             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7408                 if (print)
7409                     bxe_print_next_block(sc, par_num++, "UPB");
7410                 break;
7411             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7412                 if (print)
7413                     bxe_print_next_block(sc, par_num++, "CSDM");
7414                 break;
7415             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7416                 if (print)
7417                     bxe_print_next_block(sc, par_num++, "CCM");
7418                 break;
7419             }
7420
7421             /* Clear the bit */
7422             sig &= ~cur_bit;
7423         }
7424     }
7425
7426     return (par_num);
7427 }
7428
7429 static int
7430 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7431                               uint32_t         sig,
7432                               int              par_num,
7433                               uint8_t          print)
7434 {
7435     uint32_t cur_bit = 0;
7436     int i = 0;
7437
7438     for (i = 0; sig; i++) {
7439         cur_bit = ((uint32_t)0x1 << i);
7440         if (sig & cur_bit) {
7441             switch (cur_bit) {
7442             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7443                 if (print)
7444                     bxe_print_next_block(sc, par_num++, "CSEMI");
7445                 break;
7446             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7447                 if (print)
7448                     bxe_print_next_block(sc, par_num++, "PXP");
7449                 break;
7450             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7451                 if (print)
7452                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7453                 break;
7454             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7455                 if (print)
7456                     bxe_print_next_block(sc, par_num++, "CFC");
7457                 break;
7458             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7459                 if (print)
7460                     bxe_print_next_block(sc, par_num++, "CDU");
7461                 break;
7462             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7463                 if (print)
7464                     bxe_print_next_block(sc, par_num++, "DMAE");
7465                 break;
7466             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7467                 if (print)
7468                     bxe_print_next_block(sc, par_num++, "IGU");
7469                 break;
7470             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7471                 if (print)
7472                     bxe_print_next_block(sc, par_num++, "MISC");
7473                 break;
7474             }
7475
7476             /* Clear the bit */
7477             sig &= ~cur_bit;
7478         }
7479     }
7480
7481     return (par_num);
7482 }
7483
7484 static int
7485 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7486                               uint32_t         sig,
7487                               int              par_num,
7488                               uint8_t          *global,
7489                               uint8_t          print)
7490 {
7491     uint32_t cur_bit = 0;
7492     int i = 0;
7493
7494     for (i = 0; sig; i++) {
7495         cur_bit = ((uint32_t)0x1 << i);
7496         if (sig & cur_bit) {
7497             switch (cur_bit) {
7498             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7499                 if (print)
7500                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7501                 *global = TRUE;
7502                 break;
7503             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7504                 if (print)
7505                     bxe_print_next_block(sc, par_num++,
7506                               "MCP UMP RX");
7507                 *global = TRUE;
7508                 break;
7509             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7510                 if (print)
7511                     bxe_print_next_block(sc, par_num++,
7512                               "MCP UMP TX");
7513                 *global = TRUE;
7514                 break;
7515             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7516                 if (print)
7517                     bxe_print_next_block(sc, par_num++,
7518                               "MCP SCPAD");
7519                 *global = TRUE;
7520                 break;
7521             }
7522
7523             /* Clear the bit */
7524             sig &= ~cur_bit;
7525         }
7526     }
7527
7528     return (par_num);
7529 }
7530
7531 static int
7532 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7533                               uint32_t         sig,
7534                               int              par_num,
7535                               uint8_t          print)
7536 {
7537     uint32_t cur_bit = 0;
7538     int i = 0;
7539
7540     for (i = 0; sig; i++) {
7541         cur_bit = ((uint32_t)0x1 << i);
7542         if (sig & cur_bit) {
7543             switch (cur_bit) {
7544             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7545                 if (print)
7546                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7547                 break;
7548             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7549                 if (print)
7550                     bxe_print_next_block(sc, par_num++, "ATC");
7551                 break;
7552             }
7553
7554             /* Clear the bit */
7555             sig &= ~cur_bit;
7556         }
7557     }
7558
7559     return (par_num);
7560 }
7561
7562 static uint8_t
7563 bxe_parity_attn(struct bxe_softc *sc,
7564                 uint8_t          *global,
7565                 uint8_t          print,
7566                 uint32_t         *sig)
7567 {
7568     int par_num = 0;
7569
7570     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7571         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7572         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7573         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7574         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7575         BLOGE(sc, "Parity error: HW block parity attention:\n"
7576                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7577               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7578               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7579               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7580               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7581               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7582
7583         if (print)
7584             BLOGI(sc, "Parity errors detected in blocks: ");
7585
7586         par_num =
7587             bxe_check_blocks_with_parity0(sc, sig[0] &
7588                                           HW_PRTY_ASSERT_SET_0,
7589                                           par_num, print);
7590         par_num =
7591             bxe_check_blocks_with_parity1(sc, sig[1] &
7592                                           HW_PRTY_ASSERT_SET_1,
7593                                           par_num, global, print);
7594         par_num =
7595             bxe_check_blocks_with_parity2(sc, sig[2] &
7596                                           HW_PRTY_ASSERT_SET_2,
7597                                           par_num, print);
7598         par_num =
7599             bxe_check_blocks_with_parity3(sc, sig[3] &
7600                                           HW_PRTY_ASSERT_SET_3,
7601                                           par_num, global, print);
7602         par_num =
7603             bxe_check_blocks_with_parity4(sc, sig[4] &
7604                                           HW_PRTY_ASSERT_SET_4,
7605                                           par_num, print);
7606
7607         if (print)
7608             BLOGI(sc, "\n");
7609
7610         return (TRUE);
7611     }
7612
7613     return (FALSE);
7614 }
7615
7616 static uint8_t
7617 bxe_chk_parity_attn(struct bxe_softc *sc,
7618                     uint8_t          *global,
7619                     uint8_t          print)
7620 {
7621     struct attn_route attn = { {0} };
7622     int port = SC_PORT(sc);
7623
7624     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7625     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7626     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7627     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7628
7629     /*
7630      * Since MCP attentions can't be disabled inside the block, we need to
7631      * read AEU registers to see whether they're currently disabled
7632      */
7633     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7634                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7635                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7636                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7637
7638
7639     if (!CHIP_IS_E1x(sc))
7640         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7641
7642     return (bxe_parity_attn(sc, global, print, attn.sig));
7643 }
7644
7645 static void
7646 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7647                          uint32_t         attn)
7648 {
7649     uint32_t val;
7650
7651     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7652         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7653         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7654         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7655             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7656         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7657             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7658         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7659             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7660         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7661             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7662         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7663             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7664         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7665             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7666         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7667             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7668         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7669             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7670         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7671             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7672     }
7673
7674     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7675         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7676         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7677         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7678             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7679         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7680             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7681         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7682             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7683         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7684             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7685         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7686             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7687         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7688             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7689     }
7690
7691     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7692                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7693         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7694               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7695                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7696     }
7697 }
7698
7699 static void
7700 bxe_e1h_disable(struct bxe_softc *sc)
7701 {
7702     int port = SC_PORT(sc);
7703
7704     bxe_tx_disable(sc);
7705
7706     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7707 }
7708
7709 static void
7710 bxe_e1h_enable(struct bxe_softc *sc)
7711 {
7712     int port = SC_PORT(sc);
7713
7714     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7715
7716     // XXX bxe_tx_enable(sc);
7717 }
7718
7719 /*
7720  * called due to MCP event (on pmf):
7721  *   reread new bandwidth configuration
7722  *   configure FW
7723  *   notify others function about the change
7724  */
7725 static void
7726 bxe_config_mf_bw(struct bxe_softc *sc)
7727 {
7728     if (sc->link_vars.link_up) {
7729         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7730         // XXX bxe_link_sync_notify(sc);
7731     }
7732
7733     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7734 }
7735
7736 static void
7737 bxe_set_mf_bw(struct bxe_softc *sc)
7738 {
7739     bxe_config_mf_bw(sc);
7740     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7741 }
7742
7743 static void
7744 bxe_handle_eee_event(struct bxe_softc *sc)
7745 {
7746     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7747     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7748 }
7749
7750 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7751
7752 static void
7753 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7754 {
7755     struct eth_stats_info *ether_stat =
7756         &sc->sp->drv_info_to_mcp.ether_stat;
7757
7758     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7759             ETH_STAT_INFO_VERSION_LEN);
7760
7761     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7762     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7763                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7764                                           ether_stat->mac_local + MAC_PAD,
7765                                           MAC_PAD, ETH_ALEN);
7766
7767     ether_stat->mtu_size = sc->mtu;
7768
7769     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7770     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7771         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7772     }
7773
7774     // XXX ether_stat->feature_flags |= ???;
7775
7776     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7777
7778     ether_stat->txq_size = sc->tx_ring_size;
7779     ether_stat->rxq_size = sc->rx_ring_size;
7780 }
7781
7782 static void
7783 bxe_handle_drv_info_req(struct bxe_softc *sc)
7784 {
7785     enum drv_info_opcode op_code;
7786     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7787
7788     /* if drv_info version supported by MFW doesn't match - send NACK */
7789     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7790         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7791         return;
7792     }
7793
7794     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7795                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7796
7797     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7798
7799     switch (op_code) {
7800     case ETH_STATS_OPCODE:
7801         bxe_drv_info_ether_stat(sc);
7802         break;
7803     case FCOE_STATS_OPCODE:
7804     case ISCSI_STATS_OPCODE:
7805     default:
7806         /* if op code isn't supported - send NACK */
7807         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7808         return;
7809     }
7810
7811     /*
7812      * If we got drv_info attn from MFW then these fields are defined in
7813      * shmem2 for sure
7814      */
7815     SHMEM2_WR(sc, drv_info_host_addr_lo,
7816               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7817     SHMEM2_WR(sc, drv_info_host_addr_hi,
7818               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7819
7820     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7821 }
7822
7823 static void
7824 bxe_dcc_event(struct bxe_softc *sc,
7825               uint32_t         dcc_event)
7826 {
7827     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7828
7829     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7830         /*
7831          * This is the only place besides the function initialization
7832          * where the sc->flags can change so it is done without any
7833          * locks
7834          */
7835         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7836             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7837             sc->flags |= BXE_MF_FUNC_DIS;
7838             bxe_e1h_disable(sc);
7839         } else {
7840             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7841             sc->flags &= ~BXE_MF_FUNC_DIS;
7842             bxe_e1h_enable(sc);
7843         }
7844         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7845     }
7846
7847     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7848         bxe_config_mf_bw(sc);
7849         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7850     }
7851
7852     /* Report results to MCP */
7853     if (dcc_event)
7854         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7855     else
7856         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7857 }
7858
7859 static void
7860 bxe_pmf_update(struct bxe_softc *sc)
7861 {
7862     int port = SC_PORT(sc);
7863     uint32_t val;
7864
7865     sc->port.pmf = 1;
7866     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7867
7868     /*
7869      * We need the mb() to ensure the ordering between the writing to
7870      * sc->port.pmf here and reading it from the bxe_periodic_task().
7871      */
7872     mb();
7873
7874     /* queue a periodic task */
7875     // XXX schedule task...
7876
7877     // XXX bxe_dcbx_pmf_update(sc);
7878
7879     /* enable nig attention */
7880     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7881     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7882         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7883         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7884     } else if (!CHIP_IS_E1x(sc)) {
7885         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7886         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7887     }
7888
7889     bxe_stats_handle(sc, STATS_EVENT_PMF);
7890 }
7891
7892 static int
7893 bxe_mc_assert(struct bxe_softc *sc)
7894 {
7895     char last_idx;
7896     int i, rc = 0;
7897     uint32_t row0, row1, row2, row3;
7898
7899     /* XSTORM */
7900     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7901     if (last_idx)
7902         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7903
7904     /* print the asserts */
7905     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7906
7907         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7908         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7909         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7910         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7911
7912         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7913             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7914                   i, row3, row2, row1, row0);
7915             rc++;
7916         } else {
7917             break;
7918         }
7919     }
7920
7921     /* TSTORM */
7922     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7923     if (last_idx) {
7924         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7925     }
7926
7927     /* print the asserts */
7928     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7929
7930         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7931         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7932         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7933         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7934
7935         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7936             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7937                   i, row3, row2, row1, row0);
7938             rc++;
7939         } else {
7940             break;
7941         }
7942     }
7943
7944     /* CSTORM */
7945     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7946     if (last_idx) {
7947         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7948     }
7949
7950     /* print the asserts */
7951     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7952
7953         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7954         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7955         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7956         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7957
7958         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7959             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7960                   i, row3, row2, row1, row0);
7961             rc++;
7962         } else {
7963             break;
7964         }
7965     }
7966
7967     /* USTORM */
7968     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7969     if (last_idx) {
7970         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7971     }
7972
7973     /* print the asserts */
7974     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7975
7976         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7977         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7978         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7979         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7980
7981         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7982             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7983                   i, row3, row2, row1, row0);
7984             rc++;
7985         } else {
7986             break;
7987         }
7988     }
7989
7990     return (rc);
7991 }
7992
7993 static void
7994 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7995                          uint32_t         attn)
7996 {
7997     int func = SC_FUNC(sc);
7998     uint32_t val;
7999
8000     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
8001
8002         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
8003
8004             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
8005             bxe_read_mf_cfg(sc);
8006             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
8007                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
8008             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
8009
8010             if (val & DRV_STATUS_DCC_EVENT_MASK)
8011                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
8012
8013             if (val & DRV_STATUS_SET_MF_BW)
8014                 bxe_set_mf_bw(sc);
8015
8016             if (val & DRV_STATUS_DRV_INFO_REQ)
8017                 bxe_handle_drv_info_req(sc);
8018
8019             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
8020                 bxe_pmf_update(sc);
8021
8022             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
8023                 bxe_handle_eee_event(sc);
8024
8025             if (sc->link_vars.periodic_flags &
8026                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
8027                 /* sync with link */
8028                 bxe_acquire_phy_lock(sc);
8029                 sc->link_vars.periodic_flags &=
8030                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
8031                 bxe_release_phy_lock(sc);
8032                 if (IS_MF(sc))
8033                     ; // XXX bxe_link_sync_notify(sc);
8034                 bxe_link_report(sc);
8035             }
8036
8037             /*
8038              * Always call it here: bxe_link_report() will
8039              * prevent the link indication duplication.
8040              */
8041             bxe_link_status_update(sc);
8042
8043         } else if (attn & BXE_MC_ASSERT_BITS) {
8044
8045             BLOGE(sc, "MC assert!\n");
8046             bxe_mc_assert(sc);
8047             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
8048             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
8049             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
8050             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
8051             bxe_panic(sc, ("MC assert!\n"));
8052
8053         } else if (attn & BXE_MCP_ASSERT) {
8054
8055             BLOGE(sc, "MCP assert!\n");
8056             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
8057             // XXX bxe_fw_dump(sc);
8058
8059         } else {
8060             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
8061         }
8062     }
8063
8064     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
8065         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
8066         if (attn & BXE_GRC_TIMEOUT) {
8067             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
8068             BLOGE(sc, "GRC time-out 0x%08x\n", val);
8069         }
8070         if (attn & BXE_GRC_RSV) {
8071             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
8072             BLOGE(sc, "GRC reserved 0x%08x\n", val);
8073         }
8074         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
8075     }
8076 }
8077
8078 static void
8079 bxe_attn_int_deasserted2(struct bxe_softc *sc,
8080                          uint32_t         attn)
8081 {
8082     int port = SC_PORT(sc);
8083     int reg_offset;
8084     uint32_t val0, mask0, val1, mask1;
8085     uint32_t val;
8086
8087     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8088         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8089         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8090         /* CFC error attention */
8091         if (val & 0x2) {
8092             BLOGE(sc, "FATAL error from CFC\n");
8093         }
8094     }
8095
8096     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8097         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8098         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8099         /* RQ_USDMDP_FIFO_OVERFLOW */
8100         if (val & 0x18000) {
8101             BLOGE(sc, "FATAL error from PXP\n");
8102         }
8103
8104         if (!CHIP_IS_E1x(sc)) {
8105             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8106             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8107         }
8108     }
8109
8110 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8111 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8112
8113     if (attn & AEU_PXP2_HW_INT_BIT) {
8114         /*  CQ47854 workaround do not panic on
8115          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8116          */
8117         if (!CHIP_IS_E1x(sc)) {
8118             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8119             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8120             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8121             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8122             /*
8123              * If the olny PXP2_EOP_ERROR_BIT is set in
8124              * STS0 and STS1 - clear it
8125              *
8126              * probably we lose additional attentions between
8127              * STS0 and STS_CLR0, in this case user will not
8128              * be notified about them
8129              */
8130             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8131                 !(val1 & mask1))
8132                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8133
8134             /* print the register, since no one can restore it */
8135             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8136
8137             /*
8138              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8139              * then notify
8140              */
8141             if (val0 & PXP2_EOP_ERROR_BIT) {
8142                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8143
8144                 /*
8145                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8146                  * set then clear attention from PXP2 block without panic
8147                  */
8148                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8149                     ((val1 & mask1) == 0))
8150                     attn &= ~AEU_PXP2_HW_INT_BIT;
8151             }
8152         }
8153     }
8154
8155     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8156         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8157                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8158
8159         val = REG_RD(sc, reg_offset);
8160         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8161         REG_WR(sc, reg_offset, val);
8162
8163         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8164               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8165         bxe_panic(sc, ("HW block attention set2\n"));
8166     }
8167 }
8168
8169 static void
8170 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8171                          uint32_t         attn)
8172 {
8173     int port = SC_PORT(sc);
8174     int reg_offset;
8175     uint32_t val;
8176
8177     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8178         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8179         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8180         /* DORQ discard attention */
8181         if (val & 0x2) {
8182             BLOGE(sc, "FATAL error from DORQ\n");
8183         }
8184     }
8185
8186     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8187         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8188                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8189
8190         val = REG_RD(sc, reg_offset);
8191         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8192         REG_WR(sc, reg_offset, val);
8193
8194         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8195               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8196         bxe_panic(sc, ("HW block attention set1\n"));
8197     }
8198 }
8199
8200 static void
8201 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8202                          uint32_t         attn)
8203 {
8204     int port = SC_PORT(sc);
8205     int reg_offset;
8206     uint32_t val;
8207
8208     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8209                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8210
8211     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8212         val = REG_RD(sc, reg_offset);
8213         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8214         REG_WR(sc, reg_offset, val);
8215
8216         BLOGW(sc, "SPIO5 hw attention\n");
8217
8218         /* Fan failure attention */
8219         elink_hw_reset_phy(&sc->link_params);
8220         bxe_fan_failure(sc);
8221     }
8222
8223     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8224         bxe_acquire_phy_lock(sc);
8225         elink_handle_module_detect_int(&sc->link_params);
8226         bxe_release_phy_lock(sc);
8227     }
8228
8229     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8230         val = REG_RD(sc, reg_offset);
8231         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8232         REG_WR(sc, reg_offset, val);
8233
8234         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8235                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8236     }
8237 }
8238
8239 static void
8240 bxe_attn_int_deasserted(struct bxe_softc *sc,
8241                         uint32_t         deasserted)
8242 {
8243     struct attn_route attn;
8244     struct attn_route *group_mask;
8245     int port = SC_PORT(sc);
8246     int index;
8247     uint32_t reg_addr;
8248     uint32_t val;
8249     uint32_t aeu_mask;
8250     uint8_t global = FALSE;
8251
8252     /*
8253      * Need to take HW lock because MCP or other port might also
8254      * try to handle this event.
8255      */
8256     bxe_acquire_alr(sc);
8257
8258     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8259         /* XXX
8260          * In case of parity errors don't handle attentions so that
8261          * other function would "see" parity errors.
8262          */
8263         sc->recovery_state = BXE_RECOVERY_INIT;
8264         // XXX schedule a recovery task...
8265         /* disable HW interrupts */
8266         bxe_int_disable(sc);
8267         bxe_release_alr(sc);
8268         return;
8269     }
8270
8271     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8272     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8273     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8274     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8275     if (!CHIP_IS_E1x(sc)) {
8276         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8277     } else {
8278         attn.sig[4] = 0;
8279     }
8280
8281     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8282           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8283
8284     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8285         if (deasserted & (1 << index)) {
8286             group_mask = &sc->attn_group[index];
8287
8288             BLOGD(sc, DBG_INTR,
8289                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8290                   group_mask->sig[0], group_mask->sig[1],
8291                   group_mask->sig[2], group_mask->sig[3],
8292                   group_mask->sig[4]);
8293
8294             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8295             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8296             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8297             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8298             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8299         }
8300     }
8301
8302     bxe_release_alr(sc);
8303
8304     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8305         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8306                     COMMAND_REG_ATTN_BITS_CLR);
8307     } else {
8308         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8309     }
8310
8311     val = ~deasserted;
8312     BLOGD(sc, DBG_INTR,
8313           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8314           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8315     REG_WR(sc, reg_addr, val);
8316
8317     if (~sc->attn_state & deasserted) {
8318         BLOGE(sc, "IGU error\n");
8319     }
8320
8321     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8322                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8323
8324     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8325
8326     aeu_mask = REG_RD(sc, reg_addr);
8327
8328     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8329           aeu_mask, deasserted);
8330     aeu_mask |= (deasserted & 0x3ff);
8331     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8332
8333     REG_WR(sc, reg_addr, aeu_mask);
8334     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8335
8336     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8337     sc->attn_state &= ~deasserted;
8338     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8339 }
8340
8341 static void
8342 bxe_attn_int(struct bxe_softc *sc)
8343 {
8344     /* read local copy of bits */
8345     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8346     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8347     uint32_t attn_state = sc->attn_state;
8348
8349     /* look for changed bits */
8350     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8351     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8352
8353     BLOGD(sc, DBG_INTR,
8354           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8355           attn_bits, attn_ack, asserted, deasserted);
8356
8357     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8358         BLOGE(sc, "BAD attention state\n");
8359     }
8360
8361     /* handle bits that were raised */
8362     if (asserted) {
8363         bxe_attn_int_asserted(sc, asserted);
8364     }
8365
8366     if (deasserted) {
8367         bxe_attn_int_deasserted(sc, deasserted);
8368     }
8369 }
8370
8371 static uint16_t
8372 bxe_update_dsb_idx(struct bxe_softc *sc)
8373 {
8374     struct host_sp_status_block *def_sb = sc->def_sb;
8375     uint16_t rc = 0;
8376
8377     mb(); /* status block is written to by the chip */
8378
8379     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8380         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8381         rc |= BXE_DEF_SB_ATT_IDX;
8382     }
8383
8384     if (sc->def_idx != def_sb->sp_sb.running_index) {
8385         sc->def_idx = def_sb->sp_sb.running_index;
8386         rc |= BXE_DEF_SB_IDX;
8387     }
8388
8389     mb();
8390
8391     return (rc);
8392 }
8393
8394 static inline struct ecore_queue_sp_obj *
8395 bxe_cid_to_q_obj(struct bxe_softc *sc,
8396                  uint32_t         cid)
8397 {
8398     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8399     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8400 }
8401
8402 static void
8403 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8404 {
8405     struct ecore_mcast_ramrod_params rparam;
8406     int rc;
8407
8408     memset(&rparam, 0, sizeof(rparam));
8409
8410     rparam.mcast_obj = &sc->mcast_obj;
8411
8412     BXE_MCAST_LOCK(sc);
8413
8414     /* clear pending state for the last command */
8415     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8416
8417     /* if there are pending mcast commands - send them */
8418     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8419         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8420         if (rc < 0) {
8421             BLOGD(sc, DBG_SP,
8422                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8423         }
8424     }
8425
8426     BXE_MCAST_UNLOCK(sc);
8427 }
8428
8429 static void
8430 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8431                               union event_ring_elem *elem)
8432 {
8433     unsigned long ramrod_flags = 0;
8434     int rc = 0;
8435     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8436     struct ecore_vlan_mac_obj *vlan_mac_obj;
8437
8438     /* always push next commands out, don't wait here */
8439     bit_set(&ramrod_flags, RAMROD_CONT);
8440
8441     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8442     case ECORE_FILTER_MAC_PENDING:
8443         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8444         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8445         break;
8446
8447     case ECORE_FILTER_MCAST_PENDING:
8448         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8449         /*
8450          * This is only relevant for 57710 where multicast MACs are
8451          * configured as unicast MACs using the same ramrod.
8452          */
8453         bxe_handle_mcast_eqe(sc);
8454         return;
8455
8456     default:
8457         BLOGE(sc, "Unsupported classification command: %d\n",
8458               elem->message.data.eth_event.echo);
8459         return;
8460     }
8461
8462     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8463
8464     if (rc < 0) {
8465         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8466     } else if (rc > 0) {
8467         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8468     }
8469 }
8470
8471 static void
8472 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8473                        union event_ring_elem *elem)
8474 {
8475     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8476
8477     /* send rx_mode command again if was requested */
8478     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8479                                &sc->sp_state)) {
8480         bxe_set_storm_rx_mode(sc);
8481     }
8482 }
8483
8484 static void
8485 bxe_update_eq_prod(struct bxe_softc *sc,
8486                    uint16_t         prod)
8487 {
8488     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8489     wmb(); /* keep prod updates ordered */
8490 }
8491
8492 static void
8493 bxe_eq_int(struct bxe_softc *sc)
8494 {
8495     uint16_t hw_cons, sw_cons, sw_prod;
8496     union event_ring_elem *elem;
8497     uint8_t echo;
8498     uint32_t cid;
8499     uint8_t opcode;
8500     int spqe_cnt = 0;
8501     struct ecore_queue_sp_obj *q_obj;
8502     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8503     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8504
8505     hw_cons = le16toh(*sc->eq_cons_sb);
8506
8507     /*
8508      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8509      * when we get to the next-page we need to adjust so the loop
8510      * condition below will be met. The next element is the size of a
8511      * regular element and hence incrementing by 1
8512      */
8513     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8514         hw_cons++;
8515     }
8516
8517     /*
8518      * This function may never run in parallel with itself for a
8519      * specific sc and no need for a read memory barrier here.
8520      */
8521     sw_cons = sc->eq_cons;
8522     sw_prod = sc->eq_prod;
8523
8524     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8525           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8526
8527     for (;
8528          sw_cons != hw_cons;
8529          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8530
8531         elem = &sc->eq[EQ_DESC(sw_cons)];
8532
8533         /* elem CID originates from FW, actually LE */
8534         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8535         opcode = elem->message.opcode;
8536
8537         /* handle eq element */
8538         switch (opcode) {
8539
8540         case EVENT_RING_OPCODE_STAT_QUERY:
8541             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8542                   sc->stats_comp++);
8543             /* nothing to do with stats comp */
8544             goto next_spqe;
8545
8546         case EVENT_RING_OPCODE_CFC_DEL:
8547             /* handle according to cid range */
8548             /* we may want to verify here that the sc state is HALTING */
8549             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8550             q_obj = bxe_cid_to_q_obj(sc, cid);
8551             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8552                 break;
8553             }
8554             goto next_spqe;
8555
8556         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8557             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8558             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8559                 break;
8560             }
8561             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8562             goto next_spqe;
8563
8564         case EVENT_RING_OPCODE_START_TRAFFIC:
8565             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8566             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8567                 break;
8568             }
8569             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8570             goto next_spqe;
8571
8572         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8573             echo = elem->message.data.function_update_event.echo;
8574             if (echo == SWITCH_UPDATE) {
8575                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8576                 if (f_obj->complete_cmd(sc, f_obj,
8577                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8578                     break;
8579                 }
8580             }
8581             else {
8582                 BLOGD(sc, DBG_SP,
8583                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8584             }
8585             goto next_spqe;
8586
8587         case EVENT_RING_OPCODE_FORWARD_SETUP:
8588             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8589             if (q_obj->complete_cmd(sc, q_obj,
8590                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8591                 break;
8592             }
8593             goto next_spqe;
8594
8595         case EVENT_RING_OPCODE_FUNCTION_START:
8596             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8597             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8598                 break;
8599             }
8600             goto next_spqe;
8601
8602         case EVENT_RING_OPCODE_FUNCTION_STOP:
8603             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8604             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8605                 break;
8606             }
8607             goto next_spqe;
8608         }
8609
8610         switch (opcode | sc->state) {
8611         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8612         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8613             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8614             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8615             rss_raw->clear_pending(rss_raw);
8616             break;
8617
8618         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8619         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8620         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8621         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8622         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8623         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8624             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8625             bxe_handle_classification_eqe(sc, elem);
8626             break;
8627
8628         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8629         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8630         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8631             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8632             bxe_handle_mcast_eqe(sc);
8633             break;
8634
8635         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8636         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8637         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8638             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8639             bxe_handle_rx_mode_eqe(sc, elem);
8640             break;
8641
8642         default:
8643             /* unknown event log error and continue */
8644             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8645                   elem->message.opcode, sc->state);
8646         }
8647
8648 next_spqe:
8649         spqe_cnt++;
8650     } /* for */
8651
8652     mb();
8653     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8654
8655     sc->eq_cons = sw_cons;
8656     sc->eq_prod = sw_prod;
8657
8658     /* make sure that above mem writes were issued towards the memory */
8659     wmb();
8660
8661     /* update producer */
8662     bxe_update_eq_prod(sc, sc->eq_prod);
8663 }
8664
8665 static void
8666 bxe_handle_sp_tq(void *context,
8667                  int  pending)
8668 {
8669     struct bxe_softc *sc = (struct bxe_softc *)context;
8670     uint16_t status;
8671
8672     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8673
8674     /* what work needs to be performed? */
8675     status = bxe_update_dsb_idx(sc);
8676
8677     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8678
8679     /* HW attentions */
8680     if (status & BXE_DEF_SB_ATT_IDX) {
8681         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8682         bxe_attn_int(sc);
8683         status &= ~BXE_DEF_SB_ATT_IDX;
8684     }
8685
8686     /* SP events: STAT_QUERY and others */
8687     if (status & BXE_DEF_SB_IDX) {
8688         /* handle EQ completions */
8689         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8690         bxe_eq_int(sc);
8691         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8692                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8693         status &= ~BXE_DEF_SB_IDX;
8694     }
8695
8696     /* if status is non zero then something went wrong */
8697     if (__predict_false(status)) {
8698         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8699     }
8700
8701     /* ack status block only if something was actually handled */
8702     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8703                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8704
8705     /*
8706      * Must be called after the EQ processing (since eq leads to sriov
8707      * ramrod completion flows).
8708      * This flow may have been scheduled by the arrival of a ramrod
8709      * completion, or by the sriov code rescheduling itself.
8710      */
8711     // XXX bxe_iov_sp_task(sc);
8712
8713 }
8714
8715 static void
8716 bxe_handle_fp_tq(void *context,
8717                  int  pending)
8718 {
8719     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8720     struct bxe_softc *sc = fp->sc;
8721     uint8_t more_tx = FALSE;
8722     uint8_t more_rx = FALSE;
8723
8724     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8725
8726     /* XXX
8727      * IFF_DRV_RUNNING state can't be checked here since we process
8728      * slowpath events on a client queue during setup. Instead
8729      * we need to add a "process/continue" flag here that the driver
8730      * can use to tell the task here not to do anything.
8731      */
8732 #if 0
8733     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8734         return;
8735     }
8736 #endif
8737
8738     /* update the fastpath index */
8739     bxe_update_fp_sb_idx(fp);
8740
8741     /* XXX add loop here if ever support multiple tx CoS */
8742     /* fp->txdata[cos] */
8743     if (bxe_has_tx_work(fp)) {
8744         BXE_FP_TX_LOCK(fp);
8745         more_tx = bxe_txeof(sc, fp);
8746         BXE_FP_TX_UNLOCK(fp);
8747     }
8748
8749     if (bxe_has_rx_work(fp)) {
8750         more_rx = bxe_rxeof(sc, fp);
8751     }
8752
8753     if (more_rx /*|| more_tx*/) {
8754         /* still more work to do */
8755         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8756         return;
8757     }
8758
8759     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8760                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8761 }
8762
8763 static void
8764 bxe_task_fp(struct bxe_fastpath *fp)
8765 {
8766     struct bxe_softc *sc = fp->sc;
8767     uint8_t more_tx = FALSE;
8768     uint8_t more_rx = FALSE;
8769
8770     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8771
8772     /* update the fastpath index */
8773     bxe_update_fp_sb_idx(fp);
8774
8775     /* XXX add loop here if ever support multiple tx CoS */
8776     /* fp->txdata[cos] */
8777     if (bxe_has_tx_work(fp)) {
8778         BXE_FP_TX_LOCK(fp);
8779         more_tx = bxe_txeof(sc, fp);
8780         BXE_FP_TX_UNLOCK(fp);
8781     }
8782
8783     if (bxe_has_rx_work(fp)) {
8784         more_rx = bxe_rxeof(sc, fp);
8785     }
8786
8787     if (more_rx /*|| more_tx*/) {
8788         /* still more work to do, bail out if this ISR and process later */
8789         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8790         return;
8791     }
8792
8793     /*
8794      * Here we write the fastpath index taken before doing any tx or rx work.
8795      * It is very well possible other hw events occurred up to this point and
8796      * they were actually processed accordingly above. Since we're going to
8797      * write an older fastpath index, an interrupt is coming which we might
8798      * not do any work in.
8799      */
8800     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8801                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8802 }
8803
8804 /*
8805  * Legacy interrupt entry point.
8806  *
8807  * Verifies that the controller generated the interrupt and
8808  * then calls a separate routine to handle the various
8809  * interrupt causes: link, RX, and TX.
8810  */
8811 static void
8812 bxe_intr_legacy(void *xsc)
8813 {
8814     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8815     struct bxe_fastpath *fp;
8816     uint16_t status, mask;
8817     int i;
8818
8819     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8820
8821     /*
8822      * 0 for ustorm, 1 for cstorm
8823      * the bits returned from ack_int() are 0-15
8824      * bit 0 = attention status block
8825      * bit 1 = fast path status block
8826      * a mask of 0x2 or more = tx/rx event
8827      * a mask of 1 = slow path event
8828      */
8829
8830     status = bxe_ack_int(sc);
8831
8832     /* the interrupt is not for us */
8833     if (__predict_false(status == 0)) {
8834         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8835         return;
8836     }
8837
8838     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8839
8840     FOR_EACH_ETH_QUEUE(sc, i) {
8841         fp = &sc->fp[i];
8842         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8843         if (status & mask) {
8844             /* acknowledge and disable further fastpath interrupts */
8845             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8846             bxe_task_fp(fp);
8847             status &= ~mask;
8848         }
8849     }
8850
8851     if (__predict_false(status & 0x1)) {
8852         /* acknowledge and disable further slowpath interrupts */
8853         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8854
8855         /* schedule slowpath handler */
8856         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8857
8858         status &= ~0x1;
8859     }
8860
8861     if (__predict_false(status)) {
8862         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8863     }
8864 }
8865
8866 /* slowpath interrupt entry point */
8867 static void
8868 bxe_intr_sp(void *xsc)
8869 {
8870     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8871
8872     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8873
8874     /* acknowledge and disable further slowpath interrupts */
8875     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8876
8877     /* schedule slowpath handler */
8878     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8879 }
8880
8881 /* fastpath interrupt entry point */
8882 static void
8883 bxe_intr_fp(void *xfp)
8884 {
8885     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8886     struct bxe_softc *sc = fp->sc;
8887
8888     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8889
8890     BLOGD(sc, DBG_INTR,
8891           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8892           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8893
8894     /* acknowledge and disable further fastpath interrupts */
8895     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8896
8897     bxe_task_fp(fp);
8898 }
8899
8900 /* Release all interrupts allocated by the driver. */
8901 static void
8902 bxe_interrupt_free(struct bxe_softc *sc)
8903 {
8904     int i;
8905
8906     switch (sc->interrupt_mode) {
8907     case INTR_MODE_INTX:
8908         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8909         if (sc->intr[0].resource != NULL) {
8910             bus_release_resource(sc->dev,
8911                                  SYS_RES_IRQ,
8912                                  sc->intr[0].rid,
8913                                  sc->intr[0].resource);
8914         }
8915         break;
8916     case INTR_MODE_MSI:
8917         for (i = 0; i < sc->intr_count; i++) {
8918             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8919             if (sc->intr[i].resource && sc->intr[i].rid) {
8920                 bus_release_resource(sc->dev,
8921                                      SYS_RES_IRQ,
8922                                      sc->intr[i].rid,
8923                                      sc->intr[i].resource);
8924             }
8925         }
8926         pci_release_msi(sc->dev);
8927         break;
8928     case INTR_MODE_MSIX:
8929         for (i = 0; i < sc->intr_count; i++) {
8930             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8931             if (sc->intr[i].resource && sc->intr[i].rid) {
8932                 bus_release_resource(sc->dev,
8933                                      SYS_RES_IRQ,
8934                                      sc->intr[i].rid,
8935                                      sc->intr[i].resource);
8936             }
8937         }
8938         pci_release_msi(sc->dev);
8939         break;
8940     default:
8941         /* nothing to do as initial allocation failed */
8942         break;
8943     }
8944 }
8945
8946 /*
8947  * This function determines and allocates the appropriate
8948  * interrupt based on system capabilites and user request.
8949  *
8950  * The user may force a particular interrupt mode, specify
8951  * the number of receive queues, specify the method for
8952  * distribuitng received frames to receive queues, or use
8953  * the default settings which will automatically select the
8954  * best supported combination.  In addition, the OS may or
8955  * may not support certain combinations of these settings.
8956  * This routine attempts to reconcile the settings requested
8957  * by the user with the capabilites available from the system
8958  * to select the optimal combination of features.
8959  *
8960  * Returns:
8961  *   0 = Success, !0 = Failure.
8962  */
8963 static int
8964 bxe_interrupt_alloc(struct bxe_softc *sc)
8965 {
8966     int msix_count = 0;
8967     int msi_count = 0;
8968     int num_requested = 0;
8969     int num_allocated = 0;
8970     int rid, i, j;
8971     int rc;
8972
8973     /* get the number of available MSI/MSI-X interrupts from the OS */
8974     if (sc->interrupt_mode > 0) {
8975         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8976             msix_count = pci_msix_count(sc->dev);
8977         }
8978
8979         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8980             msi_count = pci_msi_count(sc->dev);
8981         }
8982
8983         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8984               msi_count, msix_count);
8985     }
8986
8987     do { /* try allocating MSI-X interrupt resources (at least 2) */
8988         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8989             break;
8990         }
8991
8992         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8993             (msix_count < 2)) {
8994             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8995             break;
8996         }
8997
8998         /* ask for the necessary number of MSI-X vectors */
8999         num_requested = min((sc->num_queues + 1), msix_count);
9000
9001         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
9002
9003         num_allocated = num_requested;
9004         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
9005             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
9006             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9007             break;
9008         }
9009
9010         if (num_allocated < 2) { /* possible? */
9011             BLOGE(sc, "MSI-X allocation less than 2!\n");
9012             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9013             pci_release_msi(sc->dev);
9014             break;
9015         }
9016
9017         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
9018               num_requested, num_allocated);
9019
9020         /* best effort so use the number of vectors allocated to us */
9021         sc->intr_count = num_allocated;
9022         sc->num_queues = num_allocated - 1;
9023
9024         rid = 1; /* initial resource identifier */
9025
9026         /* allocate the MSI-X vectors */
9027         for (i = 0; i < num_allocated; i++) {
9028             sc->intr[i].rid = (rid + i);
9029
9030             if ((sc->intr[i].resource =
9031                  bus_alloc_resource_any(sc->dev,
9032                                         SYS_RES_IRQ,
9033                                         &sc->intr[i].rid,
9034                                         RF_ACTIVE)) == NULL) {
9035                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
9036                       i, (rid + i));
9037
9038                 for (j = (i - 1); j >= 0; j--) {
9039                     bus_release_resource(sc->dev,
9040                                          SYS_RES_IRQ,
9041                                          sc->intr[j].rid,
9042                                          sc->intr[j].resource);
9043                 }
9044
9045                 sc->intr_count = 0;
9046                 sc->num_queues = 0;
9047                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
9048                 pci_release_msi(sc->dev);
9049                 break;
9050             }
9051
9052             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
9053         }
9054     } while (0);
9055
9056     do { /* try allocating MSI vector resources (at least 2) */
9057         if (sc->interrupt_mode != INTR_MODE_MSI) {
9058             break;
9059         }
9060
9061         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
9062             (msi_count < 1)) {
9063             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9064             break;
9065         }
9066
9067         /* ask for a single MSI vector */
9068         num_requested = 1;
9069
9070         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
9071
9072         num_allocated = num_requested;
9073         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
9074             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
9075             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9076             break;
9077         }
9078
9079         if (num_allocated != 1) { /* possible? */
9080             BLOGE(sc, "MSI allocation is not 1!\n");
9081             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9082             pci_release_msi(sc->dev);
9083             break;
9084         }
9085
9086         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9087               num_requested, num_allocated);
9088
9089         /* best effort so use the number of vectors allocated to us */
9090         sc->intr_count = num_allocated;
9091         sc->num_queues = num_allocated;
9092
9093         rid = 1; /* initial resource identifier */
9094
9095         sc->intr[0].rid = rid;
9096
9097         if ((sc->intr[0].resource =
9098              bus_alloc_resource_any(sc->dev,
9099                                     SYS_RES_IRQ,
9100                                     &sc->intr[0].rid,
9101                                     RF_ACTIVE)) == NULL) {
9102             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9103             sc->intr_count = 0;
9104             sc->num_queues = 0;
9105             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9106             pci_release_msi(sc->dev);
9107             break;
9108         }
9109
9110         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9111     } while (0);
9112
9113     do { /* try allocating INTx vector resources */
9114         if (sc->interrupt_mode != INTR_MODE_INTX) {
9115             break;
9116         }
9117
9118         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9119
9120         /* only one vector for INTx */
9121         sc->intr_count = 1;
9122         sc->num_queues = 1;
9123
9124         rid = 0; /* initial resource identifier */
9125
9126         sc->intr[0].rid = rid;
9127
9128         if ((sc->intr[0].resource =
9129              bus_alloc_resource_any(sc->dev,
9130                                     SYS_RES_IRQ,
9131                                     &sc->intr[0].rid,
9132                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9133             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9134             sc->intr_count = 0;
9135             sc->num_queues = 0;
9136             sc->interrupt_mode = -1; /* Failed! */
9137             break;
9138         }
9139
9140         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9141     } while (0);
9142
9143     if (sc->interrupt_mode == -1) {
9144         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9145         rc = 1;
9146     } else {
9147         BLOGD(sc, DBG_LOAD,
9148               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9149               sc->interrupt_mode, sc->num_queues);
9150         rc = 0;
9151     }
9152
9153     return (rc);
9154 }
9155
9156 static void
9157 bxe_interrupt_detach(struct bxe_softc *sc)
9158 {
9159     struct bxe_fastpath *fp;
9160     int i;
9161
9162     /* release interrupt resources */
9163     for (i = 0; i < sc->intr_count; i++) {
9164         if (sc->intr[i].resource && sc->intr[i].tag) {
9165             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9166             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9167         }
9168     }
9169
9170     for (i = 0; i < sc->num_queues; i++) {
9171         fp = &sc->fp[i];
9172         if (fp->tq) {
9173             taskqueue_drain(fp->tq, &fp->tq_task);
9174             taskqueue_free(fp->tq);
9175             fp->tq = NULL;
9176         }
9177     }
9178
9179
9180     if (sc->sp_tq) {
9181         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9182         taskqueue_free(sc->sp_tq);
9183         sc->sp_tq = NULL;
9184     }
9185 }
9186
9187 /*
9188  * Enables interrupts and attach to the ISR.
9189  *
9190  * When using multiple MSI/MSI-X vectors the first vector
9191  * is used for slowpath operations while all remaining
9192  * vectors are used for fastpath operations.  If only a
9193  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9194  * ISR must look for both slowpath and fastpath completions.
9195  */
9196 static int
9197 bxe_interrupt_attach(struct bxe_softc *sc)
9198 {
9199     struct bxe_fastpath *fp;
9200     int rc = 0;
9201     int i;
9202
9203     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9204              "bxe%d_sp_tq", sc->unit);
9205     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9206     sc->sp_tq = taskqueue_create_fast(sc->sp_tq_name, M_NOWAIT,
9207                                       taskqueue_thread_enqueue,
9208                                       &sc->sp_tq);
9209     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9210                             "%s", sc->sp_tq_name);
9211
9212
9213     for (i = 0; i < sc->num_queues; i++) {
9214         fp = &sc->fp[i];
9215         snprintf(fp->tq_name, sizeof(fp->tq_name),
9216                  "bxe%d_fp%d_tq", sc->unit, i);
9217         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9218         fp->tq = taskqueue_create_fast(fp->tq_name, M_NOWAIT,
9219                                        taskqueue_thread_enqueue,
9220                                        &fp->tq);
9221         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9222                                 "%s", fp->tq_name);
9223     }
9224
9225     /* setup interrupt handlers */
9226     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9227         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9228
9229         /*
9230          * Setup the interrupt handler. Note that we pass the driver instance
9231          * to the interrupt handler for the slowpath.
9232          */
9233         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9234                                  (INTR_TYPE_NET | INTR_MPSAFE),
9235                                  NULL, bxe_intr_sp, sc,
9236                                  &sc->intr[0].tag)) != 0) {
9237             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9238             goto bxe_interrupt_attach_exit;
9239         }
9240
9241         bus_describe_intr(sc->dev, sc->intr[0].resource,
9242                           sc->intr[0].tag, "sp");
9243
9244         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9245
9246         /* initialize the fastpath vectors (note the first was used for sp) */
9247         for (i = 0; i < sc->num_queues; i++) {
9248             fp = &sc->fp[i];
9249             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9250
9251             /*
9252              * Setup the interrupt handler. Note that we pass the
9253              * fastpath context to the interrupt handler in this
9254              * case.
9255              */
9256             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9257                                      (INTR_TYPE_NET | INTR_MPSAFE),
9258                                      NULL, bxe_intr_fp, fp,
9259                                      &sc->intr[i + 1].tag)) != 0) {
9260                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9261                       (i + 1), rc);
9262                 goto bxe_interrupt_attach_exit;
9263             }
9264
9265             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9266                               sc->intr[i + 1].tag, "fp%02d", i);
9267
9268             /* bind the fastpath instance to a cpu */
9269             if (sc->num_queues > 1) {
9270                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9271             }
9272
9273             fp->state = BXE_FP_STATE_IRQ;
9274         }
9275     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9276         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9277
9278         /*
9279          * Setup the interrupt handler. Note that we pass the
9280          * driver instance to the interrupt handler which
9281          * will handle both the slowpath and fastpath.
9282          */
9283         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9284                                  (INTR_TYPE_NET | INTR_MPSAFE),
9285                                  NULL, bxe_intr_legacy, sc,
9286                                  &sc->intr[0].tag)) != 0) {
9287             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9288             goto bxe_interrupt_attach_exit;
9289         }
9290
9291     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9292         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9293
9294         /*
9295          * Setup the interrupt handler. Note that we pass the
9296          * driver instance to the interrupt handler which
9297          * will handle both the slowpath and fastpath.
9298          */
9299         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9300                                  (INTR_TYPE_NET | INTR_MPSAFE),
9301                                  NULL, bxe_intr_legacy, sc,
9302                                  &sc->intr[0].tag)) != 0) {
9303             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9304             goto bxe_interrupt_attach_exit;
9305         }
9306     }
9307
9308 bxe_interrupt_attach_exit:
9309
9310     return (rc);
9311 }
9312
9313 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9314 static int  bxe_init_hw_common(struct bxe_softc *sc);
9315 static int  bxe_init_hw_port(struct bxe_softc *sc);
9316 static int  bxe_init_hw_func(struct bxe_softc *sc);
9317 static void bxe_reset_common(struct bxe_softc *sc);
9318 static void bxe_reset_port(struct bxe_softc *sc);
9319 static void bxe_reset_func(struct bxe_softc *sc);
9320 static int  bxe_gunzip_init(struct bxe_softc *sc);
9321 static void bxe_gunzip_end(struct bxe_softc *sc);
9322 static int  bxe_init_firmware(struct bxe_softc *sc);
9323 static void bxe_release_firmware(struct bxe_softc *sc);
9324
9325 static struct
9326 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9327     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9328     .init_hw_cmn      = bxe_init_hw_common,
9329     .init_hw_port     = bxe_init_hw_port,
9330     .init_hw_func     = bxe_init_hw_func,
9331
9332     .reset_hw_cmn     = bxe_reset_common,
9333     .reset_hw_port    = bxe_reset_port,
9334     .reset_hw_func    = bxe_reset_func,
9335
9336     .gunzip_init      = bxe_gunzip_init,
9337     .gunzip_end       = bxe_gunzip_end,
9338
9339     .init_fw          = bxe_init_firmware,
9340     .release_fw       = bxe_release_firmware,
9341 };
9342
9343 static void
9344 bxe_init_func_obj(struct bxe_softc *sc)
9345 {
9346     sc->dmae_ready = 0;
9347
9348     ecore_init_func_obj(sc,
9349                         &sc->func_obj,
9350                         BXE_SP(sc, func_rdata),
9351                         BXE_SP_MAPPING(sc, func_rdata),
9352                         BXE_SP(sc, func_afex_rdata),
9353                         BXE_SP_MAPPING(sc, func_afex_rdata),
9354                         &bxe_func_sp_drv);
9355 }
9356
9357 static int
9358 bxe_init_hw(struct bxe_softc *sc,
9359             uint32_t         load_code)
9360 {
9361     struct ecore_func_state_params func_params = { NULL };
9362     int rc;
9363
9364     /* prepare the parameters for function state transitions */
9365     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9366
9367     func_params.f_obj = &sc->func_obj;
9368     func_params.cmd = ECORE_F_CMD_HW_INIT;
9369
9370     func_params.params.hw_init.load_phase = load_code;
9371
9372     /*
9373      * Via a plethora of function pointers, we will eventually reach
9374      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9375      */
9376     rc = ecore_func_state_change(sc, &func_params);
9377
9378     return (rc);
9379 }
9380
9381 static void
9382 bxe_fill(struct bxe_softc *sc,
9383          uint32_t         addr,
9384          int              fill,
9385          uint32_t         len)
9386 {
9387     uint32_t i;
9388
9389     if (!(len % 4) && !(addr % 4)) {
9390         for (i = 0; i < len; i += 4) {
9391             REG_WR(sc, (addr + i), fill);
9392         }
9393     } else {
9394         for (i = 0; i < len; i++) {
9395             REG_WR8(sc, (addr + i), fill);
9396         }
9397     }
9398 }
9399
9400 /* writes FP SP data to FW - data_size in dwords */
9401 static void
9402 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9403                   int              fw_sb_id,
9404                   uint32_t         *sb_data_p,
9405                   uint32_t         data_size)
9406 {
9407     int index;
9408
9409     for (index = 0; index < data_size; index++) {
9410         REG_WR(sc,
9411                (BAR_CSTRORM_INTMEM +
9412                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9413                 (sizeof(uint32_t) * index)),
9414                *(sb_data_p + index));
9415     }
9416 }
9417
9418 static void
9419 bxe_zero_fp_sb(struct bxe_softc *sc,
9420                int              fw_sb_id)
9421 {
9422     struct hc_status_block_data_e2 sb_data_e2;
9423     struct hc_status_block_data_e1x sb_data_e1x;
9424     uint32_t *sb_data_p;
9425     uint32_t data_size = 0;
9426
9427     if (!CHIP_IS_E1x(sc)) {
9428         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9429         sb_data_e2.common.state = SB_DISABLED;
9430         sb_data_e2.common.p_func.vf_valid = FALSE;
9431         sb_data_p = (uint32_t *)&sb_data_e2;
9432         data_size = (sizeof(struct hc_status_block_data_e2) /
9433                      sizeof(uint32_t));
9434     } else {
9435         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9436         sb_data_e1x.common.state = SB_DISABLED;
9437         sb_data_e1x.common.p_func.vf_valid = FALSE;
9438         sb_data_p = (uint32_t *)&sb_data_e1x;
9439         data_size = (sizeof(struct hc_status_block_data_e1x) /
9440                      sizeof(uint32_t));
9441     }
9442
9443     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9444
9445     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9446              0, CSTORM_STATUS_BLOCK_SIZE);
9447     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9448              0, CSTORM_SYNC_BLOCK_SIZE);
9449 }
9450
9451 static void
9452 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9453                   struct hc_sp_status_block_data *sp_sb_data)
9454 {
9455     int i;
9456
9457     for (i = 0;
9458          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9459          i++) {
9460         REG_WR(sc,
9461                (BAR_CSTRORM_INTMEM +
9462                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9463                 (i * sizeof(uint32_t))),
9464                *((uint32_t *)sp_sb_data + i));
9465     }
9466 }
9467
9468 static void
9469 bxe_zero_sp_sb(struct bxe_softc *sc)
9470 {
9471     struct hc_sp_status_block_data sp_sb_data;
9472
9473     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9474
9475     sp_sb_data.state           = SB_DISABLED;
9476     sp_sb_data.p_func.vf_valid = FALSE;
9477
9478     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9479
9480     bxe_fill(sc,
9481              (BAR_CSTRORM_INTMEM +
9482               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9483               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9484     bxe_fill(sc,
9485              (BAR_CSTRORM_INTMEM +
9486               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9487               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9488 }
9489
9490 static void
9491 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9492                              int                       igu_sb_id,
9493                              int                       igu_seg_id)
9494 {
9495     hc_sm->igu_sb_id      = igu_sb_id;
9496     hc_sm->igu_seg_id     = igu_seg_id;
9497     hc_sm->timer_value    = 0xFF;
9498     hc_sm->time_to_expire = 0xFFFFFFFF;
9499 }
9500
9501 static void
9502 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9503 {
9504     /* zero out state machine indices */
9505
9506     /* rx indices */
9507     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9508
9509     /* tx indices */
9510     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9511     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9512     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9513     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9514
9515     /* map indices */
9516
9517     /* rx indices */
9518     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9519         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9520
9521     /* tx indices */
9522     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9523         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9524     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9525         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9526     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9527         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9528     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9529         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9530 }
9531
9532 static void
9533 bxe_init_sb(struct bxe_softc *sc,
9534             bus_addr_t       busaddr,
9535             int              vfid,
9536             uint8_t          vf_valid,
9537             int              fw_sb_id,
9538             int              igu_sb_id)
9539 {
9540     struct hc_status_block_data_e2  sb_data_e2;
9541     struct hc_status_block_data_e1x sb_data_e1x;
9542     struct hc_status_block_sm       *hc_sm_p;
9543     uint32_t *sb_data_p;
9544     int igu_seg_id;
9545     int data_size;
9546
9547     if (CHIP_INT_MODE_IS_BC(sc)) {
9548         igu_seg_id = HC_SEG_ACCESS_NORM;
9549     } else {
9550         igu_seg_id = IGU_SEG_ACCESS_NORM;
9551     }
9552
9553     bxe_zero_fp_sb(sc, fw_sb_id);
9554
9555     if (!CHIP_IS_E1x(sc)) {
9556         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9557         sb_data_e2.common.state = SB_ENABLED;
9558         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9559         sb_data_e2.common.p_func.vf_id = vfid;
9560         sb_data_e2.common.p_func.vf_valid = vf_valid;
9561         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9562         sb_data_e2.common.same_igu_sb_1b = TRUE;
9563         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9564         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9565         hc_sm_p = sb_data_e2.common.state_machine;
9566         sb_data_p = (uint32_t *)&sb_data_e2;
9567         data_size = (sizeof(struct hc_status_block_data_e2) /
9568                      sizeof(uint32_t));
9569         bxe_map_sb_state_machines(sb_data_e2.index_data);
9570     } else {
9571         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9572         sb_data_e1x.common.state = SB_ENABLED;
9573         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9574         sb_data_e1x.common.p_func.vf_id = 0xff;
9575         sb_data_e1x.common.p_func.vf_valid = FALSE;
9576         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9577         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9578         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9579         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9580         hc_sm_p = sb_data_e1x.common.state_machine;
9581         sb_data_p = (uint32_t *)&sb_data_e1x;
9582         data_size = (sizeof(struct hc_status_block_data_e1x) /
9583                      sizeof(uint32_t));
9584         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9585     }
9586
9587     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9588     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9589
9590     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9591
9592     /* write indices to HW - PCI guarantees endianity of regpairs */
9593     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9594 }
9595
9596 static inline uint8_t
9597 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9598 {
9599     if (CHIP_IS_E1x(fp->sc)) {
9600         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9601     } else {
9602         return (fp->cl_id);
9603     }
9604 }
9605
9606 static inline uint32_t
9607 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9608                            struct bxe_fastpath *fp)
9609 {
9610     uint32_t offset = BAR_USTRORM_INTMEM;
9611
9612     if (!CHIP_IS_E1x(sc)) {
9613         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9614     } else {
9615         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9616     }
9617
9618     return (offset);
9619 }
9620
9621 static void
9622 bxe_init_eth_fp(struct bxe_softc *sc,
9623                 int              idx)
9624 {
9625     struct bxe_fastpath *fp = &sc->fp[idx];
9626     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9627     unsigned long q_type = 0;
9628     int cos;
9629
9630     fp->sc    = sc;
9631     fp->index = idx;
9632
9633     snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
9634              "bxe%d_fp%d_tx_lock", sc->unit, idx);
9635     mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
9636
9637     snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
9638              "bxe%d_fp%d_rx_lock", sc->unit, idx);
9639     mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
9640
9641     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9642     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9643
9644     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9645                     (SC_L_ID(sc) + idx) :
9646                     /* want client ID same as IGU SB ID for non-E1 */
9647                     fp->igu_sb_id;
9648     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9649
9650     /* setup sb indices */
9651     if (!CHIP_IS_E1x(sc)) {
9652         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9653         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9654     } else {
9655         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9656         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9657     }
9658
9659     /* init shortcut */
9660     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9661
9662     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9663
9664     /*
9665      * XXX If multiple CoS is ever supported then each fastpath structure
9666      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9667      */
9668     for (cos = 0; cos < sc->max_cos; cos++) {
9669         cids[cos] = idx;
9670     }
9671     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9672
9673     /* nothing more for a VF to do */
9674     if (IS_VF(sc)) {
9675         return;
9676     }
9677
9678     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9679                 fp->fw_sb_id, fp->igu_sb_id);
9680
9681     bxe_update_fp_sb_idx(fp);
9682
9683     /* Configure Queue State object */
9684     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9685     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9686
9687     ecore_init_queue_obj(sc,
9688                          &sc->sp_objs[idx].q_obj,
9689                          fp->cl_id,
9690                          cids,
9691                          sc->max_cos,
9692                          SC_FUNC(sc),
9693                          BXE_SP(sc, q_rdata),
9694                          BXE_SP_MAPPING(sc, q_rdata),
9695                          q_type);
9696
9697     /* configure classification DBs */
9698     ecore_init_mac_obj(sc,
9699                        &sc->sp_objs[idx].mac_obj,
9700                        fp->cl_id,
9701                        idx,
9702                        SC_FUNC(sc),
9703                        BXE_SP(sc, mac_rdata),
9704                        BXE_SP_MAPPING(sc, mac_rdata),
9705                        ECORE_FILTER_MAC_PENDING,
9706                        &sc->sp_state,
9707                        ECORE_OBJ_TYPE_RX_TX,
9708                        &sc->macs_pool);
9709
9710     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9711           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9712 }
9713
9714 static inline void
9715 bxe_update_rx_prod(struct bxe_softc    *sc,
9716                    struct bxe_fastpath *fp,
9717                    uint16_t            rx_bd_prod,
9718                    uint16_t            rx_cq_prod,
9719                    uint16_t            rx_sge_prod)
9720 {
9721     struct ustorm_eth_rx_producers rx_prods = { 0 };
9722     uint32_t i;
9723
9724     /* update producers */
9725     rx_prods.bd_prod  = rx_bd_prod;
9726     rx_prods.cqe_prod = rx_cq_prod;
9727     rx_prods.sge_prod = rx_sge_prod;
9728
9729     /*
9730      * Make sure that the BD and SGE data is updated before updating the
9731      * producers since FW might read the BD/SGE right after the producer
9732      * is updated.
9733      * This is only applicable for weak-ordered memory model archs such
9734      * as IA-64. The following barrier is also mandatory since FW will
9735      * assumes BDs must have buffers.
9736      */
9737     wmb();
9738
9739     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9740         REG_WR(sc,
9741                (fp->ustorm_rx_prods_offset + (i * 4)),
9742                ((uint32_t *)&rx_prods)[i]);
9743     }
9744
9745     wmb(); /* keep prod updates ordered */
9746
9747     BLOGD(sc, DBG_RX,
9748           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9749           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9750 }
9751
9752 static void
9753 bxe_init_rx_rings(struct bxe_softc *sc)
9754 {
9755     struct bxe_fastpath *fp;
9756     int i;
9757
9758     for (i = 0; i < sc->num_queues; i++) {
9759         fp = &sc->fp[i];
9760
9761         fp->rx_bd_cons = 0;
9762
9763         /*
9764          * Activate the BD ring...
9765          * Warning, this will generate an interrupt (to the TSTORM)
9766          * so this can only be done after the chip is initialized
9767          */
9768         bxe_update_rx_prod(sc, fp,
9769                            fp->rx_bd_prod,
9770                            fp->rx_cq_prod,
9771                            fp->rx_sge_prod);
9772
9773         if (i != 0) {
9774             continue;
9775         }
9776
9777         if (CHIP_IS_E1(sc)) {
9778             REG_WR(sc,
9779                    (BAR_USTRORM_INTMEM +
9780                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9781                    U64_LO(fp->rcq_dma.paddr));
9782             REG_WR(sc,
9783                    (BAR_USTRORM_INTMEM +
9784                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9785                    U64_HI(fp->rcq_dma.paddr));
9786         }
9787     }
9788 }
9789
9790 static void
9791 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9792 {
9793     SET_FLAG(fp->tx_db.data.header.header, DOORBELL_HDR_DB_TYPE, 1);
9794     fp->tx_db.data.zero_fill1 = 0;
9795     fp->tx_db.data.prod = 0;
9796
9797     fp->tx_pkt_prod = 0;
9798     fp->tx_pkt_cons = 0;
9799     fp->tx_bd_prod = 0;
9800     fp->tx_bd_cons = 0;
9801     fp->eth_q_stats.tx_pkts = 0;
9802 }
9803
9804 static inline void
9805 bxe_init_tx_rings(struct bxe_softc *sc)
9806 {
9807     int i;
9808
9809     for (i = 0; i < sc->num_queues; i++) {
9810         bxe_init_tx_ring_one(&sc->fp[i]);
9811     }
9812 }
9813
9814 static void
9815 bxe_init_def_sb(struct bxe_softc *sc)
9816 {
9817     struct host_sp_status_block *def_sb = sc->def_sb;
9818     bus_addr_t mapping = sc->def_sb_dma.paddr;
9819     int igu_sp_sb_index;
9820     int igu_seg_id;
9821     int port = SC_PORT(sc);
9822     int func = SC_FUNC(sc);
9823     int reg_offset, reg_offset_en5;
9824     uint64_t section;
9825     int index, sindex;
9826     struct hc_sp_status_block_data sp_sb_data;
9827
9828     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9829
9830     if (CHIP_INT_MODE_IS_BC(sc)) {
9831         igu_sp_sb_index = DEF_SB_IGU_ID;
9832         igu_seg_id = HC_SEG_ACCESS_DEF;
9833     } else {
9834         igu_sp_sb_index = sc->igu_dsb_id;
9835         igu_seg_id = IGU_SEG_ACCESS_DEF;
9836     }
9837
9838     /* attentions */
9839     section = ((uint64_t)mapping +
9840                offsetof(struct host_sp_status_block, atten_status_block));
9841     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9842     sc->attn_state = 0;
9843
9844     reg_offset = (port) ?
9845                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9846                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9847     reg_offset_en5 = (port) ?
9848                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9849                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9850
9851     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9852         /* take care of sig[0]..sig[4] */
9853         for (sindex = 0; sindex < 4; sindex++) {
9854             sc->attn_group[index].sig[sindex] =
9855                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9856         }
9857
9858         if (!CHIP_IS_E1x(sc)) {
9859             /*
9860              * enable5 is separate from the rest of the registers,
9861              * and the address skip is 4 and not 16 between the
9862              * different groups
9863              */
9864             sc->attn_group[index].sig[4] =
9865                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9866         } else {
9867             sc->attn_group[index].sig[4] = 0;
9868         }
9869     }
9870
9871     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9872         reg_offset = (port) ?
9873                          HC_REG_ATTN_MSG1_ADDR_L :
9874                          HC_REG_ATTN_MSG0_ADDR_L;
9875         REG_WR(sc, reg_offset, U64_LO(section));
9876         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9877     } else if (!CHIP_IS_E1x(sc)) {
9878         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9879         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9880     }
9881
9882     section = ((uint64_t)mapping +
9883                offsetof(struct host_sp_status_block, sp_sb));
9884
9885     bxe_zero_sp_sb(sc);
9886
9887     /* PCI guarantees endianity of regpair */
9888     sp_sb_data.state           = SB_ENABLED;
9889     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9890     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9891     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9892     sp_sb_data.igu_seg_id      = igu_seg_id;
9893     sp_sb_data.p_func.pf_id    = func;
9894     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9895     sp_sb_data.p_func.vf_id    = 0xff;
9896
9897     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9898
9899     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9900 }
9901
9902 static void
9903 bxe_init_sp_ring(struct bxe_softc *sc)
9904 {
9905     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9906     sc->spq_prod_idx = 0;
9907     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9908     sc->spq_prod_bd = sc->spq;
9909     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9910 }
9911
9912 static void
9913 bxe_init_eq_ring(struct bxe_softc *sc)
9914 {
9915     union event_ring_elem *elem;
9916     int i;
9917
9918     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9919         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9920
9921         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9922                                                  BCM_PAGE_SIZE *
9923                                                  (i % NUM_EQ_PAGES)));
9924         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9925                                                  BCM_PAGE_SIZE *
9926                                                  (i % NUM_EQ_PAGES)));
9927     }
9928
9929     sc->eq_cons    = 0;
9930     sc->eq_prod    = NUM_EQ_DESC;
9931     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9932
9933     atomic_store_rel_long(&sc->eq_spq_left,
9934                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9935                                NUM_EQ_DESC) - 1));
9936 }
9937
9938 static void
9939 bxe_init_internal_common(struct bxe_softc *sc)
9940 {
9941     int i;
9942
9943     if (IS_MF_SI(sc)) {
9944         /*
9945          * In switch independent mode, the TSTORM needs to accept
9946          * packets that failed classification, since approximate match
9947          * mac addresses aren't written to NIG LLH.
9948          */
9949         REG_WR8(sc,
9950                 (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
9951                 2);
9952     } else if (!CHIP_IS_E1(sc)) { /* 57710 doesn't support MF */
9953         REG_WR8(sc,
9954                 (BAR_TSTRORM_INTMEM + TSTORM_ACCEPT_CLASSIFY_FAILED_OFFSET),
9955                 0);
9956     }
9957
9958     /*
9959      * Zero this manually as its initialization is currently missing
9960      * in the initTool.
9961      */
9962     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9963         REG_WR(sc,
9964                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9965                0);
9966     }
9967
9968     if (!CHIP_IS_E1x(sc)) {
9969         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9970                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9971     }
9972 }
9973
9974 static void
9975 bxe_init_internal(struct bxe_softc *sc,
9976                   uint32_t         load_code)
9977 {
9978     switch (load_code) {
9979     case FW_MSG_CODE_DRV_LOAD_COMMON:
9980     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9981         bxe_init_internal_common(sc);
9982         /* no break */
9983
9984     case FW_MSG_CODE_DRV_LOAD_PORT:
9985         /* nothing to do */
9986         /* no break */
9987
9988     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9989         /* internal memory per function is initialized inside bxe_pf_init */
9990         break;
9991
9992     default:
9993         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9994         break;
9995     }
9996 }
9997
9998 static void
9999 storm_memset_func_cfg(struct bxe_softc                         *sc,
10000                       struct tstorm_eth_function_common_config *tcfg,
10001                       uint16_t                                  abs_fid)
10002 {
10003     uint32_t addr;
10004     size_t size;
10005
10006     addr = (BAR_TSTRORM_INTMEM +
10007             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
10008     size = sizeof(struct tstorm_eth_function_common_config);
10009     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
10010 }
10011
10012 static void
10013 bxe_func_init(struct bxe_softc            *sc,
10014               struct bxe_func_init_params *p)
10015 {
10016     struct tstorm_eth_function_common_config tcfg = { 0 };
10017
10018     if (CHIP_IS_E1x(sc)) {
10019         storm_memset_func_cfg(sc, &tcfg, p->func_id);
10020     }
10021
10022     /* Enable the function in the FW */
10023     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
10024     storm_memset_func_en(sc, p->func_id, 1);
10025
10026     /* spq */
10027     if (p->func_flgs & FUNC_FLG_SPQ) {
10028         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
10029         REG_WR(sc,
10030                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
10031                p->spq_prod);
10032     }
10033 }
10034
10035 /*
10036  * Calculates the sum of vn_min_rates.
10037  * It's needed for further normalizing of the min_rates.
10038  * Returns:
10039  *   sum of vn_min_rates.
10040  *     or
10041  *   0 - if all the min_rates are 0.
10042  * In the later case fainess algorithm should be deactivated.
10043  * If all min rates are not zero then those that are zeroes will be set to 1.
10044  */
10045 static void
10046 bxe_calc_vn_min(struct bxe_softc       *sc,
10047                 struct cmng_init_input *input)
10048 {
10049     uint32_t vn_cfg;
10050     uint32_t vn_min_rate;
10051     int all_zero = 1;
10052     int vn;
10053
10054     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10055         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10056         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
10057                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
10058
10059         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10060             /* skip hidden VNs */
10061             vn_min_rate = 0;
10062         } else if (!vn_min_rate) {
10063             /* If min rate is zero - set it to 100 */
10064             vn_min_rate = DEF_MIN_RATE;
10065         } else {
10066             all_zero = 0;
10067         }
10068
10069         input->vnic_min_rate[vn] = vn_min_rate;
10070     }
10071
10072     /* if ETS or all min rates are zeros - disable fairness */
10073     if (BXE_IS_ETS_ENABLED(sc)) {
10074         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10075         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
10076     } else if (all_zero) {
10077         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10078         BLOGD(sc, DBG_LOAD,
10079               "Fariness disabled (all MIN values are zeroes)\n");
10080     } else {
10081         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
10082     }
10083 }
10084
10085 static inline uint16_t
10086 bxe_extract_max_cfg(struct bxe_softc *sc,
10087                     uint32_t         mf_cfg)
10088 {
10089     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
10090                         FUNC_MF_CFG_MAX_BW_SHIFT);
10091
10092     if (!max_cfg) {
10093         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
10094         max_cfg = 100;
10095     }
10096
10097     return (max_cfg);
10098 }
10099
10100 static void
10101 bxe_calc_vn_max(struct bxe_softc       *sc,
10102                 int                    vn,
10103                 struct cmng_init_input *input)
10104 {
10105     uint16_t vn_max_rate;
10106     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10107     uint32_t max_cfg;
10108
10109     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10110         vn_max_rate = 0;
10111     } else {
10112         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10113
10114         if (IS_MF_SI(sc)) {
10115             /* max_cfg in percents of linkspeed */
10116             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10117         } else { /* SD modes */
10118             /* max_cfg is absolute in 100Mb units */
10119             vn_max_rate = (max_cfg * 100);
10120         }
10121     }
10122
10123     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10124
10125     input->vnic_max_rate[vn] = vn_max_rate;
10126 }
10127
10128 static void
10129 bxe_cmng_fns_init(struct bxe_softc *sc,
10130                   uint8_t          read_cfg,
10131                   uint8_t          cmng_type)
10132 {
10133     struct cmng_init_input input;
10134     int vn;
10135
10136     memset(&input, 0, sizeof(struct cmng_init_input));
10137
10138     input.port_rate = sc->link_vars.line_speed;
10139
10140     if (cmng_type == CMNG_FNS_MINMAX) {
10141         /* read mf conf from shmem */
10142         if (read_cfg) {
10143             bxe_read_mf_cfg(sc);
10144         }
10145
10146         /* get VN min rate and enable fairness if not 0 */
10147         bxe_calc_vn_min(sc, &input);
10148
10149         /* get VN max rate */
10150         if (sc->port.pmf) {
10151             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10152                 bxe_calc_vn_max(sc, vn, &input);
10153             }
10154         }
10155
10156         /* always enable rate shaping and fairness */
10157         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10158
10159         ecore_init_cmng(&input, &sc->cmng);
10160         return;
10161     }
10162
10163     /* rate shaping and fairness are disabled */
10164     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10165 }
10166
10167 static int
10168 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10169 {
10170     if (CHIP_REV_IS_SLOW(sc)) {
10171         return (CMNG_FNS_NONE);
10172     }
10173
10174     if (IS_MF(sc)) {
10175         return (CMNG_FNS_MINMAX);
10176     }
10177
10178     return (CMNG_FNS_NONE);
10179 }
10180
10181 static void
10182 storm_memset_cmng(struct bxe_softc *sc,
10183                   struct cmng_init *cmng,
10184                   uint8_t          port)
10185 {
10186     int vn;
10187     int func;
10188     uint32_t addr;
10189     size_t size;
10190
10191     addr = (BAR_XSTRORM_INTMEM +
10192             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10193     size = sizeof(struct cmng_struct_per_port);
10194     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10195
10196     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10197         func = func_by_vn(sc, vn);
10198
10199         addr = (BAR_XSTRORM_INTMEM +
10200                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10201         size = sizeof(struct rate_shaping_vars_per_vn);
10202         ecore_storm_memset_struct(sc, addr, size,
10203                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10204
10205         addr = (BAR_XSTRORM_INTMEM +
10206                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10207         size = sizeof(struct fairness_vars_per_vn);
10208         ecore_storm_memset_struct(sc, addr, size,
10209                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10210     }
10211 }
10212
10213 static void
10214 bxe_pf_init(struct bxe_softc *sc)
10215 {
10216     struct bxe_func_init_params func_init = { 0 };
10217     struct event_ring_data eq_data = { { 0 } };
10218     uint16_t flags;
10219
10220     if (!CHIP_IS_E1x(sc)) {
10221         /* reset IGU PF statistics: MSIX + ATTN */
10222         /* PF */
10223         REG_WR(sc,
10224                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10225                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10226                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10227                0);
10228         /* ATTN */
10229         REG_WR(sc,
10230                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10231                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10232                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10233                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10234                0);
10235     }
10236
10237     /* function setup flags */
10238     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10239
10240     /*
10241      * This flag is relevant for E1x only.
10242      * E2 doesn't have a TPA configuration in a function level.
10243      */
10244     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10245
10246     func_init.func_flgs = flags;
10247     func_init.pf_id     = SC_FUNC(sc);
10248     func_init.func_id   = SC_FUNC(sc);
10249     func_init.spq_map   = sc->spq_dma.paddr;
10250     func_init.spq_prod  = sc->spq_prod_idx;
10251
10252     bxe_func_init(sc, &func_init);
10253
10254     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10255
10256     /*
10257      * Congestion management values depend on the link rate.
10258      * There is no active link so initial link rate is set to 10Gbps.
10259      * When the link comes up the congestion management values are
10260      * re-calculated according to the actual link rate.
10261      */
10262     sc->link_vars.line_speed = SPEED_10000;
10263     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10264
10265     /* Only the PMF sets the HW */
10266     if (sc->port.pmf) {
10267         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10268     }
10269
10270     /* init Event Queue - PCI bus guarantees correct endainity */
10271     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10272     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10273     eq_data.producer     = sc->eq_prod;
10274     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10275     eq_data.sb_id        = DEF_SB_ID;
10276     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10277 }
10278
10279 static void
10280 bxe_hc_int_enable(struct bxe_softc *sc)
10281 {
10282     int port = SC_PORT(sc);
10283     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10284     uint32_t val = REG_RD(sc, addr);
10285     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10286     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10287                            (sc->intr_count == 1)) ? TRUE : FALSE;
10288     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10289
10290     if (msix) {
10291         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10292                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10293         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10294                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10295         if (single_msix) {
10296             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10297         }
10298     } else if (msi) {
10299         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10300         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10301                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10302                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10303     } else {
10304         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10305                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10306                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10307                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10308
10309         if (!CHIP_IS_E1(sc)) {
10310             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10311                   val, port, addr);
10312
10313             REG_WR(sc, addr, val);
10314
10315             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10316         }
10317     }
10318
10319     if (CHIP_IS_E1(sc)) {
10320         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10321     }
10322
10323     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10324           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10325
10326     REG_WR(sc, addr, val);
10327
10328     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10329     mb();
10330
10331     if (!CHIP_IS_E1(sc)) {
10332         /* init leading/trailing edge */
10333         if (IS_MF(sc)) {
10334             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10335             if (sc->port.pmf) {
10336                 /* enable nig and gpio3 attention */
10337                 val |= 0x1100;
10338             }
10339         } else {
10340             val = 0xffff;
10341         }
10342
10343         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10344         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10345     }
10346
10347     /* make sure that interrupts are indeed enabled from here on */
10348     mb();
10349 }
10350
10351 static void
10352 bxe_igu_int_enable(struct bxe_softc *sc)
10353 {
10354     uint32_t val;
10355     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10356     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10357                            (sc->intr_count == 1)) ? TRUE : FALSE;
10358     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10359
10360     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10361
10362     if (msix) {
10363         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10364                  IGU_PF_CONF_SINGLE_ISR_EN);
10365         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10366                 IGU_PF_CONF_ATTN_BIT_EN);
10367         if (single_msix) {
10368             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10369         }
10370     } else if (msi) {
10371         val &= ~IGU_PF_CONF_INT_LINE_EN;
10372         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10373                 IGU_PF_CONF_ATTN_BIT_EN |
10374                 IGU_PF_CONF_SINGLE_ISR_EN);
10375     } else {
10376         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10377         val |= (IGU_PF_CONF_INT_LINE_EN |
10378                 IGU_PF_CONF_ATTN_BIT_EN |
10379                 IGU_PF_CONF_SINGLE_ISR_EN);
10380     }
10381
10382     /* clean previous status - need to configure igu prior to ack*/
10383     if ((!msix) || single_msix) {
10384         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10385         bxe_ack_int(sc);
10386     }
10387
10388     val |= IGU_PF_CONF_FUNC_EN;
10389
10390     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10391           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10392
10393     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10394
10395     mb();
10396
10397     /* init leading/trailing edge */
10398     if (IS_MF(sc)) {
10399         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10400         if (sc->port.pmf) {
10401             /* enable nig and gpio3 attention */
10402             val |= 0x1100;
10403         }
10404     } else {
10405         val = 0xffff;
10406     }
10407
10408     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10409     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10410
10411     /* make sure that interrupts are indeed enabled from here on */
10412     mb();
10413 }
10414
10415 static void
10416 bxe_int_enable(struct bxe_softc *sc)
10417 {
10418     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10419         bxe_hc_int_enable(sc);
10420     } else {
10421         bxe_igu_int_enable(sc);
10422     }
10423 }
10424
10425 static void
10426 bxe_hc_int_disable(struct bxe_softc *sc)
10427 {
10428     int port = SC_PORT(sc);
10429     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10430     uint32_t val = REG_RD(sc, addr);
10431
10432     /*
10433      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10434      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10435      * block
10436      */
10437     if (CHIP_IS_E1(sc)) {
10438         /*
10439          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10440          * to prevent from HC sending interrupts after we exit the function
10441          */
10442         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10443
10444         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10445                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10446                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10447     } else {
10448         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10449                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10450                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10451                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10452     }
10453
10454     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10455
10456     /* flush all outstanding writes */
10457     mb();
10458
10459     REG_WR(sc, addr, val);
10460     if (REG_RD(sc, addr) != val) {
10461         BLOGE(sc, "proper val not read from HC IGU!\n");
10462     }
10463 }
10464
10465 static void
10466 bxe_igu_int_disable(struct bxe_softc *sc)
10467 {
10468     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10469
10470     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10471              IGU_PF_CONF_INT_LINE_EN |
10472              IGU_PF_CONF_ATTN_BIT_EN);
10473
10474     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10475
10476     /* flush all outstanding writes */
10477     mb();
10478
10479     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10480     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10481         BLOGE(sc, "proper val not read from IGU!\n");
10482     }
10483 }
10484
10485 static void
10486 bxe_int_disable(struct bxe_softc *sc)
10487 {
10488     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10489         bxe_hc_int_disable(sc);
10490     } else {
10491         bxe_igu_int_disable(sc);
10492     }
10493 }
10494
10495 static void
10496 bxe_nic_init(struct bxe_softc *sc,
10497              int              load_code)
10498 {
10499     int i;
10500
10501     for (i = 0; i < sc->num_queues; i++) {
10502         bxe_init_eth_fp(sc, i);
10503     }
10504
10505     rmb(); /* ensure status block indices were read */
10506
10507     bxe_init_rx_rings(sc);
10508     bxe_init_tx_rings(sc);
10509
10510     if (IS_VF(sc)) {
10511         return;
10512     }
10513
10514     /* initialize MOD_ABS interrupts */
10515     elink_init_mod_abs_int(sc, &sc->link_vars,
10516                            sc->devinfo.chip_id,
10517                            sc->devinfo.shmem_base,
10518                            sc->devinfo.shmem2_base,
10519                            SC_PORT(sc));
10520
10521     bxe_init_def_sb(sc);
10522     bxe_update_dsb_idx(sc);
10523     bxe_init_sp_ring(sc);
10524     bxe_init_eq_ring(sc);
10525     bxe_init_internal(sc, load_code);
10526     bxe_pf_init(sc);
10527     bxe_stats_init(sc);
10528
10529     /* flush all before enabling interrupts */
10530     mb();
10531
10532     bxe_int_enable(sc);
10533
10534     /* check for SPIO5 */
10535     bxe_attn_int_deasserted0(sc,
10536                              REG_RD(sc,
10537                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10538                                      SC_PORT(sc)*4)) &
10539                              AEU_INPUTS_ATTN_BITS_SPIO5);
10540 }
10541
10542 static inline void
10543 bxe_init_objs(struct bxe_softc *sc)
10544 {
10545     /* mcast rules must be added to tx if tx switching is enabled */
10546     ecore_obj_type o_type =
10547         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10548                                          ECORE_OBJ_TYPE_RX;
10549
10550     /* RX_MODE controlling object */
10551     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10552
10553     /* multicast configuration controlling object */
10554     ecore_init_mcast_obj(sc,
10555                          &sc->mcast_obj,
10556                          sc->fp[0].cl_id,
10557                          sc->fp[0].index,
10558                          SC_FUNC(sc),
10559                          SC_FUNC(sc),
10560                          BXE_SP(sc, mcast_rdata),
10561                          BXE_SP_MAPPING(sc, mcast_rdata),
10562                          ECORE_FILTER_MCAST_PENDING,
10563                          &sc->sp_state,
10564                          o_type);
10565
10566     /* Setup CAM credit pools */
10567     ecore_init_mac_credit_pool(sc,
10568                                &sc->macs_pool,
10569                                SC_FUNC(sc),
10570                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10571                                                  VNICS_PER_PATH(sc));
10572
10573     ecore_init_vlan_credit_pool(sc,
10574                                 &sc->vlans_pool,
10575                                 SC_ABS_FUNC(sc) >> 1,
10576                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10577                                                   VNICS_PER_PATH(sc));
10578
10579     /* RSS configuration object */
10580     ecore_init_rss_config_obj(sc,
10581                               &sc->rss_conf_obj,
10582                               sc->fp[0].cl_id,
10583                               sc->fp[0].index,
10584                               SC_FUNC(sc),
10585                               SC_FUNC(sc),
10586                               BXE_SP(sc, rss_rdata),
10587                               BXE_SP_MAPPING(sc, rss_rdata),
10588                               ECORE_FILTER_RSS_CONF_PENDING,
10589                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10590 }
10591
10592 /*
10593  * Initialize the function. This must be called before sending CLIENT_SETUP
10594  * for the first client.
10595  */
10596 static inline int
10597 bxe_func_start(struct bxe_softc *sc)
10598 {
10599     struct ecore_func_state_params func_params = { NULL };
10600     struct ecore_func_start_params *start_params = &func_params.params.start;
10601
10602     /* Prepare parameters for function state transitions */
10603     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10604
10605     func_params.f_obj = &sc->func_obj;
10606     func_params.cmd = ECORE_F_CMD_START;
10607
10608     /* Function parameters */
10609     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10610     start_params->sd_vlan_tag = OVLAN(sc);
10611
10612     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10613         start_params->network_cos_mode = STATIC_COS;
10614     } else { /* CHIP_IS_E1X */
10615         start_params->network_cos_mode = FW_WRR;
10616     }
10617
10618     start_params->gre_tunnel_mode = 0;
10619     start_params->gre_tunnel_rss  = 0;
10620
10621     return (ecore_func_state_change(sc, &func_params));
10622 }
10623
10624 static int
10625 bxe_set_power_state(struct bxe_softc *sc,
10626                     uint8_t          state)
10627 {
10628     uint16_t pmcsr;
10629
10630     /* If there is no power capability, silently succeed */
10631     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10632         BLOGW(sc, "No power capability\n");
10633         return (0);
10634     }
10635
10636     pmcsr = pci_read_config(sc->dev,
10637                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10638                             2);
10639
10640     switch (state) {
10641     case PCI_PM_D0:
10642         pci_write_config(sc->dev,
10643                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10644                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10645
10646         if (pmcsr & PCIM_PSTAT_DMASK) {
10647             /* delay required during transition out of D3hot */
10648             DELAY(20000);
10649         }
10650
10651         break;
10652
10653     case PCI_PM_D3hot:
10654         /* XXX if there are other clients above don't shut down the power */
10655
10656         /* don't shut down the power for emulation and FPGA */
10657         if (CHIP_REV_IS_SLOW(sc)) {
10658             return (0);
10659         }
10660
10661         pmcsr &= ~PCIM_PSTAT_DMASK;
10662         pmcsr |= PCIM_PSTAT_D3;
10663
10664         if (sc->wol) {
10665             pmcsr |= PCIM_PSTAT_PMEENABLE;
10666         }
10667
10668         pci_write_config(sc->dev,
10669                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10670                          pmcsr, 4);
10671
10672         /*
10673          * No more memory access after this point until device is brought back
10674          * to D0 state.
10675          */
10676         break;
10677
10678     default:
10679         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10680             state, pmcsr);
10681         return (-1);
10682     }
10683
10684     return (0);
10685 }
10686
10687
10688 /* return true if succeeded to acquire the lock */
10689 static uint8_t
10690 bxe_trylock_hw_lock(struct bxe_softc *sc,
10691                     uint32_t         resource)
10692 {
10693     uint32_t lock_status;
10694     uint32_t resource_bit = (1 << resource);
10695     int func = SC_FUNC(sc);
10696     uint32_t hw_lock_control_reg;
10697
10698     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10699
10700     /* Validating that the resource is within range */
10701     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10702         BLOGD(sc, DBG_LOAD,
10703               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10704               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10705         return (FALSE);
10706     }
10707
10708     if (func <= 5) {
10709         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10710     } else {
10711         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10712     }
10713
10714     /* try to acquire the lock */
10715     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10716     lock_status = REG_RD(sc, hw_lock_control_reg);
10717     if (lock_status & resource_bit) {
10718         return (TRUE);
10719     }
10720
10721     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10722         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10723         lock_status, resource_bit);
10724
10725     return (FALSE);
10726 }
10727
10728 /*
10729  * Get the recovery leader resource id according to the engine this function
10730  * belongs to. Currently only only 2 engines is supported.
10731  */
10732 static int
10733 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10734 {
10735     if (SC_PATH(sc)) {
10736         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10737     } else {
10738         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10739     }
10740 }
10741
10742 /* try to acquire a leader lock for current engine */
10743 static uint8_t
10744 bxe_trylock_leader_lock(struct bxe_softc *sc)
10745 {
10746     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10747 }
10748
10749 static int
10750 bxe_release_leader_lock(struct bxe_softc *sc)
10751 {
10752     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10753 }
10754
10755 /* close gates #2, #3 and #4 */
10756 static void
10757 bxe_set_234_gates(struct bxe_softc *sc,
10758                   uint8_t          close)
10759 {
10760     uint32_t val;
10761
10762     /* gates #2 and #4a are closed/opened for "not E1" only */
10763     if (!CHIP_IS_E1(sc)) {
10764         /* #4 */
10765         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10766         /* #2 */
10767         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10768     }
10769
10770     /* #3 */
10771     if (CHIP_IS_E1x(sc)) {
10772         /* prevent interrupts from HC on both ports */
10773         val = REG_RD(sc, HC_REG_CONFIG_1);
10774         REG_WR(sc, HC_REG_CONFIG_1,
10775                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10776                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10777
10778         val = REG_RD(sc, HC_REG_CONFIG_0);
10779         REG_WR(sc, HC_REG_CONFIG_0,
10780                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10781                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10782     } else {
10783         /* Prevent incomming interrupts in IGU */
10784         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10785
10786         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10787                (!close) ?
10788                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10789                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10790     }
10791
10792     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10793           close ? "closing" : "opening");
10794
10795     wmb();
10796 }
10797
10798 /* poll for pending writes bit, it should get cleared in no more than 1s */
10799 static int
10800 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10801 {
10802     uint32_t cnt = 1000;
10803     uint32_t pend_bits = 0;
10804
10805     do {
10806         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10807
10808         if (pend_bits == 0) {
10809             break;
10810         }
10811
10812         DELAY(1000);
10813     } while (--cnt > 0);
10814
10815     if (cnt == 0) {
10816         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10817         return (-1);
10818     }
10819
10820     return (0);
10821 }
10822
10823 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10824
10825 static void
10826 bxe_clp_reset_prep(struct bxe_softc *sc,
10827                    uint32_t         *magic_val)
10828 {
10829     /* Do some magic... */
10830     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10831     *magic_val = val & SHARED_MF_CLP_MAGIC;
10832     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10833 }
10834
10835 /* restore the value of the 'magic' bit */
10836 static void
10837 bxe_clp_reset_done(struct bxe_softc *sc,
10838                    uint32_t         magic_val)
10839 {
10840     /* Restore the 'magic' bit value... */
10841     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10842     MFCFG_WR(sc, shared_mf_config.clp_mb,
10843               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10844 }
10845
10846 /* prepare for MCP reset, takes care of CLP configurations */
10847 static void
10848 bxe_reset_mcp_prep(struct bxe_softc *sc,
10849                    uint32_t         *magic_val)
10850 {
10851     uint32_t shmem;
10852     uint32_t validity_offset;
10853
10854     /* set `magic' bit in order to save MF config */
10855     if (!CHIP_IS_E1(sc)) {
10856         bxe_clp_reset_prep(sc, magic_val);
10857     }
10858
10859     /* get shmem offset */
10860     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10861     validity_offset =
10862         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10863
10864     /* Clear validity map flags */
10865     if (shmem > 0) {
10866         REG_WR(sc, shmem + validity_offset, 0);
10867     }
10868 }
10869
10870 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10871 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10872
10873 static void
10874 bxe_mcp_wait_one(struct bxe_softc *sc)
10875 {
10876     /* special handling for emulation and FPGA (10 times longer) */
10877     if (CHIP_REV_IS_SLOW(sc)) {
10878         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10879     } else {
10880         DELAY((MCP_ONE_TIMEOUT) * 1000);
10881     }
10882 }
10883
10884 /* initialize shmem_base and waits for validity signature to appear */
10885 static int
10886 bxe_init_shmem(struct bxe_softc *sc)
10887 {
10888     int cnt = 0;
10889     uint32_t val = 0;
10890
10891     do {
10892         sc->devinfo.shmem_base     =
10893         sc->link_params.shmem_base =
10894             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10895
10896         if (sc->devinfo.shmem_base) {
10897             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10898             if (val & SHR_MEM_VALIDITY_MB)
10899                 return (0);
10900         }
10901
10902         bxe_mcp_wait_one(sc);
10903
10904     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10905
10906     BLOGE(sc, "BAD MCP validity signature\n");
10907
10908     return (-1);
10909 }
10910
10911 static int
10912 bxe_reset_mcp_comp(struct bxe_softc *sc,
10913                    uint32_t         magic_val)
10914 {
10915     int rc = bxe_init_shmem(sc);
10916
10917     /* Restore the `magic' bit value */
10918     if (!CHIP_IS_E1(sc)) {
10919         bxe_clp_reset_done(sc, magic_val);
10920     }
10921
10922     return (rc);
10923 }
10924
10925 static void
10926 bxe_pxp_prep(struct bxe_softc *sc)
10927 {
10928     if (!CHIP_IS_E1(sc)) {
10929         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10930         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10931         wmb();
10932     }
10933 }
10934
10935 /*
10936  * Reset the whole chip except for:
10937  *      - PCIE core
10938  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10939  *      - IGU
10940  *      - MISC (including AEU)
10941  *      - GRC
10942  *      - RBCN, RBCP
10943  */
10944 static void
10945 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10946                             uint8_t          global)
10947 {
10948     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10949     uint32_t global_bits2, stay_reset2;
10950
10951     /*
10952      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10953      * (per chip) blocks.
10954      */
10955     global_bits2 =
10956         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10957         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10958
10959     /*
10960      * Don't reset the following blocks.
10961      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10962      *            reset, as in 4 port device they might still be owned
10963      *            by the MCP (there is only one leader per path).
10964      */
10965     not_reset_mask1 =
10966         MISC_REGISTERS_RESET_REG_1_RST_HC |
10967         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10968         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10969
10970     not_reset_mask2 =
10971         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10972         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10973         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10974         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10975         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10976         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10977         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10978         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10979         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10980         MISC_REGISTERS_RESET_REG_2_PGLC |
10981         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10982         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10983         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10984         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10985         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10986         MISC_REGISTERS_RESET_REG_2_UMAC1;
10987
10988     /*
10989      * Keep the following blocks in reset:
10990      *  - all xxMACs are handled by the elink code.
10991      */
10992     stay_reset2 =
10993         MISC_REGISTERS_RESET_REG_2_XMAC |
10994         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10995
10996     /* Full reset masks according to the chip */
10997     reset_mask1 = 0xffffffff;
10998
10999     if (CHIP_IS_E1(sc))
11000         reset_mask2 = 0xffff;
11001     else if (CHIP_IS_E1H(sc))
11002         reset_mask2 = 0x1ffff;
11003     else if (CHIP_IS_E2(sc))
11004         reset_mask2 = 0xfffff;
11005     else /* CHIP_IS_E3 */
11006         reset_mask2 = 0x3ffffff;
11007
11008     /* Don't reset global blocks unless we need to */
11009     if (!global)
11010         reset_mask2 &= ~global_bits2;
11011
11012     /*
11013      * In case of attention in the QM, we need to reset PXP
11014      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
11015      * because otherwise QM reset would release 'close the gates' shortly
11016      * before resetting the PXP, then the PSWRQ would send a write
11017      * request to PGLUE. Then when PXP is reset, PGLUE would try to
11018      * read the payload data from PSWWR, but PSWWR would not
11019      * respond. The write queue in PGLUE would stuck, dmae commands
11020      * would not return. Therefore it's important to reset the second
11021      * reset register (containing the
11022      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
11023      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
11024      * bit).
11025      */
11026     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
11027            reset_mask2 & (~not_reset_mask2));
11028
11029     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
11030            reset_mask1 & (~not_reset_mask1));
11031
11032     mb();
11033     wmb();
11034
11035     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
11036            reset_mask2 & (~stay_reset2));
11037
11038     mb();
11039     wmb();
11040
11041     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
11042     wmb();
11043 }
11044
11045 static int
11046 bxe_process_kill(struct bxe_softc *sc,
11047                  uint8_t          global)
11048 {
11049     int cnt = 1000;
11050     uint32_t val = 0;
11051     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
11052     uint32_t tags_63_32 = 0;
11053
11054     /* Empty the Tetris buffer, wait for 1s */
11055     do {
11056         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
11057         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
11058         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
11059         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
11060         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
11061         if (CHIP_IS_E3(sc)) {
11062             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
11063         }
11064
11065         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
11066             ((port_is_idle_0 & 0x1) == 0x1) &&
11067             ((port_is_idle_1 & 0x1) == 0x1) &&
11068             (pgl_exp_rom2 == 0xffffffff) &&
11069             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
11070             break;
11071         DELAY(1000);
11072     } while (cnt-- > 0);
11073
11074     if (cnt <= 0) {
11075         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
11076                   "are still outstanding read requests after 1s! "
11077                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
11078                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
11079               sr_cnt, blk_cnt, port_is_idle_0,
11080               port_is_idle_1, pgl_exp_rom2);
11081         return (-1);
11082     }
11083
11084     mb();
11085
11086     /* Close gates #2, #3 and #4 */
11087     bxe_set_234_gates(sc, TRUE);
11088
11089     /* Poll for IGU VQs for 57712 and newer chips */
11090     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
11091         return (-1);
11092     }
11093
11094     /* XXX indicate that "process kill" is in progress to MCP */
11095
11096     /* clear "unprepared" bit */
11097     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11098     mb();
11099
11100     /* Make sure all is written to the chip before the reset */
11101     wmb();
11102
11103     /*
11104      * Wait for 1ms to empty GLUE and PCI-E core queues,
11105      * PSWHST, GRC and PSWRD Tetris buffer.
11106      */
11107     DELAY(1000);
11108
11109     /* Prepare to chip reset: */
11110     /* MCP */
11111     if (global) {
11112         bxe_reset_mcp_prep(sc, &val);
11113     }
11114
11115     /* PXP */
11116     bxe_pxp_prep(sc);
11117     mb();
11118
11119     /* reset the chip */
11120     bxe_process_kill_chip_reset(sc, global);
11121     mb();
11122
11123     /* clear errors in PGB */
11124     if (!CHIP_IS_E1(sc))
11125         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11126
11127     /* Recover after reset: */
11128     /* MCP */
11129     if (global && bxe_reset_mcp_comp(sc, val)) {
11130         return (-1);
11131     }
11132
11133     /* XXX add resetting the NO_MCP mode DB here */
11134
11135     /* Open the gates #2, #3 and #4 */
11136     bxe_set_234_gates(sc, FALSE);
11137
11138     /* XXX
11139      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11140      * re-enable attentions
11141      */
11142
11143     return (0);
11144 }
11145
11146 static int
11147 bxe_leader_reset(struct bxe_softc *sc)
11148 {
11149     int rc = 0;
11150     uint8_t global = bxe_reset_is_global(sc);
11151     uint32_t load_code;
11152
11153     /*
11154      * If not going to reset MCP, load "fake" driver to reset HW while
11155      * driver is owner of the HW.
11156      */
11157     if (!global && !BXE_NOMCP(sc)) {
11158         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11159                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11160         if (!load_code) {
11161             BLOGE(sc, "MCP response failure, aborting\n");
11162             rc = -1;
11163             goto exit_leader_reset;
11164         }
11165
11166         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11167             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11168             BLOGE(sc, "MCP unexpected response, aborting\n");
11169             rc = -1;
11170             goto exit_leader_reset2;
11171         }
11172
11173         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11174         if (!load_code) {
11175             BLOGE(sc, "MCP response failure, aborting\n");
11176             rc = -1;
11177             goto exit_leader_reset2;
11178         }
11179     }
11180
11181     /* try to recover after the failure */
11182     if (bxe_process_kill(sc, global)) {
11183         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11184         rc = -1;
11185         goto exit_leader_reset2;
11186     }
11187
11188     /*
11189      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11190      * state.
11191      */
11192     bxe_set_reset_done(sc);
11193     if (global) {
11194         bxe_clear_reset_global(sc);
11195     }
11196
11197 exit_leader_reset2:
11198
11199     /* unload "fake driver" if it was loaded */
11200     if (!global && !BXE_NOMCP(sc)) {
11201         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11202         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11203     }
11204
11205 exit_leader_reset:
11206
11207     sc->is_leader = 0;
11208     bxe_release_leader_lock(sc);
11209
11210     mb();
11211     return (rc);
11212 }
11213
11214 /*
11215  * prepare INIT transition, parameters configured:
11216  *   - HC configuration
11217  *   - Queue's CDU context
11218  */
11219 static void
11220 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11221                    struct bxe_fastpath            *fp,
11222                    struct ecore_queue_init_params *init_params)
11223 {
11224     uint8_t cos;
11225     int cxt_index, cxt_offset;
11226
11227     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11228     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11229
11230     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11231     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11232
11233     /* HC rate */
11234     init_params->rx.hc_rate =
11235         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11236     init_params->tx.hc_rate =
11237         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11238
11239     /* FW SB ID */
11240     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11241
11242     /* CQ index among the SB indices */
11243     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11244     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11245
11246     /* set maximum number of COSs supported by this queue */
11247     init_params->max_cos = sc->max_cos;
11248
11249     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11250           fp->index, init_params->max_cos);
11251
11252     /* set the context pointers queue object */
11253     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11254         /* XXX change index/cid here if ever support multiple tx CoS */
11255         /* fp->txdata[cos]->cid */
11256         cxt_index = fp->index / ILT_PAGE_CIDS;
11257         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11258         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11259     }
11260 }
11261
11262 /* set flags that are common for the Tx-only and not normal connections */
11263 static unsigned long
11264 bxe_get_common_flags(struct bxe_softc    *sc,
11265                      struct bxe_fastpath *fp,
11266                      uint8_t             zero_stats)
11267 {
11268     unsigned long flags = 0;
11269
11270     /* PF driver will always initialize the Queue to an ACTIVE state */
11271     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11272
11273     /*
11274      * tx only connections collect statistics (on the same index as the
11275      * parent connection). The statistics are zeroed when the parent
11276      * connection is initialized.
11277      */
11278
11279     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11280     if (zero_stats) {
11281         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11282     }
11283
11284     /*
11285      * tx only connections can support tx-switching, though their
11286      * CoS-ness doesn't survive the loopback
11287      */
11288     if (sc->flags & BXE_TX_SWITCHING) {
11289         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11290     }
11291
11292     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11293
11294     return (flags);
11295 }
11296
11297 static unsigned long
11298 bxe_get_q_flags(struct bxe_softc    *sc,
11299                 struct bxe_fastpath *fp,
11300                 uint8_t             leading)
11301 {
11302     unsigned long flags = 0;
11303
11304     if (IS_MF_SD(sc)) {
11305         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11306     }
11307
11308     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11309         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11310         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11311     }
11312
11313     if (leading) {
11314         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11315         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11316     }
11317
11318     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11319
11320     /* merge with common flags */
11321     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11322 }
11323
11324 static void
11325 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11326                       struct bxe_fastpath               *fp,
11327                       struct ecore_general_setup_params *gen_init,
11328                       uint8_t                           cos)
11329 {
11330     gen_init->stat_id = bxe_stats_id(fp);
11331     gen_init->spcl_id = fp->cl_id;
11332     gen_init->mtu = sc->mtu;
11333     gen_init->cos = cos;
11334 }
11335
11336 static void
11337 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11338                  struct bxe_fastpath           *fp,
11339                  struct rxq_pause_params       *pause,
11340                  struct ecore_rxq_setup_params *rxq_init)
11341 {
11342     uint8_t max_sge = 0;
11343     uint16_t sge_sz = 0;
11344     uint16_t tpa_agg_size = 0;
11345
11346     pause->sge_th_lo = SGE_TH_LO(sc);
11347     pause->sge_th_hi = SGE_TH_HI(sc);
11348
11349     /* validate SGE ring has enough to cross high threshold */
11350     if (sc->dropless_fc &&
11351             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11352             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11353         BLOGW(sc, "sge ring threshold limit\n");
11354     }
11355
11356     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11357     tpa_agg_size = (2 * sc->mtu);
11358     if (tpa_agg_size < sc->max_aggregation_size) {
11359         tpa_agg_size = sc->max_aggregation_size;
11360     }
11361
11362     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11363     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11364                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11365     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11366
11367     /* pause - not for e1 */
11368     if (!CHIP_IS_E1(sc)) {
11369         pause->bd_th_lo = BD_TH_LO(sc);
11370         pause->bd_th_hi = BD_TH_HI(sc);
11371
11372         pause->rcq_th_lo = RCQ_TH_LO(sc);
11373         pause->rcq_th_hi = RCQ_TH_HI(sc);
11374
11375         /* validate rings have enough entries to cross high thresholds */
11376         if (sc->dropless_fc &&
11377             pause->bd_th_hi + FW_PREFETCH_CNT >
11378             sc->rx_ring_size) {
11379             BLOGW(sc, "rx bd ring threshold limit\n");
11380         }
11381
11382         if (sc->dropless_fc &&
11383             pause->rcq_th_hi + FW_PREFETCH_CNT >
11384             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11385             BLOGW(sc, "rcq ring threshold limit\n");
11386         }
11387
11388         pause->pri_map = 1;
11389     }
11390
11391     /* rxq setup */
11392     rxq_init->dscr_map   = fp->rx_dma.paddr;
11393     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11394     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11395     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11396
11397     /*
11398      * This should be a maximum number of data bytes that may be
11399      * placed on the BD (not including paddings).
11400      */
11401     rxq_init->buf_sz = (fp->rx_buf_size -
11402                         IP_HEADER_ALIGNMENT_PADDING);
11403
11404     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11405     rxq_init->tpa_agg_sz      = tpa_agg_size;
11406     rxq_init->sge_buf_sz      = sge_sz;
11407     rxq_init->max_sges_pkt    = max_sge;
11408     rxq_init->rss_engine_id   = SC_FUNC(sc);
11409     rxq_init->mcast_engine_id = SC_FUNC(sc);
11410
11411     /*
11412      * Maximum number or simultaneous TPA aggregation for this Queue.
11413      * For PF Clients it should be the maximum available number.
11414      * VF driver(s) may want to define it to a smaller value.
11415      */
11416     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11417
11418     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11419     rxq_init->fw_sb_id = fp->fw_sb_id;
11420
11421     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11422
11423     /*
11424      * configure silent vlan removal
11425      * if multi function mode is afex, then mask default vlan
11426      */
11427     if (IS_MF_AFEX(sc)) {
11428         rxq_init->silent_removal_value =
11429             sc->devinfo.mf_info.afex_def_vlan_tag;
11430         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11431     }
11432 }
11433
11434 static void
11435 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11436                  struct bxe_fastpath           *fp,
11437                  struct ecore_txq_setup_params *txq_init,
11438                  uint8_t                       cos)
11439 {
11440     /*
11441      * XXX If multiple CoS is ever supported then each fastpath structure
11442      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11443      * fp->txdata[cos]->tx_dma.paddr;
11444      */
11445     txq_init->dscr_map     = fp->tx_dma.paddr;
11446     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11447     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11448     txq_init->fw_sb_id     = fp->fw_sb_id;
11449
11450     /*
11451      * set the TSS leading client id for TX classfication to the
11452      * leading RSS client id
11453      */
11454     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11455 }
11456
11457 /*
11458  * This function performs 2 steps in a queue state machine:
11459  *   1) RESET->INIT
11460  *   2) INIT->SETUP
11461  */
11462 static int
11463 bxe_setup_queue(struct bxe_softc    *sc,
11464                 struct bxe_fastpath *fp,
11465                 uint8_t             leading)
11466 {
11467     struct ecore_queue_state_params q_params = { NULL };
11468     struct ecore_queue_setup_params *setup_params =
11469                         &q_params.params.setup;
11470     int rc;
11471
11472     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11473
11474     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11475
11476     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11477
11478     /* we want to wait for completion in this context */
11479     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11480
11481     /* prepare the INIT parameters */
11482     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11483
11484     /* Set the command */
11485     q_params.cmd = ECORE_Q_CMD_INIT;
11486
11487     /* Change the state to INIT */
11488     rc = ecore_queue_state_change(sc, &q_params);
11489     if (rc) {
11490         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11491         return (rc);
11492     }
11493
11494     BLOGD(sc, DBG_LOAD, "init complete\n");
11495
11496     /* now move the Queue to the SETUP state */
11497     memset(setup_params, 0, sizeof(*setup_params));
11498
11499     /* set Queue flags */
11500     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11501
11502     /* set general SETUP parameters */
11503     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11504                           FIRST_TX_COS_INDEX);
11505
11506     bxe_pf_rx_q_prep(sc, fp,
11507                      &setup_params->pause_params,
11508                      &setup_params->rxq_params);
11509
11510     bxe_pf_tx_q_prep(sc, fp,
11511                      &setup_params->txq_params,
11512                      FIRST_TX_COS_INDEX);
11513
11514     /* Set the command */
11515     q_params.cmd = ECORE_Q_CMD_SETUP;
11516
11517     /* change the state to SETUP */
11518     rc = ecore_queue_state_change(sc, &q_params);
11519     if (rc) {
11520         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11521         return (rc);
11522     }
11523
11524     return (rc);
11525 }
11526
11527 static int
11528 bxe_setup_leading(struct bxe_softc *sc)
11529 {
11530     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11531 }
11532
11533 static int
11534 bxe_config_rss_pf(struct bxe_softc            *sc,
11535                   struct ecore_rss_config_obj *rss_obj,
11536                   uint8_t                     config_hash)
11537 {
11538     struct ecore_config_rss_params params = { NULL };
11539     int i;
11540
11541     /*
11542      * Although RSS is meaningless when there is a single HW queue we
11543      * still need it enabled in order to have HW Rx hash generated.
11544      */
11545
11546     params.rss_obj = rss_obj;
11547
11548     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11549
11550     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11551
11552     /* RSS configuration */
11553     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11554     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11555     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11556     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11557     if (rss_obj->udp_rss_v4) {
11558         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11559     }
11560     if (rss_obj->udp_rss_v6) {
11561         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11562     }
11563
11564     /* Hash bits */
11565     params.rss_result_mask = MULTI_MASK;
11566
11567     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11568
11569     if (config_hash) {
11570         /* RSS keys */
11571         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11572             params.rss_key[i] = arc4random();
11573         }
11574
11575         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11576     }
11577
11578     return (ecore_config_rss(sc, &params));
11579 }
11580
11581 static int
11582 bxe_config_rss_eth(struct bxe_softc *sc,
11583                    uint8_t          config_hash)
11584 {
11585     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11586 }
11587
11588 static int
11589 bxe_init_rss_pf(struct bxe_softc *sc)
11590 {
11591     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11592     int i;
11593
11594     /*
11595      * Prepare the initial contents of the indirection table if
11596      * RSS is enabled
11597      */
11598     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11599         sc->rss_conf_obj.ind_table[i] =
11600             (sc->fp->cl_id + (i % num_eth_queues));
11601     }
11602
11603     if (sc->udp_rss) {
11604         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11605     }
11606
11607     /*
11608      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11609      * per-port, so if explicit configuration is needed, do it only
11610      * for a PMF.
11611      *
11612      * For 57712 and newer it's a per-function configuration.
11613      */
11614     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11615 }
11616
11617 static int
11618 bxe_set_mac_one(struct bxe_softc          *sc,
11619                 uint8_t                   *mac,
11620                 struct ecore_vlan_mac_obj *obj,
11621                 uint8_t                   set,
11622                 int                       mac_type,
11623                 unsigned long             *ramrod_flags)
11624 {
11625     struct ecore_vlan_mac_ramrod_params ramrod_param;
11626     int rc;
11627
11628     memset(&ramrod_param, 0, sizeof(ramrod_param));
11629
11630     /* fill in general parameters */
11631     ramrod_param.vlan_mac_obj = obj;
11632     ramrod_param.ramrod_flags = *ramrod_flags;
11633
11634     /* fill a user request section if needed */
11635     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11636         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11637
11638         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11639
11640         /* Set the command: ADD or DEL */
11641         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11642                                             ECORE_VLAN_MAC_DEL;
11643     }
11644
11645     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11646
11647     if (rc == ECORE_EXISTS) {
11648         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11649         /* do not treat adding same MAC as error */
11650         rc = 0;
11651     } else if (rc < 0) {
11652         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11653     }
11654
11655     return (rc);
11656 }
11657
11658 static int
11659 bxe_set_eth_mac(struct bxe_softc *sc,
11660                 uint8_t          set)
11661 {
11662     unsigned long ramrod_flags = 0;
11663
11664     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11665
11666     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11667
11668     /* Eth MAC is set on RSS leading client (fp[0]) */
11669     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11670                             &sc->sp_objs->mac_obj,
11671                             set, ECORE_ETH_MAC, &ramrod_flags));
11672 }
11673
11674 static int
11675 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11676 {
11677     uint32_t sel_phy_idx = 0;
11678
11679     if (sc->link_params.num_phys <= 1) {
11680         return (ELINK_INT_PHY);
11681     }
11682
11683     if (sc->link_vars.link_up) {
11684         sel_phy_idx = ELINK_EXT_PHY1;
11685         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11686         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11687             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11688              ELINK_SUPPORTED_FIBRE))
11689             sel_phy_idx = ELINK_EXT_PHY2;
11690     } else {
11691         switch (elink_phy_selection(&sc->link_params)) {
11692         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11693         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11694         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11695                sel_phy_idx = ELINK_EXT_PHY1;
11696                break;
11697         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11698         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11699                sel_phy_idx = ELINK_EXT_PHY2;
11700                break;
11701         }
11702     }
11703
11704     return (sel_phy_idx);
11705 }
11706
11707 static int
11708 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11709 {
11710     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11711
11712     /*
11713      * The selected activated PHY is always after swapping (in case PHY
11714      * swapping is enabled). So when swapping is enabled, we need to reverse
11715      * the configuration
11716      */
11717
11718     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11719         if (sel_phy_idx == ELINK_EXT_PHY1)
11720             sel_phy_idx = ELINK_EXT_PHY2;
11721         else if (sel_phy_idx == ELINK_EXT_PHY2)
11722             sel_phy_idx = ELINK_EXT_PHY1;
11723     }
11724
11725     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11726 }
11727
11728 static void
11729 bxe_set_requested_fc(struct bxe_softc *sc)
11730 {
11731     /*
11732      * Initialize link parameters structure variables
11733      * It is recommended to turn off RX FC for jumbo frames
11734      * for better performance
11735      */
11736     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11737         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11738     } else {
11739         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11740     }
11741 }
11742
11743 static void
11744 bxe_calc_fc_adv(struct bxe_softc *sc)
11745 {
11746     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11747     switch (sc->link_vars.ieee_fc &
11748             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11749     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11750     default:
11751         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11752                                            ADVERTISED_Pause);
11753         break;
11754
11755     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11756         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11757                                           ADVERTISED_Pause);
11758         break;
11759
11760     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11761         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11762         break;
11763     }
11764 }
11765
11766 static uint16_t
11767 bxe_get_mf_speed(struct bxe_softc *sc)
11768 {
11769     uint16_t line_speed = sc->link_vars.line_speed;
11770     if (IS_MF(sc)) {
11771         uint16_t maxCfg =
11772             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11773
11774         /* calculate the current MAX line speed limit for the MF devices */
11775         if (IS_MF_SI(sc)) {
11776             line_speed = (line_speed * maxCfg) / 100;
11777         } else { /* SD mode */
11778             uint16_t vn_max_rate = maxCfg * 100;
11779
11780             if (vn_max_rate < line_speed) {
11781                 line_speed = vn_max_rate;
11782             }
11783         }
11784     }
11785
11786     return (line_speed);
11787 }
11788
11789 static void
11790 bxe_fill_report_data(struct bxe_softc            *sc,
11791                      struct bxe_link_report_data *data)
11792 {
11793     uint16_t line_speed = bxe_get_mf_speed(sc);
11794
11795     memset(data, 0, sizeof(*data));
11796
11797     /* fill the report data with the effective line speed */
11798     data->line_speed = line_speed;
11799
11800     /* Link is down */
11801     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11802         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11803     }
11804
11805     /* Full DUPLEX */
11806     if (sc->link_vars.duplex == DUPLEX_FULL) {
11807         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11808     }
11809
11810     /* Rx Flow Control is ON */
11811     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11812         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11813     }
11814
11815     /* Tx Flow Control is ON */
11816     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11817         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11818     }
11819 }
11820
11821 /* report link status to OS, should be called under phy_lock */
11822 static void
11823 bxe_link_report_locked(struct bxe_softc *sc)
11824 {
11825     struct bxe_link_report_data cur_data;
11826
11827     /* reread mf_cfg */
11828     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11829         bxe_read_mf_cfg(sc);
11830     }
11831
11832     /* Read the current link report info */
11833     bxe_fill_report_data(sc, &cur_data);
11834
11835     /* Don't report link down or exactly the same link status twice */
11836     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11837         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11838                       &sc->last_reported_link.link_report_flags) &&
11839          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11840                       &cur_data.link_report_flags))) {
11841         return;
11842     }
11843
11844     sc->link_cnt++;
11845
11846     /* report new link params and remember the state for the next time */
11847     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11848
11849     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11850                      &cur_data.link_report_flags)) {
11851         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11852         BLOGI(sc, "NIC Link is Down\n");
11853     } else {
11854         const char *duplex;
11855         const char *flow;
11856
11857         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11858                                    &cur_data.link_report_flags)) {
11859             duplex = "full";
11860         } else {
11861             duplex = "half";
11862         }
11863
11864         /*
11865          * Handle the FC at the end so that only these flags would be
11866          * possibly set. This way we may easily check if there is no FC
11867          * enabled.
11868          */
11869         if (cur_data.link_report_flags) {
11870             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11871                              &cur_data.link_report_flags) &&
11872                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11873                              &cur_data.link_report_flags)) {
11874                 flow = "ON - receive & transmit";
11875             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11876                                     &cur_data.link_report_flags) &&
11877                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11878                                      &cur_data.link_report_flags)) {
11879                 flow = "ON - receive";
11880             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11881                                      &cur_data.link_report_flags) &&
11882                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11883                                     &cur_data.link_report_flags)) {
11884                 flow = "ON - transmit";
11885             } else {
11886                 flow = "none"; /* possible? */
11887             }
11888         } else {
11889             flow = "none";
11890         }
11891
11892         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11893         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11894               cur_data.line_speed, duplex, flow);
11895     }
11896 }
11897
11898 static void
11899 bxe_link_report(struct bxe_softc *sc)
11900 {
11901     bxe_acquire_phy_lock(sc);
11902     bxe_link_report_locked(sc);
11903     bxe_release_phy_lock(sc);
11904 }
11905
11906 static void
11907 bxe_link_status_update(struct bxe_softc *sc)
11908 {
11909     if (sc->state != BXE_STATE_OPEN) {
11910         return;
11911     }
11912
11913     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11914         elink_link_status_update(&sc->link_params, &sc->link_vars);
11915     } else {
11916         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11917                                   ELINK_SUPPORTED_10baseT_Full |
11918                                   ELINK_SUPPORTED_100baseT_Half |
11919                                   ELINK_SUPPORTED_100baseT_Full |
11920                                   ELINK_SUPPORTED_1000baseT_Full |
11921                                   ELINK_SUPPORTED_2500baseX_Full |
11922                                   ELINK_SUPPORTED_10000baseT_Full |
11923                                   ELINK_SUPPORTED_TP |
11924                                   ELINK_SUPPORTED_FIBRE |
11925                                   ELINK_SUPPORTED_Autoneg |
11926                                   ELINK_SUPPORTED_Pause |
11927                                   ELINK_SUPPORTED_Asym_Pause);
11928         sc->port.advertising[0] = sc->port.supported[0];
11929
11930         sc->link_params.sc                = sc;
11931         sc->link_params.port              = SC_PORT(sc);
11932         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11933         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11934         sc->link_params.req_line_speed[0] = SPEED_10000;
11935         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11936         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11937
11938         if (CHIP_REV_IS_FPGA(sc)) {
11939             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11940             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11941             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11942                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11943         } else {
11944             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11945             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11946             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11947                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11948         }
11949
11950         sc->link_vars.link_up = 1;
11951
11952         sc->link_vars.duplex    = DUPLEX_FULL;
11953         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11954
11955         if (IS_PF(sc)) {
11956             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11957             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11958             bxe_link_report(sc);
11959         }
11960     }
11961
11962     if (IS_PF(sc)) {
11963         if (sc->link_vars.link_up) {
11964             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11965         } else {
11966             bxe_stats_handle(sc, STATS_EVENT_STOP);
11967         }
11968         bxe_link_report(sc);
11969     } else {
11970         bxe_link_report(sc);
11971         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11972     }
11973 }
11974
11975 static int
11976 bxe_initial_phy_init(struct bxe_softc *sc,
11977                      int              load_mode)
11978 {
11979     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11980     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11981     struct elink_params *lp = &sc->link_params;
11982
11983     bxe_set_requested_fc(sc);
11984
11985     if (CHIP_REV_IS_SLOW(sc)) {
11986         uint32_t bond = CHIP_BOND_ID(sc);
11987         uint32_t feat = 0;
11988
11989         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11990             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11991         } else if (bond & 0x4) {
11992             if (CHIP_IS_E3(sc)) {
11993                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11994             } else {
11995                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11996             }
11997         } else if (bond & 0x8) {
11998             if (CHIP_IS_E3(sc)) {
11999                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
12000             } else {
12001                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12002             }
12003         }
12004
12005         /* disable EMAC for E3 and above */
12006         if (bond & 0x2) {
12007             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
12008         }
12009
12010         sc->link_params.feature_config_flags |= feat;
12011     }
12012
12013     bxe_acquire_phy_lock(sc);
12014
12015     if (load_mode == LOAD_DIAG) {
12016         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
12017         /* Prefer doing PHY loopback at 10G speed, if possible */
12018         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
12019             if (lp->speed_cap_mask[cfg_idx] &
12020                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
12021                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
12022             } else {
12023                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
12024             }
12025         }
12026     }
12027
12028     if (load_mode == LOAD_LOOPBACK_EXT) {
12029         lp->loopback_mode = ELINK_LOOPBACK_EXT;
12030     }
12031
12032     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
12033
12034     bxe_release_phy_lock(sc);
12035
12036     bxe_calc_fc_adv(sc);
12037
12038     if (sc->link_vars.link_up) {
12039         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
12040         bxe_link_report(sc);
12041     }
12042
12043     if (!CHIP_REV_IS_SLOW(sc)) {
12044         bxe_periodic_start(sc);
12045     }
12046
12047     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
12048     return (rc);
12049 }
12050
12051 /* must be called under IF_ADDR_LOCK */
12052 static int
12053 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
12054                          struct ecore_mcast_ramrod_params *p)
12055 {
12056     struct ifnet *ifp = sc->ifnet;
12057     int mc_count = 0;
12058     struct ifmultiaddr *ifma;
12059     struct ecore_mcast_list_elem *mc_mac;
12060
12061     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12062         if (ifma->ifma_addr->sa_family != AF_LINK) {
12063             continue;
12064         }
12065
12066         mc_count++;
12067     }
12068
12069     ECORE_LIST_INIT(&p->mcast_list);
12070     p->mcast_list_len = 0;
12071
12072     if (!mc_count) {
12073         return (0);
12074     }
12075
12076     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
12077                     (M_NOWAIT | M_ZERO));
12078     if (!mc_mac) {
12079         BLOGE(sc, "Failed to allocate temp mcast list\n");
12080         return (-1);
12081     }
12082     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
12083
12084     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
12085         if (ifma->ifma_addr->sa_family != AF_LINK) {
12086             continue;
12087         }
12088
12089         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
12090         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
12091
12092         BLOGD(sc, DBG_LOAD,
12093               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
12094               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
12095               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
12096
12097         mc_mac++;
12098     }
12099
12100     p->mcast_list_len = mc_count;
12101
12102     return (0);
12103 }
12104
12105 static void
12106 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12107 {
12108     struct ecore_mcast_list_elem *mc_mac =
12109         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12110                                struct ecore_mcast_list_elem,
12111                                link);
12112
12113     if (mc_mac) {
12114         /* only a single free as all mc_macs are in the same heap array */
12115         free(mc_mac, M_DEVBUF);
12116     }
12117 }
12118
12119 static int
12120 bxe_set_mc_list(struct bxe_softc *sc)
12121 {
12122     struct ecore_mcast_ramrod_params rparam = { NULL };
12123     int rc = 0;
12124
12125     rparam.mcast_obj = &sc->mcast_obj;
12126
12127     BXE_MCAST_LOCK(sc);
12128
12129     /* first, clear all configured multicast MACs */
12130     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12131     if (rc < 0) {
12132         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12133         BXE_MCAST_UNLOCK(sc);
12134         return (rc);
12135     }
12136
12137     /* configure a new MACs list */
12138     rc = bxe_init_mcast_macs_list(sc, &rparam);
12139     if (rc) {
12140         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12141         BXE_MCAST_UNLOCK(sc);
12142         return (rc);
12143     }
12144
12145     /* Now add the new MACs */
12146     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12147     if (rc < 0) {
12148         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12149     }
12150
12151     bxe_free_mcast_macs_list(&rparam);
12152
12153     BXE_MCAST_UNLOCK(sc);
12154
12155     return (rc);
12156 }
12157
12158 static int
12159 bxe_set_uc_list(struct bxe_softc *sc)
12160 {
12161     struct ifnet *ifp = sc->ifnet;
12162     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12163     struct ifaddr *ifa;
12164     unsigned long ramrod_flags = 0;
12165     int rc;
12166
12167 #if __FreeBSD_version < 800000
12168     IF_ADDR_LOCK(ifp);
12169 #else
12170     if_addr_rlock(ifp);
12171 #endif
12172
12173     /* first schedule a cleanup up of old configuration */
12174     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12175     if (rc < 0) {
12176         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12177 #if __FreeBSD_version < 800000
12178         IF_ADDR_UNLOCK(ifp);
12179 #else
12180         if_addr_runlock(ifp);
12181 #endif
12182         return (rc);
12183     }
12184
12185     ifa = ifp->if_addr;
12186     while (ifa) {
12187         if (ifa->ifa_addr->sa_family != AF_LINK) {
12188             ifa = TAILQ_NEXT(ifa, ifa_link);
12189             continue;
12190         }
12191
12192         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12193                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12194         if (rc == -EEXIST) {
12195             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12196             /* do not treat adding same MAC as an error */
12197             rc = 0;
12198         } else if (rc < 0) {
12199             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12200 #if __FreeBSD_version < 800000
12201             IF_ADDR_UNLOCK(ifp);
12202 #else
12203             if_addr_runlock(ifp);
12204 #endif
12205             return (rc);
12206         }
12207
12208         ifa = TAILQ_NEXT(ifa, ifa_link);
12209     }
12210
12211 #if __FreeBSD_version < 800000
12212     IF_ADDR_UNLOCK(ifp);
12213 #else
12214     if_addr_runlock(ifp);
12215 #endif
12216
12217     /* Execute the pending commands */
12218     bit_set(&ramrod_flags, RAMROD_CONT);
12219     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12220                             ECORE_UC_LIST_MAC, &ramrod_flags));
12221 }
12222
12223 static void
12224 bxe_set_rx_mode(struct bxe_softc *sc)
12225 {
12226     struct ifnet *ifp = sc->ifnet;
12227     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12228
12229     if (sc->state != BXE_STATE_OPEN) {
12230         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12231         return;
12232     }
12233
12234     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12235
12236     if (ifp->if_flags & IFF_PROMISC) {
12237         rx_mode = BXE_RX_MODE_PROMISC;
12238     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12239                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12240                 CHIP_IS_E1(sc))) {
12241         rx_mode = BXE_RX_MODE_ALLMULTI;
12242     } else {
12243         if (IS_PF(sc)) {
12244             /* some multicasts */
12245             if (bxe_set_mc_list(sc) < 0) {
12246                 rx_mode = BXE_RX_MODE_ALLMULTI;
12247             }
12248             if (bxe_set_uc_list(sc) < 0) {
12249                 rx_mode = BXE_RX_MODE_PROMISC;
12250             }
12251         }
12252     }
12253
12254     sc->rx_mode = rx_mode;
12255
12256     /* schedule the rx_mode command */
12257     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12258         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12259         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12260         return;
12261     }
12262
12263     if (IS_PF(sc)) {
12264         bxe_set_storm_rx_mode(sc);
12265     }
12266 }
12267
12268
12269 /* update flags in shmem */
12270 static void
12271 bxe_update_drv_flags(struct bxe_softc *sc,
12272                      uint32_t         flags,
12273                      uint32_t         set)
12274 {
12275     uint32_t drv_flags;
12276
12277     if (SHMEM2_HAS(sc, drv_flags)) {
12278         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12279         drv_flags = SHMEM2_RD(sc, drv_flags);
12280
12281         if (set) {
12282             SET_FLAGS(drv_flags, flags);
12283         } else {
12284             RESET_FLAGS(drv_flags, flags);
12285         }
12286
12287         SHMEM2_WR(sc, drv_flags, drv_flags);
12288         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12289
12290         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12291     }
12292 }
12293
12294 /* periodic timer callout routine, only runs when the interface is up */
12295
12296 static void
12297 bxe_periodic_callout_func(void *xsc)
12298 {
12299     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12300     int i;
12301
12302     if (!BXE_CORE_TRYLOCK(sc)) {
12303         /* just bail and try again next time */
12304
12305         if ((sc->state == BXE_STATE_OPEN) &&
12306             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12307             /* schedule the next periodic callout */
12308             callout_reset(&sc->periodic_callout, hz,
12309                           bxe_periodic_callout_func, sc);
12310         }
12311
12312         return;
12313     }
12314
12315     if ((sc->state != BXE_STATE_OPEN) ||
12316         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12317         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12318         BXE_CORE_UNLOCK(sc);
12319         return;
12320     }
12321
12322     /* Check for TX timeouts on any fastpath. */
12323     FOR_EACH_QUEUE(sc, i) {
12324         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12325             /* Ruh-Roh, chip was reset! */
12326             break;
12327         }
12328     }
12329
12330     if (!CHIP_REV_IS_SLOW(sc)) {
12331         /*
12332          * This barrier is needed to ensure the ordering between the writing
12333          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12334          * the reading here.
12335          */
12336         mb();
12337         if (sc->port.pmf) {
12338             bxe_acquire_phy_lock(sc);
12339             elink_period_func(&sc->link_params, &sc->link_vars);
12340             bxe_release_phy_lock(sc);
12341         }
12342     }
12343
12344     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12345         int mb_idx = SC_FW_MB_IDX(sc);
12346         uint32_t drv_pulse;
12347         uint32_t mcp_pulse;
12348
12349         ++sc->fw_drv_pulse_wr_seq;
12350         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12351
12352         drv_pulse = sc->fw_drv_pulse_wr_seq;
12353         bxe_drv_pulse(sc);
12354
12355         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12356                      MCP_PULSE_SEQ_MASK);
12357
12358         /*
12359          * The delta between driver pulse and mcp response should
12360          * be 1 (before mcp response) or 0 (after mcp response).
12361          */
12362         if ((drv_pulse != mcp_pulse) &&
12363             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12364             /* someone lost a heartbeat... */
12365             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12366                   drv_pulse, mcp_pulse);
12367         }
12368     }
12369
12370     /* state is BXE_STATE_OPEN */
12371     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12372
12373     BXE_CORE_UNLOCK(sc);
12374
12375     if ((sc->state == BXE_STATE_OPEN) &&
12376         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12377         /* schedule the next periodic callout */
12378         callout_reset(&sc->periodic_callout, hz,
12379                       bxe_periodic_callout_func, sc);
12380     }
12381 }
12382
12383 static void
12384 bxe_periodic_start(struct bxe_softc *sc)
12385 {
12386     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12387     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12388 }
12389
12390 static void
12391 bxe_periodic_stop(struct bxe_softc *sc)
12392 {
12393     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12394     callout_drain(&sc->periodic_callout);
12395 }
12396
12397 /* start the controller */
12398 static __noinline int
12399 bxe_nic_load(struct bxe_softc *sc,
12400              int              load_mode)
12401 {
12402     uint32_t val;
12403     int load_code = 0;
12404     int i, rc = 0;
12405
12406     BXE_CORE_LOCK_ASSERT(sc);
12407
12408     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12409
12410     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12411
12412     if (IS_PF(sc)) {
12413         /* must be called before memory allocation and HW init */
12414         bxe_ilt_set_info(sc);
12415     }
12416
12417     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12418
12419     bxe_set_fp_rx_buf_size(sc);
12420
12421     if (bxe_alloc_fp_buffers(sc) != 0) {
12422         BLOGE(sc, "Failed to allocate fastpath memory\n");
12423         sc->state = BXE_STATE_CLOSED;
12424         rc = ENOMEM;
12425         goto bxe_nic_load_error0;
12426     }
12427
12428     if (bxe_alloc_mem(sc) != 0) {
12429         sc->state = BXE_STATE_CLOSED;
12430         rc = ENOMEM;
12431         goto bxe_nic_load_error0;
12432     }
12433
12434     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12435         sc->state = BXE_STATE_CLOSED;
12436         rc = ENOMEM;
12437         goto bxe_nic_load_error0;
12438     }
12439
12440     if (IS_PF(sc)) {
12441         /* set pf load just before approaching the MCP */
12442         bxe_set_pf_load(sc);
12443
12444         /* if MCP exists send load request and analyze response */
12445         if (!BXE_NOMCP(sc)) {
12446             /* attempt to load pf */
12447             if (bxe_nic_load_request(sc, &load_code) != 0) {
12448                 sc->state = BXE_STATE_CLOSED;
12449                 rc = ENXIO;
12450                 goto bxe_nic_load_error1;
12451             }
12452
12453             /* what did the MCP say? */
12454             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12455                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12456                 sc->state = BXE_STATE_CLOSED;
12457                 rc = ENXIO;
12458                 goto bxe_nic_load_error2;
12459             }
12460         } else {
12461             BLOGI(sc, "Device has no MCP!\n");
12462             load_code = bxe_nic_load_no_mcp(sc);
12463         }
12464
12465         /* mark PMF if applicable */
12466         bxe_nic_load_pmf(sc, load_code);
12467
12468         /* Init Function state controlling object */
12469         bxe_init_func_obj(sc);
12470
12471         /* Initialize HW */
12472         if (bxe_init_hw(sc, load_code) != 0) {
12473             BLOGE(sc, "HW init failed\n");
12474             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12475             sc->state = BXE_STATE_CLOSED;
12476             rc = ENXIO;
12477             goto bxe_nic_load_error2;
12478         }
12479     }
12480
12481     /* set ALWAYS_ALIVE bit in shmem */
12482     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12483     bxe_drv_pulse(sc);
12484     sc->flags |= BXE_NO_PULSE;
12485
12486     /* attach interrupts */
12487     if (bxe_interrupt_attach(sc) != 0) {
12488         sc->state = BXE_STATE_CLOSED;
12489         rc = ENXIO;
12490         goto bxe_nic_load_error2;
12491     }
12492
12493     bxe_nic_init(sc, load_code);
12494
12495     /* Init per-function objects */
12496     if (IS_PF(sc)) {
12497         bxe_init_objs(sc);
12498         // XXX bxe_iov_nic_init(sc);
12499
12500         /* set AFEX default VLAN tag to an invalid value */
12501         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12502         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12503
12504         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12505         rc = bxe_func_start(sc);
12506         if (rc) {
12507             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12508             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12509             sc->state = BXE_STATE_ERROR;
12510             goto bxe_nic_load_error3;
12511         }
12512
12513         /* send LOAD_DONE command to MCP */
12514         if (!BXE_NOMCP(sc)) {
12515             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12516             if (!load_code) {
12517                 BLOGE(sc, "MCP response failure, aborting\n");
12518                 sc->state = BXE_STATE_ERROR;
12519                 rc = ENXIO;
12520                 goto bxe_nic_load_error3;
12521             }
12522         }
12523
12524         rc = bxe_setup_leading(sc);
12525         if (rc) {
12526             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12527             sc->state = BXE_STATE_ERROR;
12528             goto bxe_nic_load_error3;
12529         }
12530
12531         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12532             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12533             if (rc) {
12534                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12535                 sc->state = BXE_STATE_ERROR;
12536                 goto bxe_nic_load_error3;
12537             }
12538         }
12539
12540         rc = bxe_init_rss_pf(sc);
12541         if (rc) {
12542             BLOGE(sc, "PF RSS init failed\n");
12543             sc->state = BXE_STATE_ERROR;
12544             goto bxe_nic_load_error3;
12545         }
12546     }
12547     /* XXX VF */
12548
12549     /* now when Clients are configured we are ready to work */
12550     sc->state = BXE_STATE_OPEN;
12551
12552     /* Configure a ucast MAC */
12553     if (IS_PF(sc)) {
12554         rc = bxe_set_eth_mac(sc, TRUE);
12555     }
12556     if (rc) {
12557         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12558         sc->state = BXE_STATE_ERROR;
12559         goto bxe_nic_load_error3;
12560     }
12561
12562     if (sc->port.pmf) {
12563         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12564         if (rc) {
12565             sc->state = BXE_STATE_ERROR;
12566             goto bxe_nic_load_error3;
12567         }
12568     }
12569
12570     sc->link_params.feature_config_flags &=
12571         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12572
12573     /* start fast path */
12574
12575     /* Initialize Rx filter */
12576     bxe_set_rx_mode(sc);
12577
12578     /* start the Tx */
12579     switch (/* XXX load_mode */LOAD_OPEN) {
12580     case LOAD_NORMAL:
12581     case LOAD_OPEN:
12582         break;
12583
12584     case LOAD_DIAG:
12585     case LOAD_LOOPBACK_EXT:
12586         sc->state = BXE_STATE_DIAG;
12587         break;
12588
12589     default:
12590         break;
12591     }
12592
12593     if (sc->port.pmf) {
12594         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12595     } else {
12596         bxe_link_status_update(sc);
12597     }
12598
12599     /* start the periodic timer callout */
12600     bxe_periodic_start(sc);
12601
12602     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12603         /* mark driver is loaded in shmem2 */
12604         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12605         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12606                   (val |
12607                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12608                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12609     }
12610
12611     /* wait for all pending SP commands to complete */
12612     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12613         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12614         bxe_periodic_stop(sc);
12615         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12616         return (ENXIO);
12617     }
12618
12619     /* Tell the stack the driver is running! */
12620     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12621
12622     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12623
12624     return (0);
12625
12626 bxe_nic_load_error3:
12627
12628     if (IS_PF(sc)) {
12629         bxe_int_disable_sync(sc, 1);
12630
12631         /* clean out queued objects */
12632         bxe_squeeze_objects(sc);
12633     }
12634
12635     bxe_interrupt_detach(sc);
12636
12637 bxe_nic_load_error2:
12638
12639     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12640         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12641         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12642     }
12643
12644     sc->port.pmf = 0;
12645
12646 bxe_nic_load_error1:
12647
12648     /* clear pf_load status, as it was already set */
12649     if (IS_PF(sc)) {
12650         bxe_clear_pf_load(sc);
12651     }
12652
12653 bxe_nic_load_error0:
12654
12655     bxe_free_fw_stats_mem(sc);
12656     bxe_free_fp_buffers(sc);
12657     bxe_free_mem(sc);
12658
12659     return (rc);
12660 }
12661
12662 static int
12663 bxe_init_locked(struct bxe_softc *sc)
12664 {
12665     int other_engine = SC_PATH(sc) ? 0 : 1;
12666     uint8_t other_load_status, load_status;
12667     uint8_t global = FALSE;
12668     int rc;
12669
12670     BXE_CORE_LOCK_ASSERT(sc);
12671
12672     /* check if the driver is already running */
12673     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12674         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12675         return (0);
12676     }
12677
12678     bxe_set_power_state(sc, PCI_PM_D0);
12679
12680     /*
12681      * If parity occurred during the unload, then attentions and/or
12682      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12683      * loaded on the current engine to complete the recovery. Parity recovery
12684      * is only relevant for PF driver.
12685      */
12686     if (IS_PF(sc)) {
12687         other_load_status = bxe_get_load_status(sc, other_engine);
12688         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12689
12690         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12691             bxe_chk_parity_attn(sc, &global, TRUE)) {
12692             do {
12693                 /*
12694                  * If there are attentions and they are in global blocks, set
12695                  * the GLOBAL_RESET bit regardless whether it will be this
12696                  * function that will complete the recovery or not.
12697                  */
12698                 if (global) {
12699                     bxe_set_reset_global(sc);
12700                 }
12701
12702                 /*
12703                  * Only the first function on the current engine should try
12704                  * to recover in open. In case of attentions in global blocks
12705                  * only the first in the chip should try to recover.
12706                  */
12707                 if ((!load_status && (!global || !other_load_status)) &&
12708                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12709                     BLOGI(sc, "Recovered during init\n");
12710                     break;
12711                 }
12712
12713                 /* recovery has failed... */
12714                 bxe_set_power_state(sc, PCI_PM_D3hot);
12715                 sc->recovery_state = BXE_RECOVERY_FAILED;
12716
12717                 BLOGE(sc, "Recovery flow hasn't properly "
12718                           "completed yet, try again later. "
12719                           "If you still see this message after a "
12720                           "few retries then power cycle is required.\n");
12721
12722                 rc = ENXIO;
12723                 goto bxe_init_locked_done;
12724             } while (0);
12725         }
12726     }
12727
12728     sc->recovery_state = BXE_RECOVERY_DONE;
12729
12730     rc = bxe_nic_load(sc, LOAD_OPEN);
12731
12732 bxe_init_locked_done:
12733
12734     if (rc) {
12735         /* Tell the stack the driver is NOT running! */
12736         BLOGE(sc, "Initialization failed, "
12737                   "stack notified driver is NOT running!\n");
12738         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12739     }
12740
12741     return (rc);
12742 }
12743
12744 static int
12745 bxe_stop_locked(struct bxe_softc *sc)
12746 {
12747     BXE_CORE_LOCK_ASSERT(sc);
12748     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12749 }
12750
12751 /*
12752  * Handles controller initialization when called from an unlocked routine.
12753  * ifconfig calls this function.
12754  *
12755  * Returns:
12756  *   void
12757  */
12758 static void
12759 bxe_init(void *xsc)
12760 {
12761     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12762
12763     BXE_CORE_LOCK(sc);
12764     bxe_init_locked(sc);
12765     BXE_CORE_UNLOCK(sc);
12766 }
12767
12768 static int
12769 bxe_init_ifnet(struct bxe_softc *sc)
12770 {
12771     struct ifnet *ifp;
12772
12773     /* ifconfig entrypoint for media type/status reporting */
12774     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12775                  bxe_ifmedia_update,
12776                  bxe_ifmedia_status);
12777
12778     /* set the default interface values */
12779     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12780     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12781     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12782
12783     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12784
12785     /* allocate the ifnet structure */
12786     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12787         BLOGE(sc, "Interface allocation failed!\n");
12788         return (ENXIO);
12789     }
12790
12791     ifp->if_softc = sc;
12792     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12793     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12794     ifp->if_ioctl = bxe_ioctl;
12795     ifp->if_start = bxe_tx_start;
12796 #if __FreeBSD_version >= 800000
12797     ifp->if_transmit = bxe_tx_mq_start;
12798     ifp->if_qflush = bxe_mq_flush;
12799 #endif
12800 #ifdef FreeBSD8_0
12801     ifp->if_timer = 0;
12802 #endif
12803     ifp->if_init = bxe_init;
12804     ifp->if_mtu = sc->mtu;
12805     ifp->if_hwassist = (CSUM_IP       |
12806                         CSUM_TCP      |
12807                         CSUM_UDP      |
12808                         CSUM_TSO      |
12809                         CSUM_TCP_IPV6 |
12810                         CSUM_UDP_IPV6);
12811     ifp->if_capabilities =
12812 #if __FreeBSD_version < 700000
12813         (IFCAP_VLAN_MTU       |
12814          IFCAP_VLAN_HWTAGGING |
12815          IFCAP_HWCSUM         |
12816          IFCAP_JUMBO_MTU      |
12817          IFCAP_LRO);
12818 #else
12819         (IFCAP_VLAN_MTU       |
12820          IFCAP_VLAN_HWTAGGING |
12821          IFCAP_VLAN_HWTSO     |
12822          IFCAP_VLAN_HWFILTER  |
12823          IFCAP_VLAN_HWCSUM    |
12824          IFCAP_HWCSUM         |
12825          IFCAP_JUMBO_MTU      |
12826          IFCAP_LRO            |
12827          IFCAP_TSO4           |
12828          IFCAP_TSO6           |
12829          IFCAP_WOL_MAGIC);
12830 #endif
12831     ifp->if_capenable = ifp->if_capabilities;
12832     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12833 #if __FreeBSD_version < 1000025
12834     ifp->if_baudrate = 1000000000;
12835 #else
12836     if_initbaudrate(ifp, IF_Gbps(10));
12837 #endif
12838     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12839
12840     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12841     IFQ_SET_READY(&ifp->if_snd);
12842
12843     sc->ifnet = ifp;
12844
12845     /* attach to the Ethernet interface list */
12846     ether_ifattach(ifp, sc->link_params.mac_addr);
12847
12848     return (0);
12849 }
12850
12851 static void
12852 bxe_deallocate_bars(struct bxe_softc *sc)
12853 {
12854     int i;
12855
12856     for (i = 0; i < MAX_BARS; i++) {
12857         if (sc->bar[i].resource != NULL) {
12858             bus_release_resource(sc->dev,
12859                                  SYS_RES_MEMORY,
12860                                  sc->bar[i].rid,
12861                                  sc->bar[i].resource);
12862             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12863                   i, PCIR_BAR(i));
12864         }
12865     }
12866 }
12867
12868 static int
12869 bxe_allocate_bars(struct bxe_softc *sc)
12870 {
12871     u_int flags;
12872     int i;
12873
12874     memset(sc->bar, 0, sizeof(sc->bar));
12875
12876     for (i = 0; i < MAX_BARS; i++) {
12877
12878         /* memory resources reside at BARs 0, 2, 4 */
12879         /* Run `pciconf -lb` to see mappings */
12880         if ((i != 0) && (i != 2) && (i != 4)) {
12881             continue;
12882         }
12883
12884         sc->bar[i].rid = PCIR_BAR(i);
12885
12886         flags = RF_ACTIVE;
12887         if (i == 0) {
12888             flags |= RF_SHAREABLE;
12889         }
12890
12891         if ((sc->bar[i].resource =
12892              bus_alloc_resource_any(sc->dev,
12893                                     SYS_RES_MEMORY,
12894                                     &sc->bar[i].rid,
12895                                     flags)) == NULL) {
12896             return (0);
12897         }
12898
12899         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12900         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12901         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12902
12903         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12904               i, PCIR_BAR(i),
12905               (void *)rman_get_start(sc->bar[i].resource),
12906               (void *)rman_get_end(sc->bar[i].resource),
12907               rman_get_size(sc->bar[i].resource),
12908               (void *)sc->bar[i].kva);
12909     }
12910
12911     return (0);
12912 }
12913
12914 static void
12915 bxe_get_function_num(struct bxe_softc *sc)
12916 {
12917     uint32_t val = 0;
12918
12919     /*
12920      * Read the ME register to get the function number. The ME register
12921      * holds the relative-function number and absolute-function number. The
12922      * absolute-function number appears only in E2 and above. Before that
12923      * these bits always contained zero, therefore we cannot blindly use them.
12924      */
12925
12926     val = REG_RD(sc, BAR_ME_REGISTER);
12927
12928     sc->pfunc_rel =
12929         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12930     sc->path_id =
12931         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12932
12933     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12934         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12935     } else {
12936         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12937     }
12938
12939     BLOGD(sc, DBG_LOAD,
12940           "Relative function %d, Absolute function %d, Path %d\n",
12941           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12942 }
12943
12944 static uint32_t
12945 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12946 {
12947     uint32_t shmem2_size;
12948     uint32_t offset;
12949     uint32_t mf_cfg_offset_value;
12950
12951     /* Non 57712 */
12952     offset = (SHMEM_RD(sc, func_mb) +
12953               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12954
12955     /* 57712 plus */
12956     if (sc->devinfo.shmem2_base != 0) {
12957         shmem2_size = SHMEM2_RD(sc, size);
12958         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12959             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12960             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12961                 offset = mf_cfg_offset_value;
12962             }
12963         }
12964     }
12965
12966     return (offset);
12967 }
12968
12969 static uint32_t
12970 bxe_pcie_capability_read(struct bxe_softc *sc,
12971                          int    reg,
12972                          int    width)
12973 {
12974     int pcie_reg;
12975
12976     /* ensure PCIe capability is enabled */
12977     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12978         if (pcie_reg != 0) {
12979             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12980             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12981         }
12982     }
12983
12984     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12985
12986     return (0);
12987 }
12988
12989 static uint8_t
12990 bxe_is_pcie_pending(struct bxe_softc *sc)
12991 {
12992     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12993             PCIM_EXP_STA_TRANSACTION_PND);
12994 }
12995
12996 /*
12997  * Walk the PCI capabiites list for the device to find what features are
12998  * supported. These capabilites may be enabled/disabled by firmware so it's
12999  * best to walk the list rather than make assumptions.
13000  */
13001 static void
13002 bxe_probe_pci_caps(struct bxe_softc *sc)
13003 {
13004     uint16_t link_status;
13005     int reg;
13006
13007     /* check if PCI Power Management is enabled */
13008     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
13009         if (reg != 0) {
13010             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
13011
13012             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
13013             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
13014         }
13015     }
13016
13017     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
13018
13019     /* handle PCIe 2.0 workarounds for 57710 */
13020     if (CHIP_IS_E1(sc)) {
13021         /* workaround for 57710 errata E4_57710_27462 */
13022         sc->devinfo.pcie_link_speed =
13023             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
13024
13025         /* workaround for 57710 errata E4_57710_27488 */
13026         sc->devinfo.pcie_link_width =
13027             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13028         if (sc->devinfo.pcie_link_speed > 1) {
13029             sc->devinfo.pcie_link_width =
13030                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
13031         }
13032     } else {
13033         sc->devinfo.pcie_link_speed =
13034             (link_status & PCIM_LINK_STA_SPEED);
13035         sc->devinfo.pcie_link_width =
13036             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
13037     }
13038
13039     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
13040           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
13041
13042     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
13043     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
13044
13045     /* check if MSI capability is enabled */
13046     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
13047         if (reg != 0) {
13048             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
13049
13050             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
13051             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
13052         }
13053     }
13054
13055     /* check if MSI-X capability is enabled */
13056     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
13057         if (reg != 0) {
13058             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
13059
13060             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
13061             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
13062         }
13063     }
13064 }
13065
13066 static int
13067 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
13068 {
13069     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13070     uint32_t val;
13071
13072     /* get the outer vlan if we're in switch-dependent mode */
13073
13074     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13075     mf_info->ext_id = (uint16_t)val;
13076
13077     mf_info->multi_vnics_mode = 1;
13078
13079     if (!VALID_OVLAN(mf_info->ext_id)) {
13080         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
13081         return (1);
13082     }
13083
13084     /* get the capabilities */
13085     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13086         FUNC_MF_CFG_PROTOCOL_ISCSI) {
13087         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
13088     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
13089                FUNC_MF_CFG_PROTOCOL_FCOE) {
13090         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
13091     } else {
13092         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
13093     }
13094
13095     mf_info->vnics_per_port =
13096         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13097
13098     return (0);
13099 }
13100
13101 static uint32_t
13102 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13103 {
13104     uint32_t retval = 0;
13105     uint32_t val;
13106
13107     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13108
13109     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13110         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13111             retval |= MF_PROTO_SUPPORT_ETHERNET;
13112         }
13113         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13114             retval |= MF_PROTO_SUPPORT_ISCSI;
13115         }
13116         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13117             retval |= MF_PROTO_SUPPORT_FCOE;
13118         }
13119     }
13120
13121     return (retval);
13122 }
13123
13124 static int
13125 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13126 {
13127     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13128     uint32_t val;
13129
13130     /*
13131      * There is no outer vlan if we're in switch-independent mode.
13132      * If the mac is valid then assume multi-function.
13133      */
13134
13135     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13136
13137     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13138
13139     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13140
13141     mf_info->vnics_per_port =
13142         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13143
13144     return (0);
13145 }
13146
13147 static int
13148 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13149 {
13150     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13151     uint32_t e1hov_tag;
13152     uint32_t func_config;
13153     uint32_t niv_config;
13154
13155     mf_info->multi_vnics_mode = 1;
13156
13157     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13158     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13159     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13160
13161     mf_info->ext_id =
13162         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13163                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13164
13165     mf_info->default_vlan =
13166         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13167                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13168
13169     mf_info->niv_allowed_priorities =
13170         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13171                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13172
13173     mf_info->niv_default_cos =
13174         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13175                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13176
13177     mf_info->afex_vlan_mode =
13178         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13179          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13180
13181     mf_info->niv_mba_enabled =
13182         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13183          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13184
13185     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13186
13187     mf_info->vnics_per_port =
13188         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13189
13190     return (0);
13191 }
13192
13193 static int
13194 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13195 {
13196     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13197     uint32_t mf_cfg1;
13198     uint32_t mf_cfg2;
13199     uint32_t ovlan1;
13200     uint32_t ovlan2;
13201     uint8_t i, j;
13202
13203     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13204           SC_PORT(sc));
13205     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13206           mf_info->mf_config[SC_VN(sc)]);
13207     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13208           mf_info->multi_vnics_mode);
13209     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13210           mf_info->vnics_per_port);
13211     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13212           mf_info->ext_id);
13213     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13214           mf_info->min_bw[0], mf_info->min_bw[1],
13215           mf_info->min_bw[2], mf_info->min_bw[3]);
13216     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13217           mf_info->max_bw[0], mf_info->max_bw[1],
13218           mf_info->max_bw[2], mf_info->max_bw[3]);
13219     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13220           sc->mac_addr_str);
13221
13222     /* various MF mode sanity checks... */
13223
13224     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13225         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13226               SC_PORT(sc));
13227         return (1);
13228     }
13229
13230     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13231         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13232               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13233         return (1);
13234     }
13235
13236     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13237         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13238         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13239             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13240                   SC_VN(sc), OVLAN(sc));
13241             return (1);
13242         }
13243
13244         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13245             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13246                   mf_info->multi_vnics_mode, OVLAN(sc));
13247             return (1);
13248         }
13249
13250         /*
13251          * Verify all functions are either MF or SF mode. If MF, make sure
13252          * sure that all non-hidden functions have a valid ovlan. If SF,
13253          * make sure that all non-hidden functions have an invalid ovlan.
13254          */
13255         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13256             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13257             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13258             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13259                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13260                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13261                 BLOGE(sc, "mf_mode=SD function %d MF config "
13262                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13263                       i, mf_info->multi_vnics_mode, ovlan1);
13264                 return (1);
13265             }
13266         }
13267
13268         /* Verify all funcs on the same port each have a different ovlan. */
13269         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13270             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13271             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13272             /* iterate from the next function on the port to the max func */
13273             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13274                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13275                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13276                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13277                     VALID_OVLAN(ovlan1) &&
13278                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13279                     VALID_OVLAN(ovlan2) &&
13280                     (ovlan1 == ovlan2)) {
13281                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13282                               "have the same ovlan (%d)\n",
13283                           i, j, ovlan1);
13284                     return (1);
13285                 }
13286             }
13287         }
13288     } /* MULTI_FUNCTION_SD */
13289
13290     return (0);
13291 }
13292
13293 static int
13294 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13295 {
13296     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13297     uint32_t val, mac_upper;
13298     uint8_t i, vnic;
13299
13300     /* initialize mf_info defaults */
13301     mf_info->vnics_per_port   = 1;
13302     mf_info->multi_vnics_mode = FALSE;
13303     mf_info->path_has_ovlan   = FALSE;
13304     mf_info->mf_mode          = SINGLE_FUNCTION;
13305
13306     if (!CHIP_IS_MF_CAP(sc)) {
13307         return (0);
13308     }
13309
13310     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13311         BLOGE(sc, "Invalid mf_cfg_base!\n");
13312         return (1);
13313     }
13314
13315     /* get the MF mode (switch dependent / independent / single-function) */
13316
13317     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13318
13319     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13320     {
13321     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13322
13323         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13324
13325         /* check for legal upper mac bytes */
13326         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13327             mf_info->mf_mode = MULTI_FUNCTION_SI;
13328         } else {
13329             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13330         }
13331
13332         break;
13333
13334     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13335     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13336
13337         /* get outer vlan configuration */
13338         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13339
13340         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13341             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13342             mf_info->mf_mode = MULTI_FUNCTION_SD;
13343         } else {
13344             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13345         }
13346
13347         break;
13348
13349     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13350
13351         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13352         return (0);
13353
13354     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13355
13356         /*
13357          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13358          * and the MAC address is valid.
13359          */
13360         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13361
13362         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13363             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13364             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13365         } else {
13366             BLOGE(sc, "Invalid config for AFEX mode\n");
13367         }
13368
13369         break;
13370
13371     default:
13372
13373         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13374               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13375
13376         return (1);
13377     }
13378
13379     /* set path mf_mode (which could be different than function mf_mode) */
13380     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13381         mf_info->path_has_ovlan = TRUE;
13382     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13383         /*
13384          * Decide on path multi vnics mode. If we're not in MF mode and in
13385          * 4-port mode, this is good enough to check vnic-0 of the other port
13386          * on the same path
13387          */
13388         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13389             uint8_t other_port = !(PORT_ID(sc) & 1);
13390             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13391
13392             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13393
13394             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13395         }
13396     }
13397
13398     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13399         /* invalid MF config */
13400         if (SC_VN(sc) >= 1) {
13401             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13402             return (1);
13403         }
13404
13405         return (0);
13406     }
13407
13408     /* get the MF configuration */
13409     mf_info->mf_config[SC_VN(sc)] =
13410         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13411
13412     switch(mf_info->mf_mode)
13413     {
13414     case MULTI_FUNCTION_SD:
13415
13416         bxe_get_shmem_mf_cfg_info_sd(sc);
13417         break;
13418
13419     case MULTI_FUNCTION_SI:
13420
13421         bxe_get_shmem_mf_cfg_info_si(sc);
13422         break;
13423
13424     case MULTI_FUNCTION_AFEX:
13425
13426         bxe_get_shmem_mf_cfg_info_niv(sc);
13427         break;
13428
13429     default:
13430
13431         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13432               mf_info->mf_mode);
13433         return (1);
13434     }
13435
13436     /* get the congestion management parameters */
13437
13438     vnic = 0;
13439     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13440         /* get min/max bw */
13441         val = MFCFG_RD(sc, func_mf_config[i].config);
13442         mf_info->min_bw[vnic] =
13443             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13444         mf_info->max_bw[vnic] =
13445             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13446         vnic++;
13447     }
13448
13449     return (bxe_check_valid_mf_cfg(sc));
13450 }
13451
13452 static int
13453 bxe_get_shmem_info(struct bxe_softc *sc)
13454 {
13455     int port;
13456     uint32_t mac_hi, mac_lo, val;
13457
13458     port = SC_PORT(sc);
13459     mac_hi = mac_lo = 0;
13460
13461     sc->link_params.sc   = sc;
13462     sc->link_params.port = port;
13463
13464     /* get the hardware config info */
13465     sc->devinfo.hw_config =
13466         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13467     sc->devinfo.hw_config2 =
13468         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13469
13470     sc->link_params.hw_led_mode =
13471         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13472          SHARED_HW_CFG_LED_MODE_SHIFT);
13473
13474     /* get the port feature config */
13475     sc->port.config =
13476         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13477
13478     /* get the link params */
13479     sc->link_params.speed_cap_mask[0] =
13480         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13481     sc->link_params.speed_cap_mask[1] =
13482         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13483
13484     /* get the lane config */
13485     sc->link_params.lane_config =
13486         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13487
13488     /* get the link config */
13489     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13490     sc->port.link_config[ELINK_INT_PHY] = val;
13491     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13492     sc->port.link_config[ELINK_EXT_PHY1] =
13493         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13494
13495     /* get the override preemphasis flag and enable it or turn it off */
13496     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13497     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13498         sc->link_params.feature_config_flags |=
13499             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13500     } else {
13501         sc->link_params.feature_config_flags &=
13502             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13503     }
13504
13505     /* get the initial value of the link params */
13506     sc->link_params.multi_phy_config =
13507         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13508
13509     /* get external phy info */
13510     sc->port.ext_phy_config =
13511         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13512
13513     /* get the multifunction configuration */
13514     bxe_get_mf_cfg_info(sc);
13515
13516     /* get the mac address */
13517     if (IS_MF(sc)) {
13518         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13519         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13520     } else {
13521         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13522         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13523     }
13524
13525     if ((mac_lo == 0) && (mac_hi == 0)) {
13526         *sc->mac_addr_str = 0;
13527         BLOGE(sc, "No Ethernet address programmed!\n");
13528     } else {
13529         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13530         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13531         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13532         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13533         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13534         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13535         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13536                  "%02x:%02x:%02x:%02x:%02x:%02x",
13537                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13538                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13539                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13540         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13541     }
13542
13543     return (0);
13544 }
13545
13546 static void
13547 bxe_get_tunable_params(struct bxe_softc *sc)
13548 {
13549     /* sanity checks */
13550
13551     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13552         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13553         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13554         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13555         bxe_interrupt_mode = INTR_MODE_MSIX;
13556     }
13557
13558     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13559         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13560         bxe_queue_count = 0;
13561     }
13562
13563     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13564         if (bxe_max_rx_bufs == 0) {
13565             bxe_max_rx_bufs = RX_BD_USABLE;
13566         } else {
13567             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13568             bxe_max_rx_bufs = 2048;
13569         }
13570     }
13571
13572     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13573         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13574         bxe_hc_rx_ticks = 25;
13575     }
13576
13577     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13578         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13579         bxe_hc_tx_ticks = 50;
13580     }
13581
13582     if (bxe_max_aggregation_size == 0) {
13583         bxe_max_aggregation_size = TPA_AGG_SIZE;
13584     }
13585
13586     if (bxe_max_aggregation_size > 0xffff) {
13587         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13588               bxe_max_aggregation_size);
13589         bxe_max_aggregation_size = TPA_AGG_SIZE;
13590     }
13591
13592     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13593         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13594         bxe_mrrs = -1;
13595     }
13596
13597     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13598         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13599         bxe_autogreeen = 0;
13600     }
13601
13602     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13603         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13604         bxe_udp_rss = 0;
13605     }
13606
13607     /* pull in user settings */
13608
13609     sc->interrupt_mode       = bxe_interrupt_mode;
13610     sc->max_rx_bufs          = bxe_max_rx_bufs;
13611     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13612     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13613     sc->max_aggregation_size = bxe_max_aggregation_size;
13614     sc->mrrs                 = bxe_mrrs;
13615     sc->autogreeen           = bxe_autogreeen;
13616     sc->udp_rss              = bxe_udp_rss;
13617
13618     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13619         sc->num_queues = 1;
13620     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13621         sc->num_queues =
13622             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13623                 MAX_RSS_CHAINS);
13624         if (sc->num_queues > mp_ncpus) {
13625             sc->num_queues = mp_ncpus;
13626         }
13627     }
13628
13629     BLOGD(sc, DBG_LOAD,
13630           "User Config: "
13631           "debug=0x%lx "
13632           "interrupt_mode=%d "
13633           "queue_count=%d "
13634           "hc_rx_ticks=%d "
13635           "hc_tx_ticks=%d "
13636           "rx_budget=%d "
13637           "max_aggregation_size=%d "
13638           "mrrs=%d "
13639           "autogreeen=%d "
13640           "udp_rss=%d\n",
13641           bxe_debug,
13642           sc->interrupt_mode,
13643           sc->num_queues,
13644           sc->hc_rx_ticks,
13645           sc->hc_tx_ticks,
13646           bxe_rx_budget,
13647           sc->max_aggregation_size,
13648           sc->mrrs,
13649           sc->autogreeen,
13650           sc->udp_rss);
13651 }
13652
13653 static void
13654 bxe_media_detect(struct bxe_softc *sc)
13655 {
13656     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13657     switch (sc->link_params.phy[phy_idx].media_type) {
13658     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13659     case ELINK_ETH_PHY_XFP_FIBER:
13660         BLOGI(sc, "Found 10Gb Fiber media.\n");
13661         sc->media = IFM_10G_SR;
13662         break;
13663     case ELINK_ETH_PHY_SFP_1G_FIBER:
13664         BLOGI(sc, "Found 1Gb Fiber media.\n");
13665         sc->media = IFM_1000_SX;
13666         break;
13667     case ELINK_ETH_PHY_KR:
13668     case ELINK_ETH_PHY_CX4:
13669         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13670         sc->media = IFM_10G_CX4;
13671         break;
13672     case ELINK_ETH_PHY_DA_TWINAX:
13673         BLOGI(sc, "Found 10Gb Twinax media.\n");
13674         sc->media = IFM_10G_TWINAX;
13675         break;
13676     case ELINK_ETH_PHY_BASE_T:
13677         if (sc->link_params.speed_cap_mask[0] &
13678             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13679             BLOGI(sc, "Found 10GBase-T media.\n");
13680             sc->media = IFM_10G_T;
13681         } else {
13682             BLOGI(sc, "Found 1000Base-T media.\n");
13683             sc->media = IFM_1000_T;
13684         }
13685         break;
13686     case ELINK_ETH_PHY_NOT_PRESENT:
13687         BLOGI(sc, "Media not present.\n");
13688         sc->media = 0;
13689         break;
13690     case ELINK_ETH_PHY_UNSPECIFIED:
13691     default:
13692         BLOGI(sc, "Unknown media!\n");
13693         sc->media = 0;
13694         break;
13695     }
13696 }
13697
13698 #define GET_FIELD(value, fname)                     \
13699     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13700 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13701 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13702
13703 static int
13704 bxe_get_igu_cam_info(struct bxe_softc *sc)
13705 {
13706     int pfid = SC_FUNC(sc);
13707     int igu_sb_id;
13708     uint32_t val;
13709     uint8_t fid, igu_sb_cnt = 0;
13710
13711     sc->igu_base_sb = 0xff;
13712
13713     if (CHIP_INT_MODE_IS_BC(sc)) {
13714         int vn = SC_VN(sc);
13715         igu_sb_cnt = sc->igu_sb_cnt;
13716         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13717                            FP_SB_MAX_E1x);
13718         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13719                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13720         return (0);
13721     }
13722
13723     /* IGU in normal mode - read CAM */
13724     for (igu_sb_id = 0;
13725          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13726          igu_sb_id++) {
13727         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13728         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13729             continue;
13730         }
13731         fid = IGU_FID(val);
13732         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13733             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13734                 continue;
13735             }
13736             if (IGU_VEC(val) == 0) {
13737                 /* default status block */
13738                 sc->igu_dsb_id = igu_sb_id;
13739             } else {
13740                 if (sc->igu_base_sb == 0xff) {
13741                     sc->igu_base_sb = igu_sb_id;
13742                 }
13743                 igu_sb_cnt++;
13744             }
13745         }
13746     }
13747
13748     /*
13749      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13750      * that number of CAM entries will not be equal to the value advertised in
13751      * PCI. Driver should use the minimal value of both as the actual status
13752      * block count
13753      */
13754     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13755
13756     if (igu_sb_cnt == 0) {
13757         BLOGE(sc, "CAM configuration error\n");
13758         return (-1);
13759     }
13760
13761     return (0);
13762 }
13763
13764 /*
13765  * Gather various information from the device config space, the device itself,
13766  * shmem, and the user input.
13767  */
13768 static int
13769 bxe_get_device_info(struct bxe_softc *sc)
13770 {
13771     uint32_t val;
13772     int rc;
13773
13774     /* Get the data for the device */
13775     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13776     sc->devinfo.device_id    = pci_get_device(sc->dev);
13777     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13778     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13779
13780     /* get the chip revision (chip metal comes from pci config space) */
13781     sc->devinfo.chip_id     =
13782     sc->link_params.chip_id =
13783         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13784          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13785          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13786          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13787
13788     /* force 57811 according to MISC register */
13789     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13790         if (CHIP_IS_57810(sc)) {
13791             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13792                                    (sc->devinfo.chip_id & 0x0000ffff));
13793         } else if (CHIP_IS_57810_MF(sc)) {
13794             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13795                                    (sc->devinfo.chip_id & 0x0000ffff));
13796         }
13797         sc->devinfo.chip_id |= 0x1;
13798     }
13799
13800     BLOGD(sc, DBG_LOAD,
13801           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13802           sc->devinfo.chip_id,
13803           ((sc->devinfo.chip_id >> 16) & 0xffff),
13804           ((sc->devinfo.chip_id >> 12) & 0xf),
13805           ((sc->devinfo.chip_id >>  4) & 0xff),
13806           ((sc->devinfo.chip_id >>  0) & 0xf));
13807
13808     val = (REG_RD(sc, 0x2874) & 0x55);
13809     if ((sc->devinfo.chip_id & 0x1) ||
13810         (CHIP_IS_E1(sc) && val) ||
13811         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13812         sc->flags |= BXE_ONE_PORT_FLAG;
13813         BLOGD(sc, DBG_LOAD, "single port device\n");
13814     }
13815
13816     /* set the doorbell size */
13817     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13818
13819     /* determine whether the device is in 2 port or 4 port mode */
13820     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13821     if (CHIP_IS_E2E3(sc)) {
13822         /*
13823          * Read port4mode_en_ovwr[0]:
13824          *   If 1, four port mode is in port4mode_en_ovwr[1].
13825          *   If 0, four port mode is in port4mode_en[0].
13826          */
13827         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13828         if (val & 1) {
13829             val = ((val >> 1) & 1);
13830         } else {
13831             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13832         }
13833
13834         sc->devinfo.chip_port_mode =
13835             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13836
13837         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13838     }
13839
13840     /* get the function and path info for the device */
13841     bxe_get_function_num(sc);
13842
13843     /* get the shared memory base address */
13844     sc->devinfo.shmem_base     =
13845     sc->link_params.shmem_base =
13846         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13847     sc->devinfo.shmem2_base =
13848         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13849                                   MISC_REG_GENERIC_CR_0));
13850
13851     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13852           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13853
13854     if (!sc->devinfo.shmem_base) {
13855         /* this should ONLY prevent upcoming shmem reads */
13856         BLOGI(sc, "MCP not active\n");
13857         sc->flags |= BXE_NO_MCP_FLAG;
13858         return (0);
13859     }
13860
13861     /* make sure the shared memory contents are valid */
13862     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13863     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13864         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13865         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13866         return (0);
13867     }
13868     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13869
13870     /* get the bootcode version */
13871     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13872     snprintf(sc->devinfo.bc_ver_str,
13873              sizeof(sc->devinfo.bc_ver_str),
13874              "%d.%d.%d",
13875              ((sc->devinfo.bc_ver >> 24) & 0xff),
13876              ((sc->devinfo.bc_ver >> 16) & 0xff),
13877              ((sc->devinfo.bc_ver >>  8) & 0xff));
13878     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13879
13880     /* get the bootcode shmem address */
13881     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13882     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13883
13884     /* clean indirect addresses as they're not used */
13885     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13886     if (IS_PF(sc)) {
13887         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13888         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13889         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13890         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13891         if (CHIP_IS_E1x(sc)) {
13892             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13893             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13894             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13895             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13896         }
13897
13898         /*
13899          * Enable internal target-read (in case we are probed after PF
13900          * FLR). Must be done prior to any BAR read access. Only for
13901          * 57712 and up
13902          */
13903         if (!CHIP_IS_E1x(sc)) {
13904             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13905         }
13906     }
13907
13908     /* get the nvram size */
13909     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13910     sc->devinfo.flash_size =
13911         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13912     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13913
13914     /* get PCI capabilites */
13915     bxe_probe_pci_caps(sc);
13916
13917     bxe_set_power_state(sc, PCI_PM_D0);
13918
13919     /* get various configuration parameters from shmem */
13920     bxe_get_shmem_info(sc);
13921
13922     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13923         val = pci_read_config(sc->dev,
13924                               (sc->devinfo.pcie_msix_cap_reg +
13925                                PCIR_MSIX_CTRL),
13926                               2);
13927         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13928     } else {
13929         sc->igu_sb_cnt = 1;
13930     }
13931
13932     sc->igu_base_addr = BAR_IGU_INTMEM;
13933
13934     /* initialize IGU parameters */
13935     if (CHIP_IS_E1x(sc)) {
13936         sc->devinfo.int_block = INT_BLOCK_HC;
13937         sc->igu_dsb_id = DEF_SB_IGU_ID;
13938         sc->igu_base_sb = 0;
13939     } else {
13940         sc->devinfo.int_block = INT_BLOCK_IGU;
13941
13942         /* do not allow device reset during IGU info preocessing */
13943         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13944
13945         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13946
13947         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13948             int tout = 5000;
13949
13950             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13951
13952             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13953             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13954             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13955
13956             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13957                 tout--;
13958                 DELAY(1000);
13959             }
13960
13961             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13962                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13963                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13964                 return (-1);
13965             }
13966         }
13967
13968         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13969             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13970             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13971         } else {
13972             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13973         }
13974
13975         rc = bxe_get_igu_cam_info(sc);
13976
13977         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13978
13979         if (rc) {
13980             return (rc);
13981         }
13982     }
13983
13984     /*
13985      * Get base FW non-default (fast path) status block ID. This value is
13986      * used to initialize the fw_sb_id saved on the fp/queue structure to
13987      * determine the id used by the FW.
13988      */
13989     if (CHIP_IS_E1x(sc)) {
13990         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13991     } else {
13992         /*
13993          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13994          * the same queue are indicated on the same IGU SB). So we prefer
13995          * FW and IGU SBs to be the same value.
13996          */
13997         sc->base_fw_ndsb = sc->igu_base_sb;
13998     }
13999
14000     BLOGD(sc, DBG_LOAD,
14001           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
14002           sc->igu_dsb_id, sc->igu_base_sb,
14003           sc->igu_sb_cnt, sc->base_fw_ndsb);
14004
14005     elink_phy_probe(&sc->link_params);
14006
14007     return (0);
14008 }
14009
14010 static void
14011 bxe_link_settings_supported(struct bxe_softc *sc,
14012                             uint32_t         switch_cfg)
14013 {
14014     uint32_t cfg_size = 0;
14015     uint32_t idx;
14016     uint8_t port = SC_PORT(sc);
14017
14018     /* aggregation of supported attributes of all external phys */
14019     sc->port.supported[0] = 0;
14020     sc->port.supported[1] = 0;
14021
14022     switch (sc->link_params.num_phys) {
14023     case 1:
14024         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
14025         cfg_size = 1;
14026         break;
14027     case 2:
14028         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
14029         cfg_size = 1;
14030         break;
14031     case 3:
14032         if (sc->link_params.multi_phy_config &
14033             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
14034             sc->port.supported[1] =
14035                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14036             sc->port.supported[0] =
14037                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14038         } else {
14039             sc->port.supported[0] =
14040                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
14041             sc->port.supported[1] =
14042                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
14043         }
14044         cfg_size = 2;
14045         break;
14046     }
14047
14048     if (!(sc->port.supported[0] || sc->port.supported[1])) {
14049         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
14050               SHMEM_RD(sc,
14051                        dev_info.port_hw_config[port].external_phy_config),
14052               SHMEM_RD(sc,
14053                        dev_info.port_hw_config[port].external_phy_config2));
14054         return;
14055     }
14056
14057     if (CHIP_IS_E3(sc))
14058         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
14059     else {
14060         switch (switch_cfg) {
14061         case ELINK_SWITCH_CFG_1G:
14062             sc->port.phy_addr =
14063                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
14064             break;
14065         case ELINK_SWITCH_CFG_10G:
14066             sc->port.phy_addr =
14067                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
14068             break;
14069         default:
14070             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
14071                   sc->port.link_config[0]);
14072             return;
14073         }
14074     }
14075
14076     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
14077
14078     /* mask what we support according to speed_cap_mask per configuration */
14079     for (idx = 0; idx < cfg_size; idx++) {
14080         if (!(sc->link_params.speed_cap_mask[idx] &
14081               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
14082             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
14083         }
14084
14085         if (!(sc->link_params.speed_cap_mask[idx] &
14086               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14087             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14088         }
14089
14090         if (!(sc->link_params.speed_cap_mask[idx] &
14091               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14092             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14093         }
14094
14095         if (!(sc->link_params.speed_cap_mask[idx] &
14096               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14097             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14098         }
14099
14100         if (!(sc->link_params.speed_cap_mask[idx] &
14101               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14102             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14103         }
14104
14105         if (!(sc->link_params.speed_cap_mask[idx] &
14106               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14107             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14108         }
14109
14110         if (!(sc->link_params.speed_cap_mask[idx] &
14111               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14112             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14113         }
14114
14115         if (!(sc->link_params.speed_cap_mask[idx] &
14116               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14117             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14118         }
14119     }
14120
14121     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14122           sc->port.supported[0], sc->port.supported[1]);
14123 }
14124
14125 static void
14126 bxe_link_settings_requested(struct bxe_softc *sc)
14127 {
14128     uint32_t link_config;
14129     uint32_t idx;
14130     uint32_t cfg_size = 0;
14131
14132     sc->port.advertising[0] = 0;
14133     sc->port.advertising[1] = 0;
14134
14135     switch (sc->link_params.num_phys) {
14136     case 1:
14137     case 2:
14138         cfg_size = 1;
14139         break;
14140     case 3:
14141         cfg_size = 2;
14142         break;
14143     }
14144
14145     for (idx = 0; idx < cfg_size; idx++) {
14146         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14147         link_config = sc->port.link_config[idx];
14148
14149         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14150         case PORT_FEATURE_LINK_SPEED_AUTO:
14151             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14152                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14153                 sc->port.advertising[idx] |= sc->port.supported[idx];
14154                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14155                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14156                     sc->port.advertising[idx] |=
14157                         (ELINK_SUPPORTED_100baseT_Half |
14158                          ELINK_SUPPORTED_100baseT_Full);
14159             } else {
14160                 /* force 10G, no AN */
14161                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14162                 sc->port.advertising[idx] |=
14163                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14164                 continue;
14165             }
14166             break;
14167
14168         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14169             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14170                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14171                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14172                                               ADVERTISED_TP);
14173             } else {
14174                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14175                           "speed_cap_mask=0x%08x\n",
14176                       link_config, sc->link_params.speed_cap_mask[idx]);
14177                 return;
14178             }
14179             break;
14180
14181         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14182             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14183                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14184                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14185                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14186                                               ADVERTISED_TP);
14187             } else {
14188                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14189                           "speed_cap_mask=0x%08x\n",
14190                       link_config, sc->link_params.speed_cap_mask[idx]);
14191                 return;
14192             }
14193             break;
14194
14195         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14196             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14197                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14198                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14199                                               ADVERTISED_TP);
14200             } else {
14201                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14202                           "speed_cap_mask=0x%08x\n",
14203                       link_config, sc->link_params.speed_cap_mask[idx]);
14204                 return;
14205             }
14206             break;
14207
14208         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14209             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14210                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14211                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14212                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14213                                               ADVERTISED_TP);
14214             } else {
14215                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14216                           "speed_cap_mask=0x%08x\n",
14217                       link_config, sc->link_params.speed_cap_mask[idx]);
14218                 return;
14219             }
14220             break;
14221
14222         case PORT_FEATURE_LINK_SPEED_1G:
14223             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14224                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14225                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14226                                               ADVERTISED_TP);
14227             } else {
14228                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14229                           "speed_cap_mask=0x%08x\n",
14230                       link_config, sc->link_params.speed_cap_mask[idx]);
14231                 return;
14232             }
14233             break;
14234
14235         case PORT_FEATURE_LINK_SPEED_2_5G:
14236             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14237                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14238                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14239                                               ADVERTISED_TP);
14240             } else {
14241                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14242                           "speed_cap_mask=0x%08x\n",
14243                       link_config, sc->link_params.speed_cap_mask[idx]);
14244                 return;
14245             }
14246             break;
14247
14248         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14249             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14250                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14251                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14252                                               ADVERTISED_FIBRE);
14253             } else {
14254                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14255                           "speed_cap_mask=0x%08x\n",
14256                       link_config, sc->link_params.speed_cap_mask[idx]);
14257                 return;
14258             }
14259             break;
14260
14261         case PORT_FEATURE_LINK_SPEED_20G:
14262             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14263             break;
14264
14265         default:
14266             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14267                       "speed_cap_mask=0x%08x\n",
14268                   link_config, sc->link_params.speed_cap_mask[idx]);
14269             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14270             sc->port.advertising[idx] = sc->port.supported[idx];
14271             break;
14272         }
14273
14274         sc->link_params.req_flow_ctrl[idx] =
14275             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14276
14277         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14278             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14279                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14280             } else {
14281                 bxe_set_requested_fc(sc);
14282             }
14283         }
14284
14285         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14286                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14287               sc->link_params.req_line_speed[idx],
14288               sc->link_params.req_duplex[idx],
14289               sc->link_params.req_flow_ctrl[idx],
14290               sc->port.advertising[idx]);
14291     }
14292 }
14293
14294 static void
14295 bxe_get_phy_info(struct bxe_softc *sc)
14296 {
14297     uint8_t port = SC_PORT(sc);
14298     uint32_t config = sc->port.config;
14299     uint32_t eee_mode;
14300
14301     /* shmem data already read in bxe_get_shmem_info() */
14302
14303     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14304                         "link_config0=0x%08x\n",
14305                sc->link_params.lane_config,
14306                sc->link_params.speed_cap_mask[0],
14307                sc->port.link_config[0]);
14308
14309     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14310     bxe_link_settings_requested(sc);
14311
14312     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14313         sc->link_params.feature_config_flags |=
14314             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14315     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14316         sc->link_params.feature_config_flags &=
14317             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14318     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14319         sc->link_params.feature_config_flags |=
14320             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14321     }
14322
14323     /* configure link feature according to nvram value */
14324     eee_mode =
14325         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14326           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14327          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14328     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14329         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14330                                     ELINK_EEE_MODE_ENABLE_LPI |
14331                                     ELINK_EEE_MODE_OUTPUT_TIME);
14332     } else {
14333         sc->link_params.eee_mode = 0;
14334     }
14335
14336     /* get the media type */
14337     bxe_media_detect(sc);
14338 }
14339
14340 static void
14341 bxe_get_params(struct bxe_softc *sc)
14342 {
14343     /* get user tunable params */
14344     bxe_get_tunable_params(sc);
14345
14346     /* select the RX and TX ring sizes */
14347     sc->tx_ring_size = TX_BD_USABLE;
14348     sc->rx_ring_size = RX_BD_USABLE;
14349
14350     /* XXX disable WoL */
14351     sc->wol = 0;
14352 }
14353
14354 static void
14355 bxe_set_modes_bitmap(struct bxe_softc *sc)
14356 {
14357     uint32_t flags = 0;
14358
14359     if (CHIP_REV_IS_FPGA(sc)) {
14360         SET_FLAGS(flags, MODE_FPGA);
14361     } else if (CHIP_REV_IS_EMUL(sc)) {
14362         SET_FLAGS(flags, MODE_EMUL);
14363     } else {
14364         SET_FLAGS(flags, MODE_ASIC);
14365     }
14366
14367     if (CHIP_IS_MODE_4_PORT(sc)) {
14368         SET_FLAGS(flags, MODE_PORT4);
14369     } else {
14370         SET_FLAGS(flags, MODE_PORT2);
14371     }
14372
14373     if (CHIP_IS_E2(sc)) {
14374         SET_FLAGS(flags, MODE_E2);
14375     } else if (CHIP_IS_E3(sc)) {
14376         SET_FLAGS(flags, MODE_E3);
14377         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14378             SET_FLAGS(flags, MODE_E3_A0);
14379         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14380             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14381         }
14382     }
14383
14384     if (IS_MF(sc)) {
14385         SET_FLAGS(flags, MODE_MF);
14386         switch (sc->devinfo.mf_info.mf_mode) {
14387         case MULTI_FUNCTION_SD:
14388             SET_FLAGS(flags, MODE_MF_SD);
14389             break;
14390         case MULTI_FUNCTION_SI:
14391             SET_FLAGS(flags, MODE_MF_SI);
14392             break;
14393         case MULTI_FUNCTION_AFEX:
14394             SET_FLAGS(flags, MODE_MF_AFEX);
14395             break;
14396         }
14397     } else {
14398         SET_FLAGS(flags, MODE_SF);
14399     }
14400
14401 #if defined(__LITTLE_ENDIAN)
14402     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14403 #else /* __BIG_ENDIAN */
14404     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14405 #endif
14406
14407     INIT_MODE_FLAGS(sc) = flags;
14408 }
14409
14410 static int
14411 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14412 {
14413     struct bxe_fastpath *fp;
14414     bus_addr_t busaddr;
14415     int max_agg_queues;
14416     int max_segments;
14417     bus_size_t max_size;
14418     bus_size_t max_seg_size;
14419     char buf[32];
14420     int rc;
14421     int i, j;
14422
14423     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14424
14425     /* allocate the parent bus DMA tag */
14426     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14427                             1,                        /* alignment */
14428                             0,                        /* boundary limit */
14429                             BUS_SPACE_MAXADDR,        /* restricted low */
14430                             BUS_SPACE_MAXADDR,        /* restricted hi */
14431                             NULL,                     /* addr filter() */
14432                             NULL,                     /* addr filter() arg */
14433                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14434                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14435                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14436                             0,                        /* flags */
14437                             NULL,                     /* lock() */
14438                             NULL,                     /* lock() arg */
14439                             &sc->parent_dma_tag);     /* returned dma tag */
14440     if (rc != 0) {
14441         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14442         return (1);
14443     }
14444
14445     /************************/
14446     /* DEFAULT STATUS BLOCK */
14447     /************************/
14448
14449     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14450                       &sc->def_sb_dma, "default status block") != 0) {
14451         /* XXX */
14452         bus_dma_tag_destroy(sc->parent_dma_tag);
14453         return (1);
14454     }
14455
14456     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14457
14458     /***************/
14459     /* EVENT QUEUE */
14460     /***************/
14461
14462     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14463                       &sc->eq_dma, "event queue") != 0) {
14464         /* XXX */
14465         bxe_dma_free(sc, &sc->def_sb_dma);
14466         sc->def_sb = NULL;
14467         bus_dma_tag_destroy(sc->parent_dma_tag);
14468         return (1);
14469     }
14470
14471     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14472
14473     /*************/
14474     /* SLOW PATH */
14475     /*************/
14476
14477     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14478                       &sc->sp_dma, "slow path") != 0) {
14479         /* XXX */
14480         bxe_dma_free(sc, &sc->eq_dma);
14481         sc->eq = NULL;
14482         bxe_dma_free(sc, &sc->def_sb_dma);
14483         sc->def_sb = NULL;
14484         bus_dma_tag_destroy(sc->parent_dma_tag);
14485         return (1);
14486     }
14487
14488     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14489
14490     /*******************/
14491     /* SLOW PATH QUEUE */
14492     /*******************/
14493
14494     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14495                       &sc->spq_dma, "slow path queue") != 0) {
14496         /* XXX */
14497         bxe_dma_free(sc, &sc->sp_dma);
14498         sc->sp = NULL;
14499         bxe_dma_free(sc, &sc->eq_dma);
14500         sc->eq = NULL;
14501         bxe_dma_free(sc, &sc->def_sb_dma);
14502         sc->def_sb = NULL;
14503         bus_dma_tag_destroy(sc->parent_dma_tag);
14504         return (1);
14505     }
14506
14507     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14508
14509     /***************************/
14510     /* FW DECOMPRESSION BUFFER */
14511     /***************************/
14512
14513     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14514                       "fw decompression buffer") != 0) {
14515         /* XXX */
14516         bxe_dma_free(sc, &sc->spq_dma);
14517         sc->spq = NULL;
14518         bxe_dma_free(sc, &sc->sp_dma);
14519         sc->sp = NULL;
14520         bxe_dma_free(sc, &sc->eq_dma);
14521         sc->eq = NULL;
14522         bxe_dma_free(sc, &sc->def_sb_dma);
14523         sc->def_sb = NULL;
14524         bus_dma_tag_destroy(sc->parent_dma_tag);
14525         return (1);
14526     }
14527
14528     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14529
14530     if ((sc->gz_strm =
14531          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14532         /* XXX */
14533         bxe_dma_free(sc, &sc->gz_buf_dma);
14534         sc->gz_buf = NULL;
14535         bxe_dma_free(sc, &sc->spq_dma);
14536         sc->spq = NULL;
14537         bxe_dma_free(sc, &sc->sp_dma);
14538         sc->sp = NULL;
14539         bxe_dma_free(sc, &sc->eq_dma);
14540         sc->eq = NULL;
14541         bxe_dma_free(sc, &sc->def_sb_dma);
14542         sc->def_sb = NULL;
14543         bus_dma_tag_destroy(sc->parent_dma_tag);
14544         return (1);
14545     }
14546
14547     /*************/
14548     /* FASTPATHS */
14549     /*************/
14550
14551     /* allocate DMA memory for each fastpath structure */
14552     for (i = 0; i < sc->num_queues; i++) {
14553         fp = &sc->fp[i];
14554         fp->sc    = sc;
14555         fp->index = i;
14556
14557         /*******************/
14558         /* FP STATUS BLOCK */
14559         /*******************/
14560
14561         snprintf(buf, sizeof(buf), "fp %d status block", i);
14562         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14563                           &fp->sb_dma, buf) != 0) {
14564             /* XXX unwind and free previous fastpath allocations */
14565             BLOGE(sc, "Failed to alloc %s\n", buf);
14566             return (1);
14567         } else {
14568             if (CHIP_IS_E2E3(sc)) {
14569                 fp->status_block.e2_sb =
14570                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14571             } else {
14572                 fp->status_block.e1x_sb =
14573                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14574             }
14575         }
14576
14577         /******************/
14578         /* FP TX BD CHAIN */
14579         /******************/
14580
14581         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14582         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14583                           &fp->tx_dma, buf) != 0) {
14584             /* XXX unwind and free previous fastpath allocations */
14585             BLOGE(sc, "Failed to alloc %s\n", buf);
14586             return (1);
14587         } else {
14588             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14589         }
14590
14591         /* link together the tx bd chain pages */
14592         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14593             /* index into the tx bd chain array to last entry per page */
14594             struct eth_tx_next_bd *tx_next_bd =
14595                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14596             /* point to the next page and wrap from last page */
14597             busaddr = (fp->tx_dma.paddr +
14598                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14599             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14600             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14601         }
14602
14603         /******************/
14604         /* FP RX BD CHAIN */
14605         /******************/
14606
14607         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14608         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14609                           &fp->rx_dma, buf) != 0) {
14610             /* XXX unwind and free previous fastpath allocations */
14611             BLOGE(sc, "Failed to alloc %s\n", buf);
14612             return (1);
14613         } else {
14614             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14615         }
14616
14617         /* link together the rx bd chain pages */
14618         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14619             /* index into the rx bd chain array to last entry per page */
14620             struct eth_rx_bd *rx_bd =
14621                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14622             /* point to the next page and wrap from last page */
14623             busaddr = (fp->rx_dma.paddr +
14624                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14625             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14626             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14627         }
14628
14629         /*******************/
14630         /* FP RX RCQ CHAIN */
14631         /*******************/
14632
14633         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14634         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14635                           &fp->rcq_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->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14641         }
14642
14643         /* link together the rcq chain pages */
14644         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14645             /* index into the rcq chain array to last entry per page */
14646             struct eth_rx_cqe_next_page *rx_cqe_next =
14647                 (struct eth_rx_cqe_next_page *)
14648                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14649             /* point to the next page and wrap from last page */
14650             busaddr = (fp->rcq_dma.paddr +
14651                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14652             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14653             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14654         }
14655
14656         /*******************/
14657         /* FP RX SGE CHAIN */
14658         /*******************/
14659
14660         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14661         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14662                           &fp->rx_sge_dma, buf) != 0) {
14663             /* XXX unwind and free previous fastpath allocations */
14664             BLOGE(sc, "Failed to alloc %s\n", buf);
14665             return (1);
14666         } else {
14667             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14668         }
14669
14670         /* link together the sge chain pages */
14671         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14672             /* index into the rcq chain array to last entry per page */
14673             struct eth_rx_sge *rx_sge =
14674                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14675             /* point to the next page and wrap from last page */
14676             busaddr = (fp->rx_sge_dma.paddr +
14677                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14678             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14679             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14680         }
14681
14682         /***********************/
14683         /* FP TX MBUF DMA MAPS */
14684         /***********************/
14685
14686         /* set required sizes before mapping to conserve resources */
14687         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14688             max_size     = BXE_TSO_MAX_SIZE;
14689             max_segments = BXE_TSO_MAX_SEGMENTS;
14690             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14691         } else {
14692             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14693             max_segments = BXE_MAX_SEGMENTS;
14694             max_seg_size = MCLBYTES;
14695         }
14696
14697         /* create a dma tag for the tx mbufs */
14698         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14699                                 1,                  /* alignment */
14700                                 0,                  /* boundary limit */
14701                                 BUS_SPACE_MAXADDR,  /* restricted low */
14702                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14703                                 NULL,               /* addr filter() */
14704                                 NULL,               /* addr filter() arg */
14705                                 max_size,           /* max map size */
14706                                 max_segments,       /* num discontinuous */
14707                                 max_seg_size,       /* max seg size */
14708                                 0,                  /* flags */
14709                                 NULL,               /* lock() */
14710                                 NULL,               /* lock() arg */
14711                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14712         if (rc != 0) {
14713             /* XXX unwind and free previous fastpath allocations */
14714             BLOGE(sc, "Failed to create dma tag for "
14715                       "'fp %d tx mbufs' (%d)\n", i, rc);
14716             return (1);
14717         }
14718
14719         /* create dma maps for each of the tx mbuf clusters */
14720         for (j = 0; j < TX_BD_TOTAL; j++) {
14721             if (bus_dmamap_create(fp->tx_mbuf_tag,
14722                                   BUS_DMA_NOWAIT,
14723                                   &fp->tx_mbuf_chain[j].m_map)) {
14724                 /* XXX unwind and free previous fastpath allocations */
14725                 BLOGE(sc, "Failed to create dma map for "
14726                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14727                 return (1);
14728             }
14729         }
14730
14731         /***********************/
14732         /* FP RX MBUF DMA MAPS */
14733         /***********************/
14734
14735         /* create a dma tag for the rx mbufs */
14736         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14737                                 1,                  /* alignment */
14738                                 0,                  /* boundary limit */
14739                                 BUS_SPACE_MAXADDR,  /* restricted low */
14740                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14741                                 NULL,               /* addr filter() */
14742                                 NULL,               /* addr filter() arg */
14743                                 MJUM9BYTES,         /* max map size */
14744                                 1,                  /* num discontinuous */
14745                                 MJUM9BYTES,         /* max seg size */
14746                                 0,                  /* flags */
14747                                 NULL,               /* lock() */
14748                                 NULL,               /* lock() arg */
14749                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14750         if (rc != 0) {
14751             /* XXX unwind and free previous fastpath allocations */
14752             BLOGE(sc, "Failed to create dma tag for "
14753                       "'fp %d rx mbufs' (%d)\n", i, rc);
14754             return (1);
14755         }
14756
14757         /* create dma maps for each of the rx mbuf clusters */
14758         for (j = 0; j < RX_BD_TOTAL; j++) {
14759             if (bus_dmamap_create(fp->rx_mbuf_tag,
14760                                   BUS_DMA_NOWAIT,
14761                                   &fp->rx_mbuf_chain[j].m_map)) {
14762                 /* XXX unwind and free previous fastpath allocations */
14763                 BLOGE(sc, "Failed to create dma map for "
14764                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14765                 return (1);
14766             }
14767         }
14768
14769         /* create dma map for the spare rx mbuf cluster */
14770         if (bus_dmamap_create(fp->rx_mbuf_tag,
14771                               BUS_DMA_NOWAIT,
14772                               &fp->rx_mbuf_spare_map)) {
14773             /* XXX unwind and free previous fastpath allocations */
14774             BLOGE(sc, "Failed to create dma map for "
14775                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14776             return (1);
14777         }
14778
14779         /***************************/
14780         /* FP RX SGE MBUF DMA MAPS */
14781         /***************************/
14782
14783         /* create a dma tag for the rx sge mbufs */
14784         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14785                                 1,                  /* alignment */
14786                                 0,                  /* boundary limit */
14787                                 BUS_SPACE_MAXADDR,  /* restricted low */
14788                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14789                                 NULL,               /* addr filter() */
14790                                 NULL,               /* addr filter() arg */
14791                                 BCM_PAGE_SIZE,      /* max map size */
14792                                 1,                  /* num discontinuous */
14793                                 BCM_PAGE_SIZE,      /* max seg size */
14794                                 0,                  /* flags */
14795                                 NULL,               /* lock() */
14796                                 NULL,               /* lock() arg */
14797                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14798         if (rc != 0) {
14799             /* XXX unwind and free previous fastpath allocations */
14800             BLOGE(sc, "Failed to create dma tag for "
14801                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14802             return (1);
14803         }
14804
14805         /* create dma maps for the rx sge mbuf clusters */
14806         for (j = 0; j < RX_SGE_TOTAL; j++) {
14807             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14808                                   BUS_DMA_NOWAIT,
14809                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14810                 /* XXX unwind and free previous fastpath allocations */
14811                 BLOGE(sc, "Failed to create dma map for "
14812                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14813                 return (1);
14814             }
14815         }
14816
14817         /* create dma map for the spare rx sge mbuf cluster */
14818         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14819                               BUS_DMA_NOWAIT,
14820                               &fp->rx_sge_mbuf_spare_map)) {
14821             /* XXX unwind and free previous fastpath allocations */
14822             BLOGE(sc, "Failed to create dma map for "
14823                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14824             return (1);
14825         }
14826
14827         /***************************/
14828         /* FP RX TPA MBUF DMA MAPS */
14829         /***************************/
14830
14831         /* create dma maps for the rx tpa mbuf clusters */
14832         max_agg_queues = MAX_AGG_QS(sc);
14833
14834         for (j = 0; j < max_agg_queues; j++) {
14835             if (bus_dmamap_create(fp->rx_mbuf_tag,
14836                                   BUS_DMA_NOWAIT,
14837                                   &fp->rx_tpa_info[j].bd.m_map)) {
14838                 /* XXX unwind and free previous fastpath allocations */
14839                 BLOGE(sc, "Failed to create dma map for "
14840                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14841                 return (1);
14842             }
14843         }
14844
14845         /* create dma map for the spare rx tpa mbuf cluster */
14846         if (bus_dmamap_create(fp->rx_mbuf_tag,
14847                               BUS_DMA_NOWAIT,
14848                               &fp->rx_tpa_info_mbuf_spare_map)) {
14849             /* XXX unwind and free previous fastpath allocations */
14850             BLOGE(sc, "Failed to create dma map for "
14851                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14852             return (1);
14853         }
14854
14855         bxe_init_sge_ring_bit_mask(fp);
14856     }
14857
14858     return (0);
14859 }
14860
14861 static void
14862 bxe_free_hsi_mem(struct bxe_softc *sc)
14863 {
14864     struct bxe_fastpath *fp;
14865     int max_agg_queues;
14866     int i, j;
14867
14868     if (sc->parent_dma_tag == NULL) {
14869         return; /* assume nothing was allocated */
14870     }
14871
14872     for (i = 0; i < sc->num_queues; i++) {
14873         fp = &sc->fp[i];
14874
14875         /*******************/
14876         /* FP STATUS BLOCK */
14877         /*******************/
14878
14879         bxe_dma_free(sc, &fp->sb_dma);
14880         memset(&fp->status_block, 0, sizeof(fp->status_block));
14881
14882         /******************/
14883         /* FP TX BD CHAIN */
14884         /******************/
14885
14886         bxe_dma_free(sc, &fp->tx_dma);
14887         fp->tx_chain = NULL;
14888
14889         /******************/
14890         /* FP RX BD CHAIN */
14891         /******************/
14892
14893         bxe_dma_free(sc, &fp->rx_dma);
14894         fp->rx_chain = NULL;
14895
14896         /*******************/
14897         /* FP RX RCQ CHAIN */
14898         /*******************/
14899
14900         bxe_dma_free(sc, &fp->rcq_dma);
14901         fp->rcq_chain = NULL;
14902
14903         /*******************/
14904         /* FP RX SGE CHAIN */
14905         /*******************/
14906
14907         bxe_dma_free(sc, &fp->rx_sge_dma);
14908         fp->rx_sge_chain = NULL;
14909
14910         /***********************/
14911         /* FP TX MBUF DMA MAPS */
14912         /***********************/
14913
14914         if (fp->tx_mbuf_tag != NULL) {
14915             for (j = 0; j < TX_BD_TOTAL; j++) {
14916                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14917                     bus_dmamap_unload(fp->tx_mbuf_tag,
14918                                       fp->tx_mbuf_chain[j].m_map);
14919                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14920                                        fp->tx_mbuf_chain[j].m_map);
14921                 }
14922             }
14923
14924             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14925             fp->tx_mbuf_tag = NULL;
14926         }
14927
14928         /***********************/
14929         /* FP RX MBUF DMA MAPS */
14930         /***********************/
14931
14932         if (fp->rx_mbuf_tag != NULL) {
14933             for (j = 0; j < RX_BD_TOTAL; j++) {
14934                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14935                     bus_dmamap_unload(fp->rx_mbuf_tag,
14936                                       fp->rx_mbuf_chain[j].m_map);
14937                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14938                                        fp->rx_mbuf_chain[j].m_map);
14939                 }
14940             }
14941
14942             if (fp->rx_mbuf_spare_map != NULL) {
14943                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14944                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14945             }
14946
14947             /***************************/
14948             /* FP RX TPA MBUF DMA MAPS */
14949             /***************************/
14950
14951             max_agg_queues = MAX_AGG_QS(sc);
14952
14953             for (j = 0; j < max_agg_queues; j++) {
14954                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14955                     bus_dmamap_unload(fp->rx_mbuf_tag,
14956                                       fp->rx_tpa_info[j].bd.m_map);
14957                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14958                                        fp->rx_tpa_info[j].bd.m_map);
14959                 }
14960             }
14961
14962             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14963                 bus_dmamap_unload(fp->rx_mbuf_tag,
14964                                   fp->rx_tpa_info_mbuf_spare_map);
14965                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14966                                    fp->rx_tpa_info_mbuf_spare_map);
14967             }
14968
14969             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14970             fp->rx_mbuf_tag = NULL;
14971         }
14972
14973         /***************************/
14974         /* FP RX SGE MBUF DMA MAPS */
14975         /***************************/
14976
14977         if (fp->rx_sge_mbuf_tag != NULL) {
14978             for (j = 0; j < RX_SGE_TOTAL; j++) {
14979                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14980                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14981                                       fp->rx_sge_mbuf_chain[j].m_map);
14982                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14983                                        fp->rx_sge_mbuf_chain[j].m_map);
14984                 }
14985             }
14986
14987             if (fp->rx_sge_mbuf_spare_map != NULL) {
14988                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14989                                   fp->rx_sge_mbuf_spare_map);
14990                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14991                                    fp->rx_sge_mbuf_spare_map);
14992             }
14993
14994             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14995             fp->rx_sge_mbuf_tag = NULL;
14996         }
14997     }
14998
14999     /***************************/
15000     /* FW DECOMPRESSION BUFFER */
15001     /***************************/
15002
15003     bxe_dma_free(sc, &sc->gz_buf_dma);
15004     sc->gz_buf = NULL;
15005     free(sc->gz_strm, M_DEVBUF);
15006     sc->gz_strm = NULL;
15007
15008     /*******************/
15009     /* SLOW PATH QUEUE */
15010     /*******************/
15011
15012     bxe_dma_free(sc, &sc->spq_dma);
15013     sc->spq = NULL;
15014
15015     /*************/
15016     /* SLOW PATH */
15017     /*************/
15018
15019     bxe_dma_free(sc, &sc->sp_dma);
15020     sc->sp = NULL;
15021
15022     /***************/
15023     /* EVENT QUEUE */
15024     /***************/
15025
15026     bxe_dma_free(sc, &sc->eq_dma);
15027     sc->eq = NULL;
15028
15029     /************************/
15030     /* DEFAULT STATUS BLOCK */
15031     /************************/
15032
15033     bxe_dma_free(sc, &sc->def_sb_dma);
15034     sc->def_sb = NULL;
15035
15036     bus_dma_tag_destroy(sc->parent_dma_tag);
15037     sc->parent_dma_tag = NULL;
15038 }
15039
15040 /*
15041  * Previous driver DMAE transaction may have occurred when pre-boot stage
15042  * ended and boot began. This would invalidate the addresses of the
15043  * transaction, resulting in was-error bit set in the PCI causing all
15044  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
15045  * the interrupt which detected this from the pglueb and the was-done bit
15046  */
15047 static void
15048 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
15049 {
15050     uint32_t val;
15051
15052     if (!CHIP_IS_E1x(sc)) {
15053         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
15054         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
15055             BLOGD(sc, DBG_LOAD,
15056                   "Clearing 'was-error' bit that was set in pglueb");
15057             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
15058         }
15059     }
15060 }
15061
15062 static int
15063 bxe_prev_mcp_done(struct bxe_softc *sc)
15064 {
15065     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
15066                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
15067     if (!rc) {
15068         BLOGE(sc, "MCP response failure, aborting\n");
15069         return (-1);
15070     }
15071
15072     return (0);
15073 }
15074
15075 static struct bxe_prev_list_node *
15076 bxe_prev_path_get_entry(struct bxe_softc *sc)
15077 {
15078     struct bxe_prev_list_node *tmp;
15079
15080     LIST_FOREACH(tmp, &bxe_prev_list, node) {
15081         if ((sc->pcie_bus == tmp->bus) &&
15082             (sc->pcie_device == tmp->slot) &&
15083             (SC_PATH(sc) == tmp->path)) {
15084             return (tmp);
15085         }
15086     }
15087
15088     return (NULL);
15089 }
15090
15091 static uint8_t
15092 bxe_prev_is_path_marked(struct bxe_softc *sc)
15093 {
15094     struct bxe_prev_list_node *tmp;
15095     int rc = FALSE;
15096
15097     mtx_lock(&bxe_prev_mtx);
15098
15099     tmp = bxe_prev_path_get_entry(sc);
15100     if (tmp) {
15101         if (tmp->aer) {
15102             BLOGD(sc, DBG_LOAD,
15103                   "Path %d/%d/%d was marked by AER\n",
15104                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15105         } else {
15106             rc = TRUE;
15107             BLOGD(sc, DBG_LOAD,
15108                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15109                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15110         }
15111     }
15112
15113     mtx_unlock(&bxe_prev_mtx);
15114
15115     return (rc);
15116 }
15117
15118 static int
15119 bxe_prev_mark_path(struct bxe_softc *sc,
15120                    uint8_t          after_undi)
15121 {
15122     struct bxe_prev_list_node *tmp;
15123
15124     mtx_lock(&bxe_prev_mtx);
15125
15126     /* Check whether the entry for this path already exists */
15127     tmp = bxe_prev_path_get_entry(sc);
15128     if (tmp) {
15129         if (!tmp->aer) {
15130             BLOGD(sc, DBG_LOAD,
15131                   "Re-marking AER in path %d/%d/%d\n",
15132                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15133         } else {
15134             BLOGD(sc, DBG_LOAD,
15135                   "Removing AER indication from path %d/%d/%d\n",
15136                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15137             tmp->aer = 0;
15138         }
15139
15140         mtx_unlock(&bxe_prev_mtx);
15141         return (0);
15142     }
15143
15144     mtx_unlock(&bxe_prev_mtx);
15145
15146     /* Create an entry for this path and add it */
15147     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15148                  (M_NOWAIT | M_ZERO));
15149     if (!tmp) {
15150         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15151         return (-1);
15152     }
15153
15154     tmp->bus  = sc->pcie_bus;
15155     tmp->slot = sc->pcie_device;
15156     tmp->path = SC_PATH(sc);
15157     tmp->aer  = 0;
15158     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15159
15160     mtx_lock(&bxe_prev_mtx);
15161
15162     BLOGD(sc, DBG_LOAD,
15163           "Marked path %d/%d/%d - finished previous unload\n",
15164           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15165     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15166
15167     mtx_unlock(&bxe_prev_mtx);
15168
15169     return (0);
15170 }
15171
15172 static int
15173 bxe_do_flr(struct bxe_softc *sc)
15174 {
15175     int i;
15176
15177     /* only E2 and onwards support FLR */
15178     if (CHIP_IS_E1x(sc)) {
15179         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15180         return (-1);
15181     }
15182
15183     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15184     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15185         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15186               sc->devinfo.bc_ver);
15187         return (-1);
15188     }
15189
15190     /* Wait for Transaction Pending bit clean */
15191     for (i = 0; i < 4; i++) {
15192         if (i) {
15193             DELAY(((1 << (i - 1)) * 100) * 1000);
15194         }
15195
15196         if (!bxe_is_pcie_pending(sc)) {
15197             goto clear;
15198         }
15199     }
15200
15201     BLOGE(sc, "PCIE transaction is not cleared, "
15202               "proceeding with reset anyway\n");
15203
15204 clear:
15205
15206     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15207     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15208
15209     return (0);
15210 }
15211
15212 struct bxe_mac_vals {
15213     uint32_t xmac_addr;
15214     uint32_t xmac_val;
15215     uint32_t emac_addr;
15216     uint32_t emac_val;
15217     uint32_t umac_addr;
15218     uint32_t umac_val;
15219     uint32_t bmac_addr;
15220     uint32_t bmac_val[2];
15221 };
15222
15223 static void
15224 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15225                           struct bxe_mac_vals *vals)
15226 {
15227     uint32_t val, base_addr, offset, mask, reset_reg;
15228     uint8_t mac_stopped = FALSE;
15229     uint8_t port = SC_PORT(sc);
15230     uint32_t wb_data[2];
15231
15232     /* reset addresses as they also mark which values were changed */
15233     vals->bmac_addr = 0;
15234     vals->umac_addr = 0;
15235     vals->xmac_addr = 0;
15236     vals->emac_addr = 0;
15237
15238     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15239
15240     if (!CHIP_IS_E3(sc)) {
15241         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15242         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15243         if ((mask & reset_reg) && val) {
15244             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15245             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15246                                     : NIG_REG_INGRESS_BMAC0_MEM;
15247             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15248                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15249
15250             /*
15251              * use rd/wr since we cannot use dmae. This is safe
15252              * since MCP won't access the bus due to the request
15253              * to unload, and no function on the path can be
15254              * loaded at this time.
15255              */
15256             wb_data[0] = REG_RD(sc, base_addr + offset);
15257             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15258             vals->bmac_addr = base_addr + offset;
15259             vals->bmac_val[0] = wb_data[0];
15260             vals->bmac_val[1] = wb_data[1];
15261             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15262             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15263             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15264         }
15265
15266         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15267         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15268         vals->emac_val = REG_RD(sc, vals->emac_addr);
15269         REG_WR(sc, vals->emac_addr, 0);
15270         mac_stopped = TRUE;
15271     } else {
15272         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15273             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15274             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15275             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15276             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15277             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15278             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15279             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15280             REG_WR(sc, vals->xmac_addr, 0);
15281             mac_stopped = TRUE;
15282         }
15283
15284         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15285         if (mask & reset_reg) {
15286             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15287             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15288             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15289             vals->umac_val = REG_RD(sc, vals->umac_addr);
15290             REG_WR(sc, vals->umac_addr, 0);
15291             mac_stopped = TRUE;
15292         }
15293     }
15294
15295     if (mac_stopped) {
15296         DELAY(20000);
15297     }
15298 }
15299
15300 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15301 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15302 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15303 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15304
15305 static void
15306 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15307                          uint8_t          port,
15308                          uint8_t          inc)
15309 {
15310     uint16_t rcq, bd;
15311     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15312
15313     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15314     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15315
15316     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15317     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15318
15319     BLOGD(sc, DBG_LOAD,
15320           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15321           port, bd, rcq);
15322 }
15323
15324 static int
15325 bxe_prev_unload_common(struct bxe_softc *sc)
15326 {
15327     uint32_t reset_reg, tmp_reg = 0, rc;
15328     uint8_t prev_undi = FALSE;
15329     struct bxe_mac_vals mac_vals;
15330     uint32_t timer_count = 1000;
15331     uint32_t prev_brb;
15332
15333     /*
15334      * It is possible a previous function received 'common' answer,
15335      * but hasn't loaded yet, therefore creating a scenario of
15336      * multiple functions receiving 'common' on the same path.
15337      */
15338     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15339
15340     memset(&mac_vals, 0, sizeof(mac_vals));
15341
15342     if (bxe_prev_is_path_marked(sc)) {
15343         return (bxe_prev_mcp_done(sc));
15344     }
15345
15346     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15347
15348     /* Reset should be performed after BRB is emptied */
15349     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15350         /* Close the MAC Rx to prevent BRB from filling up */
15351         bxe_prev_unload_close_mac(sc, &mac_vals);
15352
15353         /* close LLH filters towards the BRB */
15354         elink_set_rx_filter(&sc->link_params, 0);
15355
15356         /*
15357          * Check if the UNDI driver was previously loaded.
15358          * UNDI driver initializes CID offset for normal bell to 0x7
15359          */
15360         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15361             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15362             if (tmp_reg == 0x7) {
15363                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15364                 prev_undi = TRUE;
15365                 /* clear the UNDI indication */
15366                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15367                 /* clear possible idle check errors */
15368                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15369             }
15370         }
15371
15372         /* wait until BRB is empty */
15373         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15374         while (timer_count) {
15375             prev_brb = tmp_reg;
15376
15377             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15378             if (!tmp_reg) {
15379                 break;
15380             }
15381
15382             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15383
15384             /* reset timer as long as BRB actually gets emptied */
15385             if (prev_brb > tmp_reg) {
15386                 timer_count = 1000;
15387             } else {
15388                 timer_count--;
15389             }
15390
15391             /* If UNDI resides in memory, manually increment it */
15392             if (prev_undi) {
15393                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15394             }
15395
15396             DELAY(10);
15397         }
15398
15399         if (!timer_count) {
15400             BLOGE(sc, "Failed to empty BRB\n");
15401         }
15402     }
15403
15404     /* No packets are in the pipeline, path is ready for reset */
15405     bxe_reset_common(sc);
15406
15407     if (mac_vals.xmac_addr) {
15408         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15409     }
15410     if (mac_vals.umac_addr) {
15411         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15412     }
15413     if (mac_vals.emac_addr) {
15414         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15415     }
15416     if (mac_vals.bmac_addr) {
15417         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15418         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15419     }
15420
15421     rc = bxe_prev_mark_path(sc, prev_undi);
15422     if (rc) {
15423         bxe_prev_mcp_done(sc);
15424         return (rc);
15425     }
15426
15427     return (bxe_prev_mcp_done(sc));
15428 }
15429
15430 static int
15431 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15432 {
15433     int rc;
15434
15435     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15436
15437     /* Test if previous unload process was already finished for this path */
15438     if (bxe_prev_is_path_marked(sc)) {
15439         return (bxe_prev_mcp_done(sc));
15440     }
15441
15442     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15443
15444     /*
15445      * If function has FLR capabilities, and existing FW version matches
15446      * the one required, then FLR will be sufficient to clean any residue
15447      * left by previous driver
15448      */
15449     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15450     if (!rc) {
15451         /* fw version is good */
15452         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15453         rc = bxe_do_flr(sc);
15454     }
15455
15456     if (!rc) {
15457         /* FLR was performed */
15458         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15459         return (0);
15460     }
15461
15462     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15463
15464     /* Close the MCP request, return failure*/
15465     rc = bxe_prev_mcp_done(sc);
15466     if (!rc) {
15467         rc = BXE_PREV_WAIT_NEEDED;
15468     }
15469
15470     return (rc);
15471 }
15472
15473 static int
15474 bxe_prev_unload(struct bxe_softc *sc)
15475 {
15476     int time_counter = 10;
15477     uint32_t fw, hw_lock_reg, hw_lock_val;
15478     uint32_t rc = 0;
15479
15480     /*
15481      * Clear HW from errors which may have resulted from an interrupted
15482      * DMAE transaction.
15483      */
15484     bxe_prev_interrupted_dmae(sc);
15485
15486     /* Release previously held locks */
15487     hw_lock_reg =
15488         (SC_FUNC(sc) <= 5) ?
15489             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15490             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15491
15492     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15493     if (hw_lock_val) {
15494         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15495             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15496             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15497                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15498         }
15499         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15500         REG_WR(sc, hw_lock_reg, 0xffffffff);
15501     } else {
15502         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15503     }
15504
15505     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15506         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15507         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15508     }
15509
15510     do {
15511         /* Lock MCP using an unload request */
15512         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15513         if (!fw) {
15514             BLOGE(sc, "MCP response failure, aborting\n");
15515             rc = -1;
15516             break;
15517         }
15518
15519         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15520             rc = bxe_prev_unload_common(sc);
15521             break;
15522         }
15523
15524         /* non-common reply from MCP night require looping */
15525         rc = bxe_prev_unload_uncommon(sc);
15526         if (rc != BXE_PREV_WAIT_NEEDED) {
15527             break;
15528         }
15529
15530         DELAY(20000);
15531     } while (--time_counter);
15532
15533     if (!time_counter || rc) {
15534         BLOGE(sc, "Failed to unload previous driver!"
15535             " time_counter %d rc %d\n", time_counter, rc);
15536         rc = -1;
15537     }
15538
15539     return (rc);
15540 }
15541
15542 void
15543 bxe_dcbx_set_state(struct bxe_softc *sc,
15544                    uint8_t          dcb_on,
15545                    uint32_t         dcbx_enabled)
15546 {
15547     if (!CHIP_IS_E1x(sc)) {
15548         sc->dcb_state = dcb_on;
15549         sc->dcbx_enabled = dcbx_enabled;
15550     } else {
15551         sc->dcb_state = FALSE;
15552         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15553     }
15554     BLOGD(sc, DBG_LOAD,
15555           "DCB state [%s:%s]\n",
15556           dcb_on ? "ON" : "OFF",
15557           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15558           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15559           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15560           "on-chip with negotiation" : "invalid");
15561 }
15562
15563 /* must be called after sriov-enable */
15564 static int
15565 bxe_set_qm_cid_count(struct bxe_softc *sc)
15566 {
15567     int cid_count = BXE_L2_MAX_CID(sc);
15568
15569     if (IS_SRIOV(sc)) {
15570         cid_count += BXE_VF_CIDS;
15571     }
15572
15573     if (CNIC_SUPPORT(sc)) {
15574         cid_count += CNIC_CID_MAX;
15575     }
15576
15577     return (roundup(cid_count, QM_CID_ROUND));
15578 }
15579
15580 static void
15581 bxe_init_multi_cos(struct bxe_softc *sc)
15582 {
15583     int pri, cos;
15584
15585     uint32_t pri_map = 0; /* XXX change to user config */
15586
15587     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15588         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15589         if (cos < sc->max_cos) {
15590             sc->prio_to_cos[pri] = cos;
15591         } else {
15592             BLOGW(sc, "Invalid COS %d for priority %d "
15593                       "(max COS is %d), setting to 0\n",
15594                   cos, pri, (sc->max_cos - 1));
15595             sc->prio_to_cos[pri] = 0;
15596         }
15597     }
15598 }
15599
15600 static int
15601 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15602 {
15603     struct bxe_softc *sc;
15604     int error, result;
15605
15606     result = 0;
15607     error = sysctl_handle_int(oidp, &result, 0, req);
15608
15609     if (error || !req->newptr) {
15610         return (error);
15611     }
15612
15613     if (result == 1) {
15614         uint32_t  temp;
15615         sc = (struct bxe_softc *)arg1;
15616
15617         BLOGI(sc, "... dumping driver state ...\n");
15618         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15619         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15620     }
15621
15622     return (error);
15623 }
15624
15625 static int
15626 bxe_sysctl_trigger_grcdump(SYSCTL_HANDLER_ARGS)
15627 {
15628     struct bxe_softc *sc;
15629     int error, result;
15630
15631     result = 0;
15632     error = sysctl_handle_int(oidp, &result, 0, req);
15633
15634     if (error || !req->newptr) {
15635         return (error);
15636     }
15637
15638     if (result == 1) {
15639         sc = (struct bxe_softc *)arg1;
15640
15641         BLOGI(sc, "... grcdump start ...\n");
15642         bxe_grc_dump(sc);
15643         BLOGI(sc, "... grcdump done ...\n");
15644     }
15645
15646     return (error);
15647 }
15648
15649 static int
15650 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15651 {
15652     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15653     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15654     uint32_t *offset;
15655     uint64_t value = 0;
15656     int index = (int)arg2;
15657
15658     if (index >= BXE_NUM_ETH_STATS) {
15659         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15660         return (-1);
15661     }
15662
15663     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15664
15665     switch (bxe_eth_stats_arr[index].size) {
15666     case 4:
15667         value = (uint64_t)*offset;
15668         break;
15669     case 8:
15670         value = HILO_U64(*offset, *(offset + 1));
15671         break;
15672     default:
15673         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15674               index, bxe_eth_stats_arr[index].size);
15675         return (-1);
15676     }
15677
15678     return (sysctl_handle_64(oidp, &value, 0, req));
15679 }
15680
15681 static int
15682 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15683 {
15684     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15685     uint32_t *eth_stats;
15686     uint32_t *offset;
15687     uint64_t value = 0;
15688     uint32_t q_stat = (uint32_t)arg2;
15689     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15690     uint32_t index = (q_stat & 0xffff);
15691
15692     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15693
15694     if (index >= BXE_NUM_ETH_Q_STATS) {
15695         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15696         return (-1);
15697     }
15698
15699     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15700
15701     switch (bxe_eth_q_stats_arr[index].size) {
15702     case 4:
15703         value = (uint64_t)*offset;
15704         break;
15705     case 8:
15706         value = HILO_U64(*offset, *(offset + 1));
15707         break;
15708     default:
15709         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15710               index, bxe_eth_q_stats_arr[index].size);
15711         return (-1);
15712     }
15713
15714     return (sysctl_handle_64(oidp, &value, 0, req));
15715 }
15716
15717 static void
15718 bxe_add_sysctls(struct bxe_softc *sc)
15719 {
15720     struct sysctl_ctx_list *ctx;
15721     struct sysctl_oid_list *children;
15722     struct sysctl_oid *queue_top, *queue;
15723     struct sysctl_oid_list *queue_top_children, *queue_children;
15724     char queue_num_buf[32];
15725     uint32_t q_stat;
15726     int i, j;
15727
15728     ctx = device_get_sysctl_ctx(sc->dev);
15729     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15730
15731     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15732                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15733                       "version");
15734
15735     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15736                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15737                       "bootcode version");
15738
15739     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15740              BCM_5710_FW_MAJOR_VERSION,
15741              BCM_5710_FW_MINOR_VERSION,
15742              BCM_5710_FW_REVISION_VERSION,
15743              BCM_5710_FW_ENGINEERING_VERSION);
15744     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15745                       CTLFLAG_RD, sc->fw_ver_str, 0,
15746                       "firmware version");
15747
15748     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15749         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15750          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15751          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15752          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15753                                                                 "Unknown"));
15754     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15755                       CTLFLAG_RD, sc->mf_mode_str, 0,
15756                       "multifunction mode");
15757
15758     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15759                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15760                     "multifunction vnics per port");
15761
15762     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15763                       CTLFLAG_RD, sc->mac_addr_str, 0,
15764                       "mac address");
15765
15766     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15767         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15768          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15769          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15770                                               "???GT/s"),
15771         sc->devinfo.pcie_link_width);
15772     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15773                       CTLFLAG_RD, sc->pci_link_str, 0,
15774                       "pci link status");
15775
15776     sc->debug = bxe_debug;
15777     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15778                     CTLFLAG_RW, &sc->debug,
15779                     "debug logging mode");
15780
15781     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "trigger_grcdump",
15782                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15783                     bxe_sysctl_trigger_grcdump, "IU",
15784                     "set by driver when a grcdump is needed");
15785
15786     sc->grcdump_done = 0;
15787     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15788                    CTLFLAG_RW, &sc->grcdump_done, 0,
15789                    "set by driver when grcdump is done");
15790
15791     sc->rx_budget = bxe_rx_budget;
15792     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15793                     CTLFLAG_RW, &sc->rx_budget, 0,
15794                     "rx processing budget");
15795
15796     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15797                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15798                     bxe_sysctl_state, "IU", "dump driver state");
15799
15800     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15801         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15802                         bxe_eth_stats_arr[i].string,
15803                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15804                         bxe_sysctl_eth_stat, "LU",
15805                         bxe_eth_stats_arr[i].string);
15806     }
15807
15808     /* add a new parent node for all queues "dev.bxe.#.queue" */
15809     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15810                                 CTLFLAG_RD, NULL, "queue");
15811     queue_top_children = SYSCTL_CHILDREN(queue_top);
15812
15813     for (i = 0; i < sc->num_queues; i++) {
15814         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15815         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15816         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15817                                 queue_num_buf, CTLFLAG_RD, NULL,
15818                                 "single queue");
15819         queue_children = SYSCTL_CHILDREN(queue);
15820
15821         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15822             q_stat = ((i << 16) | j);
15823             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15824                             bxe_eth_q_stats_arr[j].string,
15825                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15826                             bxe_sysctl_eth_q_stat, "LU",
15827                             bxe_eth_q_stats_arr[j].string);
15828         }
15829     }
15830 }
15831
15832 /*
15833  * Device attach function.
15834  *
15835  * Allocates device resources, performs secondary chip identification, and
15836  * initializes driver instance variables. This function is called from driver
15837  * load after a successful probe.
15838  *
15839  * Returns:
15840  *   0 = Success, >0 = Failure
15841  */
15842 static int
15843 bxe_attach(device_t dev)
15844 {
15845     struct bxe_softc *sc;
15846
15847     sc = device_get_softc(dev);
15848
15849     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15850
15851     sc->state = BXE_STATE_CLOSED;
15852
15853     sc->dev  = dev;
15854     sc->unit = device_get_unit(dev);
15855
15856     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15857
15858     sc->pcie_bus    = pci_get_bus(dev);
15859     sc->pcie_device = pci_get_slot(dev);
15860     sc->pcie_func   = pci_get_function(dev);
15861
15862     /* enable bus master capability */
15863     pci_enable_busmaster(dev);
15864
15865     /* get the BARs */
15866     if (bxe_allocate_bars(sc) != 0) {
15867         return (ENXIO);
15868     }
15869
15870     /* initialize the mutexes */
15871     bxe_init_mutexes(sc);
15872
15873     /* prepare the periodic callout */
15874     callout_init(&sc->periodic_callout, 0);
15875
15876     /* prepare the chip taskqueue */
15877     sc->chip_tq_flags = CHIP_TQ_NONE;
15878     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15879              "bxe%d_chip_tq", sc->unit);
15880     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15881     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15882                                    taskqueue_thread_enqueue,
15883                                    &sc->chip_tq);
15884     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15885                             "%s", sc->chip_tq_name);
15886
15887     /* get device info and set params */
15888     if (bxe_get_device_info(sc) != 0) {
15889         BLOGE(sc, "getting device info\n");
15890         bxe_deallocate_bars(sc);
15891         pci_disable_busmaster(dev);
15892         return (ENXIO);
15893     }
15894
15895     /* get final misc params */
15896     bxe_get_params(sc);
15897
15898     /* set the default MTU (changed via ifconfig) */
15899     sc->mtu = ETHERMTU;
15900
15901     bxe_set_modes_bitmap(sc);
15902
15903     /* XXX
15904      * If in AFEX mode and the function is configured for FCoE
15905      * then bail... no L2 allowed.
15906      */
15907
15908     /* get phy settings from shmem and 'and' against admin settings */
15909     bxe_get_phy_info(sc);
15910
15911     /* initialize the FreeBSD ifnet interface */
15912     if (bxe_init_ifnet(sc) != 0) {
15913         bxe_release_mutexes(sc);
15914         bxe_deallocate_bars(sc);
15915         pci_disable_busmaster(dev);
15916         return (ENXIO);
15917     }
15918
15919     if (bxe_add_cdev(sc) != 0) {
15920         if (sc->ifnet != NULL) {
15921             ether_ifdetach(sc->ifnet);
15922         }
15923         ifmedia_removeall(&sc->ifmedia);
15924         bxe_release_mutexes(sc);
15925         bxe_deallocate_bars(sc);
15926         pci_disable_busmaster(dev);
15927         return (ENXIO);
15928     }
15929
15930     /* allocate device interrupts */
15931     if (bxe_interrupt_alloc(sc) != 0) {
15932         bxe_del_cdev(sc);
15933         if (sc->ifnet != NULL) {
15934             ether_ifdetach(sc->ifnet);
15935         }
15936         ifmedia_removeall(&sc->ifmedia);
15937         bxe_release_mutexes(sc);
15938         bxe_deallocate_bars(sc);
15939         pci_disable_busmaster(dev);
15940         return (ENXIO);
15941     }
15942
15943     /* allocate ilt */
15944     if (bxe_alloc_ilt_mem(sc) != 0) {
15945         bxe_interrupt_free(sc);
15946         bxe_del_cdev(sc);
15947         if (sc->ifnet != NULL) {
15948             ether_ifdetach(sc->ifnet);
15949         }
15950         ifmedia_removeall(&sc->ifmedia);
15951         bxe_release_mutexes(sc);
15952         bxe_deallocate_bars(sc);
15953         pci_disable_busmaster(dev);
15954         return (ENXIO);
15955     }
15956
15957     /* allocate the host hardware/software hsi structures */
15958     if (bxe_alloc_hsi_mem(sc) != 0) {
15959         bxe_free_ilt_mem(sc);
15960         bxe_interrupt_free(sc);
15961         bxe_del_cdev(sc);
15962         if (sc->ifnet != NULL) {
15963             ether_ifdetach(sc->ifnet);
15964         }
15965         ifmedia_removeall(&sc->ifmedia);
15966         bxe_release_mutexes(sc);
15967         bxe_deallocate_bars(sc);
15968         pci_disable_busmaster(dev);
15969         return (ENXIO);
15970     }
15971
15972     /* need to reset chip if UNDI was active */
15973     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
15974         /* init fw_seq */
15975         sc->fw_seq =
15976             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
15977              DRV_MSG_SEQ_NUMBER_MASK);
15978         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
15979         bxe_prev_unload(sc);
15980     }
15981
15982 #if 1
15983     /* XXX */
15984     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15985 #else
15986     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
15987         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
15988         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
15989         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
15990         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
15991         bxe_dcbx_init_params(sc);
15992     } else {
15993         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15994     }
15995 #endif
15996
15997     /* calculate qm_cid_count */
15998     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
15999     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16000
16001     sc->max_cos = 1;
16002     bxe_init_multi_cos(sc);
16003
16004     bxe_add_sysctls(sc);
16005
16006     return (0);
16007 }
16008
16009 /*
16010  * Device detach function.
16011  *
16012  * Stops the controller, resets the controller, and releases resources.
16013  *
16014  * Returns:
16015  *   0 = Success, >0 = Failure
16016  */
16017 static int
16018 bxe_detach(device_t dev)
16019 {
16020     struct bxe_softc *sc;
16021     struct ifnet *ifp;
16022
16023     sc = device_get_softc(dev);
16024
16025     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16026
16027     ifp = sc->ifnet;
16028     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16029         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16030         return(EBUSY);
16031     }
16032
16033     bxe_del_cdev(sc);
16034
16035     /* stop the periodic callout */
16036     bxe_periodic_stop(sc);
16037
16038     /* stop the chip taskqueue */
16039     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16040     if (sc->chip_tq) {
16041         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16042         taskqueue_free(sc->chip_tq);
16043         sc->chip_tq = NULL;
16044     }
16045
16046     /* stop and reset the controller if it was open */
16047     if (sc->state != BXE_STATE_CLOSED) {
16048         BXE_CORE_LOCK(sc);
16049         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16050         BXE_CORE_UNLOCK(sc);
16051     }
16052
16053     /* release the network interface */
16054     if (ifp != NULL) {
16055         ether_ifdetach(ifp);
16056     }
16057     ifmedia_removeall(&sc->ifmedia);
16058
16059     /* XXX do the following based on driver state... */
16060
16061     /* free the host hardware/software hsi structures */
16062     bxe_free_hsi_mem(sc);
16063
16064     /* free ilt */
16065     bxe_free_ilt_mem(sc);
16066
16067     /* release the interrupts */
16068     bxe_interrupt_free(sc);
16069
16070     /* Release the mutexes*/
16071     bxe_release_mutexes(sc);
16072
16073     /* Release the PCIe BAR mapped memory */
16074     bxe_deallocate_bars(sc);
16075
16076     /* Release the FreeBSD interface. */
16077     if (sc->ifnet != NULL) {
16078         if_free(sc->ifnet);
16079     }
16080
16081     pci_disable_busmaster(dev);
16082
16083     return (0);
16084 }
16085
16086 /*
16087  * Device shutdown function.
16088  *
16089  * Stops and resets the controller.
16090  *
16091  * Returns:
16092  *   Nothing
16093  */
16094 static int
16095 bxe_shutdown(device_t dev)
16096 {
16097     struct bxe_softc *sc;
16098
16099     sc = device_get_softc(dev);
16100
16101     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16102
16103     /* stop the periodic callout */
16104     bxe_periodic_stop(sc);
16105
16106     BXE_CORE_LOCK(sc);
16107     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16108     BXE_CORE_UNLOCK(sc);
16109
16110     return (0);
16111 }
16112
16113 void
16114 bxe_igu_ack_sb(struct bxe_softc *sc,
16115                uint8_t          igu_sb_id,
16116                uint8_t          segment,
16117                uint16_t         index,
16118                uint8_t          op,
16119                uint8_t          update)
16120 {
16121     uint32_t igu_addr = sc->igu_base_addr;
16122     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16123     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16124 }
16125
16126 static void
16127 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16128                      uint8_t          func,
16129                      uint8_t          idu_sb_id,
16130                      uint8_t          is_pf)
16131 {
16132     uint32_t data, ctl, cnt = 100;
16133     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16134     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16135     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16136     uint32_t sb_bit =  1 << (idu_sb_id%32);
16137     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16138     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16139
16140     /* Not supported in BC mode */
16141     if (CHIP_INT_MODE_IS_BC(sc)) {
16142         return;
16143     }
16144
16145     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16146              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16147             IGU_REGULAR_CLEANUP_SET |
16148             IGU_REGULAR_BCLEANUP);
16149
16150     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16151            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16152            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16153
16154     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16155             data, igu_addr_data);
16156     REG_WR(sc, igu_addr_data, data);
16157
16158     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16159                       BUS_SPACE_BARRIER_WRITE);
16160     mb();
16161
16162     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16163             ctl, igu_addr_ctl);
16164     REG_WR(sc, igu_addr_ctl, ctl);
16165
16166     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16167                       BUS_SPACE_BARRIER_WRITE);
16168     mb();
16169
16170     /* wait for clean up to finish */
16171     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16172         DELAY(20000);
16173     }
16174
16175     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16176         BLOGD(sc, DBG_LOAD,
16177               "Unable to finish IGU cleanup: "
16178               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16179               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16180     }
16181 }
16182
16183 static void
16184 bxe_igu_clear_sb(struct bxe_softc *sc,
16185                  uint8_t          idu_sb_id)
16186 {
16187     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16188 }
16189
16190
16191
16192
16193
16194
16195
16196 /*******************/
16197 /* ECORE CALLBACKS */
16198 /*******************/
16199
16200 static void
16201 bxe_reset_common(struct bxe_softc *sc)
16202 {
16203     uint32_t val = 0x1400;
16204
16205     /* reset_common */
16206     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16207
16208     if (CHIP_IS_E3(sc)) {
16209         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16210         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16211     }
16212
16213     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16214 }
16215
16216 static void
16217 bxe_common_init_phy(struct bxe_softc *sc)
16218 {
16219     uint32_t shmem_base[2];
16220     uint32_t shmem2_base[2];
16221
16222     /* Avoid common init in case MFW supports LFA */
16223     if (SHMEM2_RD(sc, size) >
16224         (uint32_t)offsetof(struct shmem2_region,
16225                            lfa_host_addr[SC_PORT(sc)])) {
16226         return;
16227     }
16228
16229     shmem_base[0]  = sc->devinfo.shmem_base;
16230     shmem2_base[0] = sc->devinfo.shmem2_base;
16231
16232     if (!CHIP_IS_E1x(sc)) {
16233         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16234         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16235     }
16236
16237     bxe_acquire_phy_lock(sc);
16238     elink_common_init_phy(sc, shmem_base, shmem2_base,
16239                           sc->devinfo.chip_id, 0);
16240     bxe_release_phy_lock(sc);
16241 }
16242
16243 static void
16244 bxe_pf_disable(struct bxe_softc *sc)
16245 {
16246     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16247
16248     val &= ~IGU_PF_CONF_FUNC_EN;
16249
16250     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16251     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16252     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16253 }
16254
16255 static void
16256 bxe_init_pxp(struct bxe_softc *sc)
16257 {
16258     uint16_t devctl;
16259     int r_order, w_order;
16260
16261     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16262
16263     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16264
16265     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16266
16267     if (sc->mrrs == -1) {
16268         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16269     } else {
16270         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16271         r_order = sc->mrrs;
16272     }
16273
16274     ecore_init_pxp_arb(sc, r_order, w_order);
16275 }
16276
16277 static uint32_t
16278 bxe_get_pretend_reg(struct bxe_softc *sc)
16279 {
16280     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16281     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16282     return (base + (SC_ABS_FUNC(sc)) * stride);
16283 }
16284
16285 /*
16286  * Called only on E1H or E2.
16287  * When pretending to be PF, the pretend value is the function number 0..7.
16288  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16289  * combination.
16290  */
16291 static int
16292 bxe_pretend_func(struct bxe_softc *sc,
16293                  uint16_t         pretend_func_val)
16294 {
16295     uint32_t pretend_reg;
16296
16297     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16298         return (-1);
16299     }
16300
16301     /* get my own pretend register */
16302     pretend_reg = bxe_get_pretend_reg(sc);
16303     REG_WR(sc, pretend_reg, pretend_func_val);
16304     REG_RD(sc, pretend_reg);
16305     return (0);
16306 }
16307
16308 static void
16309 bxe_iov_init_dmae(struct bxe_softc *sc)
16310 {
16311     return;
16312 }
16313
16314 static void
16315 bxe_iov_init_dq(struct bxe_softc *sc)
16316 {
16317     return;
16318 }
16319
16320 /* send a NIG loopback debug packet */
16321 static void
16322 bxe_lb_pckt(struct bxe_softc *sc)
16323 {
16324     uint32_t wb_write[3];
16325
16326     /* Ethernet source and destination addresses */
16327     wb_write[0] = 0x55555555;
16328     wb_write[1] = 0x55555555;
16329     wb_write[2] = 0x20;     /* SOP */
16330     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16331
16332     /* NON-IP protocol */
16333     wb_write[0] = 0x09000000;
16334     wb_write[1] = 0x55555555;
16335     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16336     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16337 }
16338
16339 /*
16340  * Some of the internal memories are not directly readable from the driver.
16341  * To test them we send debug packets.
16342  */
16343 static int
16344 bxe_int_mem_test(struct bxe_softc *sc)
16345 {
16346     int factor;
16347     int count, i;
16348     uint32_t val = 0;
16349
16350     if (CHIP_REV_IS_FPGA(sc)) {
16351         factor = 120;
16352     } else if (CHIP_REV_IS_EMUL(sc)) {
16353         factor = 200;
16354     } else {
16355         factor = 1;
16356     }
16357
16358     /* disable inputs of parser neighbor blocks */
16359     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16360     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16361     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16362     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16363
16364     /*  write 0 to parser credits for CFC search request */
16365     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16366
16367     /* send Ethernet packet */
16368     bxe_lb_pckt(sc);
16369
16370     /* TODO do i reset NIG statistic? */
16371     /* Wait until NIG register shows 1 packet of size 0x10 */
16372     count = 1000 * factor;
16373     while (count) {
16374         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16375         val = *BXE_SP(sc, wb_data[0]);
16376         if (val == 0x10) {
16377             break;
16378         }
16379
16380         DELAY(10000);
16381         count--;
16382     }
16383
16384     if (val != 0x10) {
16385         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16386         return (-1);
16387     }
16388
16389     /* wait until PRS register shows 1 packet */
16390     count = (1000 * factor);
16391     while (count) {
16392         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16393         if (val == 1) {
16394             break;
16395         }
16396
16397         DELAY(10000);
16398         count--;
16399     }
16400
16401     if (val != 0x1) {
16402         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16403         return (-2);
16404     }
16405
16406     /* Reset and init BRB, PRS */
16407     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16408     DELAY(50000);
16409     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16410     DELAY(50000);
16411     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16412     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16413
16414     /* Disable inputs of parser neighbor blocks */
16415     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16416     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16417     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16418     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16419
16420     /* Write 0 to parser credits for CFC search request */
16421     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16422
16423     /* send 10 Ethernet packets */
16424     for (i = 0; i < 10; i++) {
16425         bxe_lb_pckt(sc);
16426     }
16427
16428     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16429     count = (1000 * factor);
16430     while (count) {
16431         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16432         val = *BXE_SP(sc, wb_data[0]);
16433         if (val == 0xb0) {
16434             break;
16435         }
16436
16437         DELAY(10000);
16438         count--;
16439     }
16440
16441     if (val != 0xb0) {
16442         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16443         return (-3);
16444     }
16445
16446     /* Wait until PRS register shows 2 packets */
16447     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16448     if (val != 2) {
16449         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16450     }
16451
16452     /* Write 1 to parser credits for CFC search request */
16453     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16454
16455     /* Wait until PRS register shows 3 packets */
16456     DELAY(10000 * factor);
16457
16458     /* Wait until NIG register shows 1 packet of size 0x10 */
16459     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16460     if (val != 3) {
16461         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16462     }
16463
16464     /* clear NIG EOP FIFO */
16465     for (i = 0; i < 11; i++) {
16466         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16467     }
16468
16469     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16470     if (val != 1) {
16471         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16472         return (-4);
16473     }
16474
16475     /* Reset and init BRB, PRS, NIG */
16476     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16477     DELAY(50000);
16478     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16479     DELAY(50000);
16480     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16481     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16482     if (!CNIC_SUPPORT(sc)) {
16483         /* set NIC mode */
16484         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16485     }
16486
16487     /* Enable inputs of parser neighbor blocks */
16488     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16489     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16490     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16491     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16492
16493     return (0);
16494 }
16495
16496 static void
16497 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16498 {
16499     int is_required;
16500     uint32_t val;
16501     int port;
16502
16503     is_required = 0;
16504     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16505            SHARED_HW_CFG_FAN_FAILURE_MASK);
16506
16507     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16508         is_required = 1;
16509     }
16510     /*
16511      * The fan failure mechanism is usually related to the PHY type since
16512      * the power consumption of the board is affected by the PHY. Currently,
16513      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16514      */
16515     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16516         for (port = PORT_0; port < PORT_MAX; port++) {
16517             is_required |= elink_fan_failure_det_req(sc,
16518                                                      sc->devinfo.shmem_base,
16519                                                      sc->devinfo.shmem2_base,
16520                                                      port);
16521         }
16522     }
16523
16524     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16525
16526     if (is_required == 0) {
16527         return;
16528     }
16529
16530     /* Fan failure is indicated by SPIO 5 */
16531     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16532
16533     /* set to active low mode */
16534     val = REG_RD(sc, MISC_REG_SPIO_INT);
16535     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16536     REG_WR(sc, MISC_REG_SPIO_INT, val);
16537
16538     /* enable interrupt to signal the IGU */
16539     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16540     val |= MISC_SPIO_SPIO5;
16541     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16542 }
16543
16544 static void
16545 bxe_enable_blocks_attention(struct bxe_softc *sc)
16546 {
16547     uint32_t val;
16548
16549     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16550     if (!CHIP_IS_E1x(sc)) {
16551         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16552     } else {
16553         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16554     }
16555     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16556     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16557     /*
16558      * mask read length error interrupts in brb for parser
16559      * (parsing unit and 'checksum and crc' unit)
16560      * these errors are legal (PU reads fixed length and CAC can cause
16561      * read length error on truncated packets)
16562      */
16563     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16564     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16565     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16566     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16567     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16568     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16569 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16570 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16571     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16572     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16573     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16574 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16575 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16576     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16577     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16578     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16579     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16580 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16581 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16582
16583     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16584            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16585            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16586     if (!CHIP_IS_E1x(sc)) {
16587         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16588                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16589     }
16590     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16591
16592     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16593     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16594     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16595 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16596
16597     if (!CHIP_IS_E1x(sc)) {
16598         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16599         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16600     }
16601
16602     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16603     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16604 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16605     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16606 }
16607
16608 /**
16609  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16610  *
16611  * @sc:     driver handle
16612  */
16613 static int
16614 bxe_init_hw_common(struct bxe_softc *sc)
16615 {
16616     uint8_t abs_func_id;
16617     uint32_t val;
16618
16619     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16620           SC_ABS_FUNC(sc));
16621
16622     /*
16623      * take the RESET lock to protect undi_unload flow from accessing
16624      * registers while we are resetting the chip
16625      */
16626     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16627
16628     bxe_reset_common(sc);
16629
16630     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16631
16632     val = 0xfffc;
16633     if (CHIP_IS_E3(sc)) {
16634         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16635         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16636     }
16637
16638     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16639
16640     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16641
16642     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16643     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16644
16645     if (!CHIP_IS_E1x(sc)) {
16646         /*
16647          * 4-port mode or 2-port mode we need to turn off master-enable for
16648          * everyone. After that we turn it back on for self. So, we disregard
16649          * multi-function, and always disable all functions on the given path,
16650          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16651          */
16652         for (abs_func_id = SC_PATH(sc);
16653              abs_func_id < (E2_FUNC_MAX * 2);
16654              abs_func_id += 2) {
16655             if (abs_func_id == SC_ABS_FUNC(sc)) {
16656                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16657                 continue;
16658             }
16659
16660             bxe_pretend_func(sc, abs_func_id);
16661
16662             /* clear pf enable */
16663             bxe_pf_disable(sc);
16664
16665             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16666         }
16667     }
16668
16669     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16670
16671     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16672
16673     if (CHIP_IS_E1(sc)) {
16674         /*
16675          * enable HW interrupt from PXP on USDM overflow
16676          * bit 16 on INT_MASK_0
16677          */
16678         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16679     }
16680
16681     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16682     bxe_init_pxp(sc);
16683
16684 #ifdef __BIG_ENDIAN
16685     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16686     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16687     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16688     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16689     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16690     /* make sure this value is 0 */
16691     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16692
16693     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16694     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16695     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16696     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16697     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16698 #endif
16699
16700     ecore_ilt_init_page_size(sc, INITOP_SET);
16701
16702     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16703         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16704     }
16705
16706     /* let the HW do it's magic... */
16707     DELAY(100000);
16708
16709     /* finish PXP init */
16710     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16711     if (val != 1) {
16712         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16713             val);
16714         return (-1);
16715     }
16716     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16717     if (val != 1) {
16718         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16719         return (-1);
16720     }
16721
16722     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16723
16724     /*
16725      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16726      * entries with value "0" and valid bit on. This needs to be done by the
16727      * first PF that is loaded in a path (i.e. common phase)
16728      */
16729     if (!CHIP_IS_E1x(sc)) {
16730 /*
16731  * In E2 there is a bug in the timers block that can cause function 6 / 7
16732  * (i.e. vnic3) to start even if it is marked as "scan-off".
16733  * This occurs when a different function (func2,3) is being marked
16734  * as "scan-off". Real-life scenario for example: if a driver is being
16735  * load-unloaded while func6,7 are down. This will cause the timer to access
16736  * the ilt, translate to a logical address and send a request to read/write.
16737  * Since the ilt for the function that is down is not valid, this will cause
16738  * a translation error which is unrecoverable.
16739  * The Workaround is intended to make sure that when this happens nothing
16740  * fatal will occur. The workaround:
16741  *  1.  First PF driver which loads on a path will:
16742  *      a.  After taking the chip out of reset, by using pretend,
16743  *          it will write "0" to the following registers of
16744  *          the other vnics.
16745  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16746  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16747  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16748  *          And for itself it will write '1' to
16749  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16750  *          dmae-operations (writing to pram for example.)
16751  *          note: can be done for only function 6,7 but cleaner this
16752  *            way.
16753  *      b.  Write zero+valid to the entire ILT.
16754  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16755  *          VNIC3 (of that port). The range allocated will be the
16756  *          entire ILT. This is needed to prevent  ILT range error.
16757  *  2.  Any PF driver load flow:
16758  *      a.  ILT update with the physical addresses of the allocated
16759  *          logical pages.
16760  *      b.  Wait 20msec. - note that this timeout is needed to make
16761  *          sure there are no requests in one of the PXP internal
16762  *          queues with "old" ILT addresses.
16763  *      c.  PF enable in the PGLC.
16764  *      d.  Clear the was_error of the PF in the PGLC. (could have
16765  *          occurred while driver was down)
16766  *      e.  PF enable in the CFC (WEAK + STRONG)
16767  *      f.  Timers scan enable
16768  *  3.  PF driver unload flow:
16769  *      a.  Clear the Timers scan_en.
16770  *      b.  Polling for scan_on=0 for that PF.
16771  *      c.  Clear the PF enable bit in the PXP.
16772  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16773  *      e.  Write zero+valid to all ILT entries (The valid bit must
16774  *          stay set)
16775  *      f.  If this is VNIC 3 of a port then also init
16776  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16777  *          to the last enrty in the ILT.
16778  *
16779  *      Notes:
16780  *      Currently the PF error in the PGLC is non recoverable.
16781  *      In the future the there will be a recovery routine for this error.
16782  *      Currently attention is masked.
16783  *      Having an MCP lock on the load/unload process does not guarantee that
16784  *      there is no Timer disable during Func6/7 enable. This is because the
16785  *      Timers scan is currently being cleared by the MCP on FLR.
16786  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16787  *      there is error before clearing it. But the flow above is simpler and
16788  *      more general.
16789  *      All ILT entries are written by zero+valid and not just PF6/7
16790  *      ILT entries since in the future the ILT entries allocation for
16791  *      PF-s might be dynamic.
16792  */
16793         struct ilt_client_info ilt_cli;
16794         struct ecore_ilt ilt;
16795
16796         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16797         memset(&ilt, 0, sizeof(struct ecore_ilt));
16798
16799         /* initialize dummy TM client */
16800         ilt_cli.start      = 0;
16801         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16802         ilt_cli.client_num = ILT_CLIENT_TM;
16803
16804         /*
16805          * Step 1: set zeroes to all ilt page entries with valid bit on
16806          * Step 2: set the timers first/last ilt entry to point
16807          * to the entire range to prevent ILT range error for 3rd/4th
16808          * vnic (this code assumes existence of the vnic)
16809          *
16810          * both steps performed by call to ecore_ilt_client_init_op()
16811          * with dummy TM client
16812          *
16813          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16814          * and his brother are split registers
16815          */
16816
16817         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16818         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16819         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16820
16821         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16822         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16823         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16824     }
16825
16826     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16827     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16828
16829     if (!CHIP_IS_E1x(sc)) {
16830         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16831                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16832
16833         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16834         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16835
16836         /* let the HW do it's magic... */
16837         do {
16838             DELAY(200000);
16839             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16840         } while (factor-- && (val != 1));
16841
16842         if (val != 1) {
16843             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16844             return (-1);
16845         }
16846     }
16847
16848     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16849
16850     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16851
16852     bxe_iov_init_dmae(sc);
16853
16854     /* clean the DMAE memory */
16855     sc->dmae_ready = 1;
16856     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16857
16858     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16859
16860     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16861
16862     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16863
16864     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16865
16866     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16867     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
16868     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
16869     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
16870
16871     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
16872
16873     /* QM queues pointers table */
16874     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
16875
16876     /* soft reset pulse */
16877     REG_WR(sc, QM_REG_SOFT_RESET, 1);
16878     REG_WR(sc, QM_REG_SOFT_RESET, 0);
16879
16880     if (CNIC_SUPPORT(sc))
16881         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
16882
16883     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
16884     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
16885     if (!CHIP_REV_IS_SLOW(sc)) {
16886         /* enable hw interrupt from doorbell Q */
16887         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16888     }
16889
16890     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16891
16892     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16893     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
16894
16895     if (!CHIP_IS_E1(sc)) {
16896         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
16897     }
16898
16899     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
16900         if (IS_MF_AFEX(sc)) {
16901             /*
16902              * configure that AFEX and VLAN headers must be
16903              * received in AFEX mode
16904              */
16905             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
16906             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
16907             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
16908             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
16909             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
16910         } else {
16911             /*
16912              * Bit-map indicating which L2 hdrs may appear
16913              * after the basic Ethernet header
16914              */
16915             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
16916                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16917         }
16918     }
16919
16920     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
16921     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
16922     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
16923     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
16924
16925     if (!CHIP_IS_E1x(sc)) {
16926         /* reset VFC memories */
16927         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16928                VFC_MEMORIES_RST_REG_CAM_RST |
16929                VFC_MEMORIES_RST_REG_RAM_RST);
16930         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16931                VFC_MEMORIES_RST_REG_CAM_RST |
16932                VFC_MEMORIES_RST_REG_RAM_RST);
16933
16934         DELAY(20000);
16935     }
16936
16937     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
16938     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
16939     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
16940     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
16941
16942     /* sync semi rtc */
16943     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
16944            0x80000000);
16945     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
16946            0x80000000);
16947
16948     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
16949     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
16950     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
16951
16952     if (!CHIP_IS_E1x(sc)) {
16953         if (IS_MF_AFEX(sc)) {
16954             /*
16955              * configure that AFEX and VLAN headers must be
16956              * sent in AFEX mode
16957              */
16958             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
16959             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
16960             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
16961             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
16962             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
16963         } else {
16964             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
16965                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16966         }
16967     }
16968
16969     REG_WR(sc, SRC_REG_SOFT_RST, 1);
16970
16971     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
16972
16973     if (CNIC_SUPPORT(sc)) {
16974         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
16975         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
16976         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
16977         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
16978         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
16979         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
16980         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
16981         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
16982         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
16983         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
16984     }
16985     REG_WR(sc, SRC_REG_SOFT_RST, 0);
16986
16987     if (sizeof(union cdu_context) != 1024) {
16988         /* we currently assume that a context is 1024 bytes */
16989         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
16990               (long)sizeof(union cdu_context));
16991     }
16992
16993     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
16994     val = (4 << 24) + (0 << 12) + 1024;
16995     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
16996
16997     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
16998
16999     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17000     /* enable context validation interrupt from CFC */
17001     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17002
17003     /* set the thresholds to prevent CFC/CDU race */
17004     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17005     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17006
17007     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17008         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17009     }
17010
17011     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17012     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17013
17014     /* Reset PCIE errors for debug */
17015     REG_WR(sc, 0x2814, 0xffffffff);
17016     REG_WR(sc, 0x3820, 0xffffffff);
17017
17018     if (!CHIP_IS_E1x(sc)) {
17019         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17020                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17021                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17022         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17023                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17024                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17025                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17026         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17027                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17028                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17029                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17030     }
17031
17032     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17033
17034     if (!CHIP_IS_E1(sc)) {
17035         /* in E3 this done in per-port section */
17036         if (!CHIP_IS_E3(sc))
17037             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17038     }
17039
17040     if (CHIP_IS_E1H(sc)) {
17041         /* not applicable for E2 (and above ...) */
17042         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17043     }
17044
17045     if (CHIP_REV_IS_SLOW(sc)) {
17046         DELAY(200000);
17047     }
17048
17049     /* finish CFC init */
17050     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17051     if (val != 1) {
17052         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17053         return (-1);
17054     }
17055     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17056     if (val != 1) {
17057         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17058         return (-1);
17059     }
17060     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17061     if (val != 1) {
17062         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17063         return (-1);
17064     }
17065     REG_WR(sc, CFC_REG_DEBUG0, 0);
17066
17067     if (CHIP_IS_E1(sc)) {
17068         /* read NIG statistic to see if this is our first up since powerup */
17069         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17070         val = *BXE_SP(sc, wb_data[0]);
17071
17072         /* do internal memory self test */
17073         if ((val == 0) && bxe_int_mem_test(sc)) {
17074             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17075             return (-1);
17076         }
17077     }
17078
17079     bxe_setup_fan_failure_detection(sc);
17080
17081     /* clear PXP2 attentions */
17082     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17083
17084     bxe_enable_blocks_attention(sc);
17085
17086     if (!CHIP_REV_IS_SLOW(sc)) {
17087         ecore_enable_blocks_parity(sc);
17088     }
17089
17090     if (!BXE_NOMCP(sc)) {
17091         if (CHIP_IS_E1x(sc)) {
17092             bxe_common_init_phy(sc);
17093         }
17094     }
17095
17096     return (0);
17097 }
17098
17099 /**
17100  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17101  *
17102  * @sc:     driver handle
17103  */
17104 static int
17105 bxe_init_hw_common_chip(struct bxe_softc *sc)
17106 {
17107     int rc = bxe_init_hw_common(sc);
17108
17109     if (rc) {
17110         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17111         return (rc);
17112     }
17113
17114     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17115     if (!BXE_NOMCP(sc)) {
17116         bxe_common_init_phy(sc);
17117     }
17118
17119     return (0);
17120 }
17121
17122 static int
17123 bxe_init_hw_port(struct bxe_softc *sc)
17124 {
17125     int port = SC_PORT(sc);
17126     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17127     uint32_t low, high;
17128     uint32_t val;
17129
17130     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17131
17132     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17133
17134     ecore_init_block(sc, BLOCK_MISC, init_phase);
17135     ecore_init_block(sc, BLOCK_PXP, init_phase);
17136     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17137
17138     /*
17139      * Timers bug workaround: disables the pf_master bit in pglue at
17140      * common phase, we need to enable it here before any dmae access are
17141      * attempted. Therefore we manually added the enable-master to the
17142      * port phase (it also happens in the function phase)
17143      */
17144     if (!CHIP_IS_E1x(sc)) {
17145         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17146     }
17147
17148     ecore_init_block(sc, BLOCK_ATC, init_phase);
17149     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17150     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17151     ecore_init_block(sc, BLOCK_QM, init_phase);
17152
17153     ecore_init_block(sc, BLOCK_TCM, init_phase);
17154     ecore_init_block(sc, BLOCK_UCM, init_phase);
17155     ecore_init_block(sc, BLOCK_CCM, init_phase);
17156     ecore_init_block(sc, BLOCK_XCM, init_phase);
17157
17158     /* QM cid (connection) count */
17159     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17160
17161     if (CNIC_SUPPORT(sc)) {
17162         ecore_init_block(sc, BLOCK_TM, init_phase);
17163         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17164         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17165     }
17166
17167     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17168
17169     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17170
17171     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17172         if (IS_MF(sc)) {
17173             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17174         } else if (sc->mtu > 4096) {
17175             if (BXE_ONE_PORT(sc)) {
17176                 low = 160;
17177             } else {
17178                 val = sc->mtu;
17179                 /* (24*1024 + val*4)/256 */
17180                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17181             }
17182         } else {
17183             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17184         }
17185         high = (low + 56); /* 14*1024/256 */
17186         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17187         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17188     }
17189
17190     if (CHIP_IS_MODE_4_PORT(sc)) {
17191         REG_WR(sc, SC_PORT(sc) ?
17192                BRB1_REG_MAC_GUARANTIED_1 :
17193                BRB1_REG_MAC_GUARANTIED_0, 40);
17194     }
17195
17196     ecore_init_block(sc, BLOCK_PRS, init_phase);
17197     if (CHIP_IS_E3B0(sc)) {
17198         if (IS_MF_AFEX(sc)) {
17199             /* configure headers for AFEX mode */
17200             REG_WR(sc, SC_PORT(sc) ?
17201                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17202                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17203             REG_WR(sc, SC_PORT(sc) ?
17204                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17205                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17206             REG_WR(sc, SC_PORT(sc) ?
17207                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17208                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17209         } else {
17210             /* Ovlan exists only if we are in multi-function +
17211              * switch-dependent mode, in switch-independent there
17212              * is no ovlan headers
17213              */
17214             REG_WR(sc, SC_PORT(sc) ?
17215                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17216                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17217                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17218         }
17219     }
17220
17221     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17222     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17223     ecore_init_block(sc, BLOCK_USDM, init_phase);
17224     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17225
17226     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17227     ecore_init_block(sc, BLOCK_USEM, init_phase);
17228     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17229     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17230
17231     ecore_init_block(sc, BLOCK_UPB, init_phase);
17232     ecore_init_block(sc, BLOCK_XPB, init_phase);
17233
17234     ecore_init_block(sc, BLOCK_PBF, init_phase);
17235
17236     if (CHIP_IS_E1x(sc)) {
17237         /* configure PBF to work without PAUSE mtu 9000 */
17238         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17239
17240         /* update threshold */
17241         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17242         /* update init credit */
17243         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17244
17245         /* probe changes */
17246         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17247         DELAY(50);
17248         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17249     }
17250
17251     if (CNIC_SUPPORT(sc)) {
17252         ecore_init_block(sc, BLOCK_SRC, init_phase);
17253     }
17254
17255     ecore_init_block(sc, BLOCK_CDU, init_phase);
17256     ecore_init_block(sc, BLOCK_CFC, init_phase);
17257
17258     if (CHIP_IS_E1(sc)) {
17259         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17260         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17261     }
17262     ecore_init_block(sc, BLOCK_HC, init_phase);
17263
17264     ecore_init_block(sc, BLOCK_IGU, init_phase);
17265
17266     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17267     /* init aeu_mask_attn_func_0/1:
17268      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17269      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17270      *             bits 4-7 are used for "per vn group attention" */
17271     val = IS_MF(sc) ? 0xF7 : 0x7;
17272     /* Enable DCBX attention for all but E1 */
17273     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17274     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17275
17276     ecore_init_block(sc, BLOCK_NIG, init_phase);
17277
17278     if (!CHIP_IS_E1x(sc)) {
17279         /* Bit-map indicating which L2 hdrs may appear after the
17280          * basic Ethernet header
17281          */
17282         if (IS_MF_AFEX(sc)) {
17283             REG_WR(sc, SC_PORT(sc) ?
17284                    NIG_REG_P1_HDRS_AFTER_BASIC :
17285                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17286         } else {
17287             REG_WR(sc, SC_PORT(sc) ?
17288                    NIG_REG_P1_HDRS_AFTER_BASIC :
17289                    NIG_REG_P0_HDRS_AFTER_BASIC,
17290                    IS_MF_SD(sc) ? 7 : 6);
17291         }
17292
17293         if (CHIP_IS_E3(sc)) {
17294             REG_WR(sc, SC_PORT(sc) ?
17295                    NIG_REG_LLH1_MF_MODE :
17296                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17297         }
17298     }
17299     if (!CHIP_IS_E3(sc)) {
17300         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17301     }
17302
17303     if (!CHIP_IS_E1(sc)) {
17304         /* 0x2 disable mf_ov, 0x1 enable */
17305         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17306                (IS_MF_SD(sc) ? 0x1 : 0x2));
17307
17308         if (!CHIP_IS_E1x(sc)) {
17309             val = 0;
17310             switch (sc->devinfo.mf_info.mf_mode) {
17311             case MULTI_FUNCTION_SD:
17312                 val = 1;
17313                 break;
17314             case MULTI_FUNCTION_SI:
17315             case MULTI_FUNCTION_AFEX:
17316                 val = 2;
17317                 break;
17318             }
17319
17320             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17321                         NIG_REG_LLH0_CLS_TYPE), val);
17322         }
17323         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17324         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17325         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17326     }
17327
17328     /* If SPIO5 is set to generate interrupts, enable it for this port */
17329     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17330     if (val & MISC_SPIO_SPIO5) {
17331         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17332                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17333         val = REG_RD(sc, reg_addr);
17334         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17335         REG_WR(sc, reg_addr, val);
17336     }
17337
17338     return (0);
17339 }
17340
17341 static uint32_t
17342 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17343                        uint32_t         reg,
17344                        uint32_t         expected,
17345                        uint32_t         poll_count)
17346 {
17347     uint32_t cur_cnt = poll_count;
17348     uint32_t val;
17349
17350     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17351         DELAY(FLR_WAIT_INTERVAL);
17352     }
17353
17354     return (val);
17355 }
17356
17357 static int
17358 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17359                               uint32_t         reg,
17360                               char             *msg,
17361                               uint32_t         poll_cnt)
17362 {
17363     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17364
17365     if (val != 0) {
17366         BLOGE(sc, "%s usage count=%d\n", msg, val);
17367         return (1);
17368     }
17369
17370     return (0);
17371 }
17372
17373 /* Common routines with VF FLR cleanup */
17374 static uint32_t
17375 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17376 {
17377     /* adjust polling timeout */
17378     if (CHIP_REV_IS_EMUL(sc)) {
17379         return (FLR_POLL_CNT * 2000);
17380     }
17381
17382     if (CHIP_REV_IS_FPGA(sc)) {
17383         return (FLR_POLL_CNT * 120);
17384     }
17385
17386     return (FLR_POLL_CNT);
17387 }
17388
17389 static int
17390 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17391                            uint32_t         poll_cnt)
17392 {
17393     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17394     if (bxe_flr_clnup_poll_hw_counter(sc,
17395                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17396                                       "CFC PF usage counter timed out",
17397                                       poll_cnt)) {
17398         return (1);
17399     }
17400
17401     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17402     if (bxe_flr_clnup_poll_hw_counter(sc,
17403                                       DORQ_REG_PF_USAGE_CNT,
17404                                       "DQ PF usage counter timed out",
17405                                       poll_cnt)) {
17406         return (1);
17407     }
17408
17409     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17410     if (bxe_flr_clnup_poll_hw_counter(sc,
17411                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17412                                       "QM PF usage counter timed out",
17413                                       poll_cnt)) {
17414         return (1);
17415     }
17416
17417     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17418     if (bxe_flr_clnup_poll_hw_counter(sc,
17419                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17420                                       "Timers VNIC usage counter timed out",
17421                                       poll_cnt)) {
17422         return (1);
17423     }
17424
17425     if (bxe_flr_clnup_poll_hw_counter(sc,
17426                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17427                                       "Timers NUM_SCANS usage counter timed out",
17428                                       poll_cnt)) {
17429         return (1);
17430     }
17431
17432     /* Wait DMAE PF usage counter to zero */
17433     if (bxe_flr_clnup_poll_hw_counter(sc,
17434                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17435                                       "DMAE dommand register timed out",
17436                                       poll_cnt)) {
17437         return (1);
17438     }
17439
17440     return (0);
17441 }
17442
17443 #define OP_GEN_PARAM(param)                                            \
17444     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17445 #define OP_GEN_TYPE(type)                                           \
17446     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17447 #define OP_GEN_AGG_VECT(index)                                             \
17448     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17449
17450 static int
17451 bxe_send_final_clnup(struct bxe_softc *sc,
17452                      uint8_t          clnup_func,
17453                      uint32_t         poll_cnt)
17454 {
17455     uint32_t op_gen_command = 0;
17456     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17457                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17458     int ret = 0;
17459
17460     if (REG_RD(sc, comp_addr)) {
17461         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17462         return (1);
17463     }
17464
17465     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17466     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17467     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17468     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17469
17470     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17471     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17472
17473     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17474         BLOGE(sc, "FW final cleanup did not succeed\n");
17475         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17476               (REG_RD(sc, comp_addr)));
17477         bxe_panic(sc, ("FLR cleanup failed\n"));
17478         return (1);
17479     }
17480
17481     /* Zero completion for nxt FLR */
17482     REG_WR(sc, comp_addr, 0);
17483
17484     return (ret);
17485 }
17486
17487 static void
17488 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17489                        struct pbf_pN_buf_regs *regs,
17490                        uint32_t               poll_count)
17491 {
17492     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17493     uint32_t cur_cnt = poll_count;
17494
17495     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17496     crd = crd_start = REG_RD(sc, regs->crd);
17497     init_crd = REG_RD(sc, regs->init_crd);
17498
17499     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17500     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17501     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17502
17503     while ((crd != init_crd) &&
17504            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17505             (init_crd - crd_start))) {
17506         if (cur_cnt--) {
17507             DELAY(FLR_WAIT_INTERVAL);
17508             crd = REG_RD(sc, regs->crd);
17509             crd_freed = REG_RD(sc, regs->crd_freed);
17510         } else {
17511             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17512             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17513             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17514             break;
17515         }
17516     }
17517
17518     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17519           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17520 }
17521
17522 static void
17523 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17524                        struct pbf_pN_cmd_regs *regs,
17525                        uint32_t               poll_count)
17526 {
17527     uint32_t occup, to_free, freed, freed_start;
17528     uint32_t cur_cnt = poll_count;
17529
17530     occup = to_free = REG_RD(sc, regs->lines_occup);
17531     freed = freed_start = REG_RD(sc, regs->lines_freed);
17532
17533     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17534     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17535
17536     while (occup &&
17537            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17538         if (cur_cnt--) {
17539             DELAY(FLR_WAIT_INTERVAL);
17540             occup = REG_RD(sc, regs->lines_occup);
17541             freed = REG_RD(sc, regs->lines_freed);
17542         } else {
17543             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17544             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17545             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17546             break;
17547         }
17548     }
17549
17550     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17551           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17552 }
17553
17554 static void
17555 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17556 {
17557     struct pbf_pN_cmd_regs cmd_regs[] = {
17558         {0, (CHIP_IS_E3B0(sc)) ?
17559             PBF_REG_TQ_OCCUPANCY_Q0 :
17560             PBF_REG_P0_TQ_OCCUPANCY,
17561             (CHIP_IS_E3B0(sc)) ?
17562             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17563             PBF_REG_P0_TQ_LINES_FREED_CNT},
17564         {1, (CHIP_IS_E3B0(sc)) ?
17565             PBF_REG_TQ_OCCUPANCY_Q1 :
17566             PBF_REG_P1_TQ_OCCUPANCY,
17567             (CHIP_IS_E3B0(sc)) ?
17568             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17569             PBF_REG_P1_TQ_LINES_FREED_CNT},
17570         {4, (CHIP_IS_E3B0(sc)) ?
17571             PBF_REG_TQ_OCCUPANCY_LB_Q :
17572             PBF_REG_P4_TQ_OCCUPANCY,
17573             (CHIP_IS_E3B0(sc)) ?
17574             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17575             PBF_REG_P4_TQ_LINES_FREED_CNT}
17576     };
17577
17578     struct pbf_pN_buf_regs buf_regs[] = {
17579         {0, (CHIP_IS_E3B0(sc)) ?
17580             PBF_REG_INIT_CRD_Q0 :
17581             PBF_REG_P0_INIT_CRD ,
17582             (CHIP_IS_E3B0(sc)) ?
17583             PBF_REG_CREDIT_Q0 :
17584             PBF_REG_P0_CREDIT,
17585             (CHIP_IS_E3B0(sc)) ?
17586             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17587             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17588         {1, (CHIP_IS_E3B0(sc)) ?
17589             PBF_REG_INIT_CRD_Q1 :
17590             PBF_REG_P1_INIT_CRD,
17591             (CHIP_IS_E3B0(sc)) ?
17592             PBF_REG_CREDIT_Q1 :
17593             PBF_REG_P1_CREDIT,
17594             (CHIP_IS_E3B0(sc)) ?
17595             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17596             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17597         {4, (CHIP_IS_E3B0(sc)) ?
17598             PBF_REG_INIT_CRD_LB_Q :
17599             PBF_REG_P4_INIT_CRD,
17600             (CHIP_IS_E3B0(sc)) ?
17601             PBF_REG_CREDIT_LB_Q :
17602             PBF_REG_P4_CREDIT,
17603             (CHIP_IS_E3B0(sc)) ?
17604             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17605             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17606     };
17607
17608     int i;
17609
17610     /* Verify the command queues are flushed P0, P1, P4 */
17611     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17612         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17613     }
17614
17615     /* Verify the transmission buffers are flushed P0, P1, P4 */
17616     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17617         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17618     }
17619 }
17620
17621 static void
17622 bxe_hw_enable_status(struct bxe_softc *sc)
17623 {
17624     uint32_t val;
17625
17626     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17627     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17628
17629     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17630     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17631
17632     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17633     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17634
17635     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17636     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17637
17638     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17639     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17640
17641     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17642     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17643
17644     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17645     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17646
17647     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17648     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17649 }
17650
17651 static int
17652 bxe_pf_flr_clnup(struct bxe_softc *sc)
17653 {
17654     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17655
17656     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17657
17658     /* Re-enable PF target read access */
17659     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17660
17661     /* Poll HW usage counters */
17662     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17663     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17664         return (-1);
17665     }
17666
17667     /* Zero the igu 'trailing edge' and 'leading edge' */
17668
17669     /* Send the FW cleanup command */
17670     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17671         return (-1);
17672     }
17673
17674     /* ATC cleanup */
17675
17676     /* Verify TX hw is flushed */
17677     bxe_tx_hw_flushed(sc, poll_cnt);
17678
17679     /* Wait 100ms (not adjusted according to platform) */
17680     DELAY(100000);
17681
17682     /* Verify no pending pci transactions */
17683     if (bxe_is_pcie_pending(sc)) {
17684         BLOGE(sc, "PCIE Transactions still pending\n");
17685     }
17686
17687     /* Debug */
17688     bxe_hw_enable_status(sc);
17689
17690     /*
17691      * Master enable - Due to WB DMAE writes performed before this
17692      * register is re-initialized as part of the regular function init
17693      */
17694     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17695
17696     return (0);
17697 }
17698
17699 static int
17700 bxe_init_hw_func(struct bxe_softc *sc)
17701 {
17702     int port = SC_PORT(sc);
17703     int func = SC_FUNC(sc);
17704     int init_phase = PHASE_PF0 + func;
17705     struct ecore_ilt *ilt = sc->ilt;
17706     uint16_t cdu_ilt_start;
17707     uint32_t addr, val;
17708     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17709     int i, main_mem_width, rc;
17710
17711     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17712
17713     /* FLR cleanup */
17714     if (!CHIP_IS_E1x(sc)) {
17715         rc = bxe_pf_flr_clnup(sc);
17716         if (rc) {
17717             BLOGE(sc, "FLR cleanup failed!\n");
17718             // XXX bxe_fw_dump(sc);
17719             // XXX bxe_idle_chk(sc);
17720             return (rc);
17721         }
17722     }
17723
17724     /* set MSI reconfigure capability */
17725     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17726         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17727         val = REG_RD(sc, addr);
17728         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17729         REG_WR(sc, addr, val);
17730     }
17731
17732     ecore_init_block(sc, BLOCK_PXP, init_phase);
17733     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17734
17735     ilt = sc->ilt;
17736     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17737
17738     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17739         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17740         ilt->lines[cdu_ilt_start + i].page_mapping =
17741             sc->context[i].vcxt_dma.paddr;
17742         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17743     }
17744     ecore_ilt_init_op(sc, INITOP_SET);
17745
17746     /* Set NIC mode */
17747     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17748     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17749
17750     if (!CHIP_IS_E1x(sc)) {
17751         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17752
17753         /* Turn on a single ISR mode in IGU if driver is going to use
17754          * INT#x or MSI
17755          */
17756         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17757             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17758         }
17759
17760         /*
17761          * Timers workaround bug: function init part.
17762          * Need to wait 20msec after initializing ILT,
17763          * needed to make sure there are no requests in
17764          * one of the PXP internal queues with "old" ILT addresses
17765          */
17766         DELAY(20000);
17767
17768         /*
17769          * Master enable - Due to WB DMAE writes performed before this
17770          * register is re-initialized as part of the regular function
17771          * init
17772          */
17773         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17774         /* Enable the function in IGU */
17775         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17776     }
17777
17778     sc->dmae_ready = 1;
17779
17780     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17781
17782     if (!CHIP_IS_E1x(sc))
17783         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17784
17785     ecore_init_block(sc, BLOCK_ATC, init_phase);
17786     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17787     ecore_init_block(sc, BLOCK_NIG, init_phase);
17788     ecore_init_block(sc, BLOCK_SRC, init_phase);
17789     ecore_init_block(sc, BLOCK_MISC, init_phase);
17790     ecore_init_block(sc, BLOCK_TCM, init_phase);
17791     ecore_init_block(sc, BLOCK_UCM, init_phase);
17792     ecore_init_block(sc, BLOCK_CCM, init_phase);
17793     ecore_init_block(sc, BLOCK_XCM, init_phase);
17794     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17795     ecore_init_block(sc, BLOCK_USEM, init_phase);
17796     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17797     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17798
17799     if (!CHIP_IS_E1x(sc))
17800         REG_WR(sc, QM_REG_PF_EN, 1);
17801
17802     if (!CHIP_IS_E1x(sc)) {
17803         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17804         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17805         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17806         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17807     }
17808     ecore_init_block(sc, BLOCK_QM, init_phase);
17809
17810     ecore_init_block(sc, BLOCK_TM, init_phase);
17811     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17812
17813     bxe_iov_init_dq(sc);
17814
17815     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17816     ecore_init_block(sc, BLOCK_PRS, init_phase);
17817     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17818     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17819     ecore_init_block(sc, BLOCK_USDM, init_phase);
17820     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17821     ecore_init_block(sc, BLOCK_UPB, init_phase);
17822     ecore_init_block(sc, BLOCK_XPB, init_phase);
17823     ecore_init_block(sc, BLOCK_PBF, init_phase);
17824     if (!CHIP_IS_E1x(sc))
17825         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17826
17827     ecore_init_block(sc, BLOCK_CDU, init_phase);
17828
17829     ecore_init_block(sc, BLOCK_CFC, init_phase);
17830
17831     if (!CHIP_IS_E1x(sc))
17832         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17833
17834     if (IS_MF(sc)) {
17835         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17836         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17837     }
17838
17839     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17840
17841     /* HC init per function */
17842     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17843         if (CHIP_IS_E1H(sc)) {
17844             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17845
17846             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17847             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17848         }
17849         ecore_init_block(sc, BLOCK_HC, init_phase);
17850
17851     } else {
17852         int num_segs, sb_idx, prod_offset;
17853
17854         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17855
17856         if (!CHIP_IS_E1x(sc)) {
17857             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17858             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17859         }
17860
17861         ecore_init_block(sc, BLOCK_IGU, init_phase);
17862
17863         if (!CHIP_IS_E1x(sc)) {
17864             int dsb_idx = 0;
17865             /**
17866              * Producer memory:
17867              * E2 mode: address 0-135 match to the mapping memory;
17868              * 136 - PF0 default prod; 137 - PF1 default prod;
17869              * 138 - PF2 default prod; 139 - PF3 default prod;
17870              * 140 - PF0 attn prod;    141 - PF1 attn prod;
17871              * 142 - PF2 attn prod;    143 - PF3 attn prod;
17872              * 144-147 reserved.
17873              *
17874              * E1.5 mode - In backward compatible mode;
17875              * for non default SB; each even line in the memory
17876              * holds the U producer and each odd line hold
17877              * the C producer. The first 128 producers are for
17878              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
17879              * producers are for the DSB for each PF.
17880              * Each PF has five segments: (the order inside each
17881              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
17882              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
17883              * 144-147 attn prods;
17884              */
17885             /* non-default-status-blocks */
17886             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17887                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
17888             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
17889                 prod_offset = (sc->igu_base_sb + sb_idx) *
17890                     num_segs;
17891
17892                 for (i = 0; i < num_segs; i++) {
17893                     addr = IGU_REG_PROD_CONS_MEMORY +
17894                             (prod_offset + i) * 4;
17895                     REG_WR(sc, addr, 0);
17896                 }
17897                 /* send consumer update with value 0 */
17898                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
17899                            USTORM_ID, 0, IGU_INT_NOP, 1);
17900                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
17901             }
17902
17903             /* default-status-blocks */
17904             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17905                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
17906
17907             if (CHIP_IS_MODE_4_PORT(sc))
17908                 dsb_idx = SC_FUNC(sc);
17909             else
17910                 dsb_idx = SC_VN(sc);
17911
17912             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
17913                        IGU_BC_BASE_DSB_PROD + dsb_idx :
17914                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
17915
17916             /*
17917              * igu prods come in chunks of E1HVN_MAX (4) -
17918              * does not matters what is the current chip mode
17919              */
17920             for (i = 0; i < (num_segs * E1HVN_MAX);
17921                  i += E1HVN_MAX) {
17922                 addr = IGU_REG_PROD_CONS_MEMORY +
17923                             (prod_offset + i)*4;
17924                 REG_WR(sc, addr, 0);
17925             }
17926             /* send consumer update with 0 */
17927             if (CHIP_INT_MODE_IS_BC(sc)) {
17928                 bxe_ack_sb(sc, sc->igu_dsb_id,
17929                            USTORM_ID, 0, IGU_INT_NOP, 1);
17930                 bxe_ack_sb(sc, sc->igu_dsb_id,
17931                            CSTORM_ID, 0, IGU_INT_NOP, 1);
17932                 bxe_ack_sb(sc, sc->igu_dsb_id,
17933                            XSTORM_ID, 0, IGU_INT_NOP, 1);
17934                 bxe_ack_sb(sc, sc->igu_dsb_id,
17935                            TSTORM_ID, 0, IGU_INT_NOP, 1);
17936                 bxe_ack_sb(sc, sc->igu_dsb_id,
17937                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17938             } else {
17939                 bxe_ack_sb(sc, sc->igu_dsb_id,
17940                            USTORM_ID, 0, IGU_INT_NOP, 1);
17941                 bxe_ack_sb(sc, sc->igu_dsb_id,
17942                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17943             }
17944             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
17945
17946             /* !!! these should become driver const once
17947                rf-tool supports split-68 const */
17948             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
17949             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
17950             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
17951             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
17952             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
17953             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
17954         }
17955     }
17956
17957     /* Reset PCIE errors for debug */
17958     REG_WR(sc, 0x2114, 0xffffffff);
17959     REG_WR(sc, 0x2120, 0xffffffff);
17960
17961     if (CHIP_IS_E1x(sc)) {
17962         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
17963         main_mem_base = HC_REG_MAIN_MEMORY +
17964                 SC_PORT(sc) * (main_mem_size * 4);
17965         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
17966         main_mem_width = 8;
17967
17968         val = REG_RD(sc, main_mem_prty_clr);
17969         if (val) {
17970             BLOGD(sc, DBG_LOAD,
17971                   "Parity errors in HC block during function init (0x%x)!\n",
17972                   val);
17973         }
17974
17975         /* Clear "false" parity errors in MSI-X table */
17976         for (i = main_mem_base;
17977              i < main_mem_base + main_mem_size * 4;
17978              i += main_mem_width) {
17979             bxe_read_dmae(sc, i, main_mem_width / 4);
17980             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
17981                            i, main_mem_width / 4);
17982         }
17983         /* Clear HC parity attention */
17984         REG_RD(sc, main_mem_prty_clr);
17985     }
17986
17987 #if 1
17988     /* Enable STORMs SP logging */
17989     REG_WR8(sc, BAR_USTRORM_INTMEM +
17990            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17991     REG_WR8(sc, BAR_TSTRORM_INTMEM +
17992            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17993     REG_WR8(sc, BAR_CSTRORM_INTMEM +
17994            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17995     REG_WR8(sc, BAR_XSTRORM_INTMEM +
17996            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
17997 #endif
17998
17999     elink_phy_probe(&sc->link_params);
18000
18001     return (0);
18002 }
18003
18004 static void
18005 bxe_link_reset(struct bxe_softc *sc)
18006 {
18007     if (!BXE_NOMCP(sc)) {
18008         bxe_acquire_phy_lock(sc);
18009         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18010         bxe_release_phy_lock(sc);
18011     } else {
18012         if (!CHIP_REV_IS_SLOW(sc)) {
18013             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18014         }
18015     }
18016 }
18017
18018 static void
18019 bxe_reset_port(struct bxe_softc *sc)
18020 {
18021     int port = SC_PORT(sc);
18022     uint32_t val;
18023
18024     /* reset physical Link */
18025     bxe_link_reset(sc);
18026
18027     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18028
18029     /* Do not rcv packets to BRB */
18030     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18031     /* Do not direct rcv packets that are not for MCP to the BRB */
18032     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18033                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18034
18035     /* Configure AEU */
18036     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18037
18038     DELAY(100000);
18039
18040     /* Check for BRB port occupancy */
18041     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18042     if (val) {
18043         BLOGD(sc, DBG_LOAD,
18044               "BRB1 is not empty, %d blocks are occupied\n", val);
18045     }
18046
18047     /* TODO: Close Doorbell port? */
18048 }
18049
18050 static void
18051 bxe_ilt_wr(struct bxe_softc *sc,
18052            uint32_t         index,
18053            bus_addr_t       addr)
18054 {
18055     int reg;
18056     uint32_t wb_write[2];
18057
18058     if (CHIP_IS_E1(sc)) {
18059         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18060     } else {
18061         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18062     }
18063
18064     wb_write[0] = ONCHIP_ADDR1(addr);
18065     wb_write[1] = ONCHIP_ADDR2(addr);
18066     REG_WR_DMAE(sc, reg, wb_write, 2);
18067 }
18068
18069 static void
18070 bxe_clear_func_ilt(struct bxe_softc *sc,
18071                    uint32_t         func)
18072 {
18073     uint32_t i, base = FUNC_ILT_BASE(func);
18074     for (i = base; i < base + ILT_PER_FUNC; i++) {
18075         bxe_ilt_wr(sc, i, 0);
18076     }
18077 }
18078
18079 static void
18080 bxe_reset_func(struct bxe_softc *sc)
18081 {
18082     struct bxe_fastpath *fp;
18083     int port = SC_PORT(sc);
18084     int func = SC_FUNC(sc);
18085     int i;
18086
18087     /* Disable the function in the FW */
18088     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18089     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18090     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18091     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18092
18093     /* FP SBs */
18094     FOR_EACH_ETH_QUEUE(sc, i) {
18095         fp = &sc->fp[i];
18096         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18097                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18098                 SB_DISABLED);
18099     }
18100
18101     /* SP SB */
18102     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18103             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18104             SB_DISABLED);
18105
18106     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18107         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18108     }
18109
18110     /* Configure IGU */
18111     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18112         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18113         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18114     } else {
18115         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18116         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18117     }
18118
18119     if (CNIC_LOADED(sc)) {
18120         /* Disable Timer scan */
18121         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18122         /*
18123          * Wait for at least 10ms and up to 2 second for the timers
18124          * scan to complete
18125          */
18126         for (i = 0; i < 200; i++) {
18127             DELAY(10000);
18128             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18129                 break;
18130         }
18131     }
18132
18133     /* Clear ILT */
18134     bxe_clear_func_ilt(sc, func);
18135
18136     /*
18137      * Timers workaround bug for E2: if this is vnic-3,
18138      * we need to set the entire ilt range for this timers.
18139      */
18140     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18141         struct ilt_client_info ilt_cli;
18142         /* use dummy TM client */
18143         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18144         ilt_cli.start = 0;
18145         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18146         ilt_cli.client_num = ILT_CLIENT_TM;
18147
18148         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18149     }
18150
18151     /* this assumes that reset_port() called before reset_func()*/
18152     if (!CHIP_IS_E1x(sc)) {
18153         bxe_pf_disable(sc);
18154     }
18155
18156     sc->dmae_ready = 0;
18157 }
18158
18159 static int
18160 bxe_gunzip_init(struct bxe_softc *sc)
18161 {
18162     return (0);
18163 }
18164
18165 static void
18166 bxe_gunzip_end(struct bxe_softc *sc)
18167 {
18168     return;
18169 }
18170
18171 static int
18172 bxe_init_firmware(struct bxe_softc *sc)
18173 {
18174     if (CHIP_IS_E1(sc)) {
18175         ecore_init_e1_firmware(sc);
18176         sc->iro_array = e1_iro_arr;
18177     } else if (CHIP_IS_E1H(sc)) {
18178         ecore_init_e1h_firmware(sc);
18179         sc->iro_array = e1h_iro_arr;
18180     } else if (!CHIP_IS_E1x(sc)) {
18181         ecore_init_e2_firmware(sc);
18182         sc->iro_array = e2_iro_arr;
18183     } else {
18184         BLOGE(sc, "Unsupported chip revision\n");
18185         return (-1);
18186     }
18187
18188     return (0);
18189 }
18190
18191 static void
18192 bxe_release_firmware(struct bxe_softc *sc)
18193 {
18194     /* Do nothing */
18195     return;
18196 }
18197
18198 static int
18199 ecore_gunzip(struct bxe_softc *sc,
18200              const uint8_t    *zbuf,
18201              int              len)
18202 {
18203     /* XXX : Implement... */
18204     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18205     return (FALSE);
18206 }
18207
18208 static void
18209 ecore_reg_wr_ind(struct bxe_softc *sc,
18210                  uint32_t         addr,
18211                  uint32_t         val)
18212 {
18213     bxe_reg_wr_ind(sc, addr, val);
18214 }
18215
18216 static void
18217 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18218                           bus_addr_t       phys_addr,
18219                           uint32_t         addr,
18220                           uint32_t         len)
18221 {
18222     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18223 }
18224
18225 void
18226 ecore_storm_memset_struct(struct bxe_softc *sc,
18227                           uint32_t         addr,
18228                           size_t           size,
18229                           uint32_t         *data)
18230 {
18231     uint8_t i;
18232     for (i = 0; i < size/4; i++) {
18233         REG_WR(sc, addr + (i * 4), data[i]);
18234     }
18235 }
18236
18237
18238 /*
18239  * character device - ioctl interface definitions
18240  */
18241
18242
18243 #include "bxe_dump.h"
18244 #include "bxe_ioctl.h"
18245 #include <sys/conf.h>
18246
18247 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18248                 struct thread *td);
18249
18250 static struct cdevsw bxe_cdevsw = {
18251     .d_version = D_VERSION,
18252     .d_ioctl = bxe_eioctl,
18253     .d_name = "bxecnic",
18254 };
18255
18256 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18257
18258
18259 #define DUMP_ALL_PRESETS        0x1FFF
18260 #define DUMP_MAX_PRESETS        13
18261 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18262 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18263 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18264 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18265 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18266
18267 #define IS_REG_IN_PRESET(presets, idx)  \
18268                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18269
18270
18271 static int
18272 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18273 {
18274     if (CHIP_IS_E1(sc))
18275         return dump_num_registers[0][preset-1];
18276     else if (CHIP_IS_E1H(sc))
18277         return dump_num_registers[1][preset-1];
18278     else if (CHIP_IS_E2(sc))
18279         return dump_num_registers[2][preset-1];
18280     else if (CHIP_IS_E3A0(sc))
18281         return dump_num_registers[3][preset-1];
18282     else if (CHIP_IS_E3B0(sc))
18283         return dump_num_registers[4][preset-1];
18284     else
18285         return 0;
18286 }
18287
18288 static int
18289 bxe_get_total_regs_len32(struct bxe_softc *sc)
18290 {
18291     uint32_t preset_idx;
18292     int regdump_len32 = 0;
18293
18294
18295     /* Calculate the total preset regs length */
18296     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18297         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18298     }
18299
18300     return regdump_len32;
18301 }
18302
18303 static const uint32_t *
18304 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18305 {
18306     if (CHIP_IS_E2(sc))
18307         return page_vals_e2;
18308     else if (CHIP_IS_E3(sc))
18309         return page_vals_e3;
18310     else
18311         return NULL;
18312 }
18313
18314 static uint32_t
18315 __bxe_get_page_reg_num(struct bxe_softc *sc)
18316 {
18317     if (CHIP_IS_E2(sc))
18318         return PAGE_MODE_VALUES_E2;
18319     else if (CHIP_IS_E3(sc))
18320         return PAGE_MODE_VALUES_E3;
18321     else
18322         return 0;
18323 }
18324
18325 static const uint32_t *
18326 __bxe_get_page_write_ar(struct bxe_softc *sc)
18327 {
18328     if (CHIP_IS_E2(sc))
18329         return page_write_regs_e2;
18330     else if (CHIP_IS_E3(sc))
18331         return page_write_regs_e3;
18332     else
18333         return NULL;
18334 }
18335
18336 static uint32_t
18337 __bxe_get_page_write_num(struct bxe_softc *sc)
18338 {
18339     if (CHIP_IS_E2(sc))
18340         return PAGE_WRITE_REGS_E2;
18341     else if (CHIP_IS_E3(sc))
18342         return PAGE_WRITE_REGS_E3;
18343     else
18344         return 0;
18345 }
18346
18347 static const struct reg_addr *
18348 __bxe_get_page_read_ar(struct bxe_softc *sc)
18349 {
18350     if (CHIP_IS_E2(sc))
18351         return page_read_regs_e2;
18352     else if (CHIP_IS_E3(sc))
18353         return page_read_regs_e3;
18354     else
18355         return NULL;
18356 }
18357
18358 static uint32_t
18359 __bxe_get_page_read_num(struct bxe_softc *sc)
18360 {
18361     if (CHIP_IS_E2(sc))
18362         return PAGE_READ_REGS_E2;
18363     else if (CHIP_IS_E3(sc))
18364         return PAGE_READ_REGS_E3;
18365     else
18366         return 0;
18367 }
18368
18369 static bool
18370 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18371 {
18372     if (CHIP_IS_E1(sc))
18373         return IS_E1_REG(reg_info->chips);
18374     else if (CHIP_IS_E1H(sc))
18375         return IS_E1H_REG(reg_info->chips);
18376     else if (CHIP_IS_E2(sc))
18377         return IS_E2_REG(reg_info->chips);
18378     else if (CHIP_IS_E3A0(sc))
18379         return IS_E3A0_REG(reg_info->chips);
18380     else if (CHIP_IS_E3B0(sc))
18381         return IS_E3B0_REG(reg_info->chips);
18382     else
18383         return 0;
18384 }
18385
18386 static bool
18387 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18388 {
18389     if (CHIP_IS_E1(sc))
18390         return IS_E1_REG(wreg_info->chips);
18391     else if (CHIP_IS_E1H(sc))
18392         return IS_E1H_REG(wreg_info->chips);
18393     else if (CHIP_IS_E2(sc))
18394         return IS_E2_REG(wreg_info->chips);
18395     else if (CHIP_IS_E3A0(sc))
18396         return IS_E3A0_REG(wreg_info->chips);
18397     else if (CHIP_IS_E3B0(sc))
18398         return IS_E3B0_REG(wreg_info->chips);
18399     else
18400         return 0;
18401 }
18402
18403 /**
18404  * bxe_read_pages_regs - read "paged" registers
18405  *
18406  * @bp          device handle
18407  * @p           output buffer
18408  *
18409  * Reads "paged" memories: memories that may only be read by first writing to a
18410  * specific address ("write address") and then reading from a specific address
18411  * ("read address"). There may be more than one write address per "page" and
18412  * more than one read address per write address.
18413  */
18414 static void
18415 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18416 {
18417     uint32_t i, j, k, n;
18418
18419     /* addresses of the paged registers */
18420     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18421     /* number of paged registers */
18422     int num_pages = __bxe_get_page_reg_num(sc);
18423     /* write addresses */
18424     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18425     /* number of write addresses */
18426     int write_num = __bxe_get_page_write_num(sc);
18427     /* read addresses info */
18428     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18429     /* number of read addresses */
18430     int read_num = __bxe_get_page_read_num(sc);
18431     uint32_t addr, size;
18432
18433     for (i = 0; i < num_pages; i++) {
18434         for (j = 0; j < write_num; j++) {
18435             REG_WR(sc, write_addr[j], page_addr[i]);
18436
18437             for (k = 0; k < read_num; k++) {
18438                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18439                     size = read_addr[k].size;
18440                     for (n = 0; n < size; n++) {
18441                         addr = read_addr[k].addr + n*4;
18442                         *p++ = REG_RD(sc, addr);
18443                     }
18444                 }
18445             }
18446         }
18447     }
18448     return;
18449 }
18450
18451
18452 static int
18453 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18454 {
18455     uint32_t i, j, addr;
18456     const struct wreg_addr *wreg_addr_p = NULL;
18457
18458     if (CHIP_IS_E1(sc))
18459         wreg_addr_p = &wreg_addr_e1;
18460     else if (CHIP_IS_E1H(sc))
18461         wreg_addr_p = &wreg_addr_e1h;
18462     else if (CHIP_IS_E2(sc))
18463         wreg_addr_p = &wreg_addr_e2;
18464     else if (CHIP_IS_E3A0(sc))
18465         wreg_addr_p = &wreg_addr_e3;
18466     else if (CHIP_IS_E3B0(sc))
18467         wreg_addr_p = &wreg_addr_e3b0;
18468     else
18469         return (-1);
18470
18471     /* Read the idle_chk registers */
18472     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18473         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18474             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18475             for (j = 0; j < idle_reg_addrs[i].size; j++)
18476                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18477         }
18478     }
18479
18480     /* Read the regular registers */
18481     for (i = 0; i < REGS_COUNT; i++) {
18482         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18483             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18484             for (j = 0; j < reg_addrs[i].size; j++)
18485                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18486         }
18487     }
18488
18489     /* Read the CAM registers */
18490     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18491         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18492         for (i = 0; i < wreg_addr_p->size; i++) {
18493             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18494
18495             /* In case of wreg_addr register, read additional
18496                registers from read_regs array
18497              */
18498             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18499                 addr = *(wreg_addr_p->read_regs);
18500                 *p++ = REG_RD(sc, addr + j*4);
18501             }
18502         }
18503     }
18504
18505     /* Paged registers are supported in E2 & E3 only */
18506     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18507         /* Read "paged" registers */
18508         bxe_read_pages_regs(sc, p, preset);
18509     }
18510
18511     return 0;
18512 }
18513
18514 static int
18515 bxe_grc_dump(struct bxe_softc *sc)
18516 {
18517     int rval = 0;
18518     uint32_t preset_idx;
18519     uint8_t *buf;
18520     uint32_t size;
18521     struct  dump_header *d_hdr;
18522
18523     if (sc->grcdump_done)
18524         return (rval);
18525     
18526     ecore_disable_blocks_parity(sc);
18527
18528     buf = sc->grc_dump;
18529     d_hdr = sc->grc_dump;
18530
18531     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18532     d_hdr->version = BNX2X_DUMP_VERSION;
18533     d_hdr->preset = DUMP_ALL_PRESETS;
18534
18535     if (CHIP_IS_E1(sc)) {
18536         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18537     } else if (CHIP_IS_E1H(sc)) {
18538         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18539     } else if (CHIP_IS_E2(sc)) {
18540         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18541                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18542     } else if (CHIP_IS_E3A0(sc)) {
18543         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18544                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18545     } else if (CHIP_IS_E3B0(sc)) {
18546         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18547                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18548     }
18549
18550     buf += sizeof(struct  dump_header);
18551
18552     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18553
18554         /* Skip presets with IOR */
18555         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18556             (preset_idx == 11))
18557             continue;
18558
18559         rval = bxe_get_preset_regs(sc, sc->grc_dump, preset_idx);
18560
18561         if (rval)
18562             break;
18563
18564         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18565
18566         buf += size;
18567     }
18568
18569     ecore_clear_blocks_parity(sc);
18570     ecore_enable_blocks_parity(sc);
18571
18572     sc->grcdump_done = 1;
18573     return(rval);
18574 }
18575
18576 static int
18577 bxe_add_cdev(struct bxe_softc *sc)
18578 {
18579     int grc_dump_size;
18580
18581     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18582                                 sizeof(struct  dump_header);
18583
18584     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18585
18586     if (sc->grc_dump == NULL)
18587         return (-1);
18588
18589     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18590                             sc->ifnet->if_dunit,
18591                             UID_ROOT,
18592                             GID_WHEEL,
18593                             0600,
18594                             "%s",
18595                             if_name(sc->ifnet));
18596
18597     if (sc->ioctl_dev == NULL) {
18598
18599         free(sc->grc_dump, M_DEVBUF);
18600
18601         return (-1);
18602     }
18603
18604     sc->ioctl_dev->si_drv1 = sc;
18605
18606     return (0);
18607 }
18608
18609 static void
18610 bxe_del_cdev(struct bxe_softc *sc)
18611 {
18612     if (sc->ioctl_dev != NULL)
18613         destroy_dev(sc->ioctl_dev);
18614
18615     if (sc->grc_dump == NULL)
18616         free(sc->grc_dump, M_DEVBUF);
18617
18618     return;
18619 }
18620
18621 static int
18622 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18623         struct thread *td)
18624 {
18625     struct bxe_softc    *sc;
18626     int                 rval = 0;
18627     device_t            pci_dev;
18628     bxe_grcdump_t       *dump = NULL;
18629     int grc_dump_size;
18630
18631     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18632         return ENXIO;
18633
18634     pci_dev= sc->dev;
18635
18636     dump = (bxe_grcdump_t *)data;
18637
18638     switch(cmd) {
18639
18640         case BXE_GRC_DUMP_SIZE:
18641             dump->pci_func = sc->pcie_func;
18642             dump->grcdump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18643                                         sizeof(struct  dump_header);
18644             break;
18645
18646         case BXE_GRC_DUMP:
18647             
18648             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18649                                 sizeof(struct  dump_header);
18650
18651             if ((sc->grc_dump == NULL) || (dump->grcdump == NULL) ||
18652                 (dump->grcdump_size < grc_dump_size) || (!sc->grcdump_done)) {
18653                 rval = EINVAL;
18654                 break;
18655             }
18656             dump->grcdump_dwords = grc_dump_size >> 2;
18657             rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18658             sc->grcdump_done = 0;
18659
18660             break;
18661
18662         default:
18663             break;
18664     }
18665
18666     return (rval);
18667 }