]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/dev/bxe/bxe.c
MFC r307578
[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.89"
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     { STATS_OFFSET32(tx_queue_full_return),
503                 4, STATS_FLAGS_FUNC, "tx_queue_full_return"},
504     { STATS_OFFSET32(tx_request_link_down_failures),
505                 4, STATS_FLAGS_FUNC, "tx_request_link_down_failures"},
506     { STATS_OFFSET32(bd_avail_too_less_failures),
507                 4, STATS_FLAGS_FUNC, "bd_avail_too_less_failures"},
508     { STATS_OFFSET32(tx_mq_not_empty),
509                 4, STATS_FLAGS_FUNC, "tx_mq_not_empty"}
510
511 };
512
513 static const struct {
514     uint32_t offset;
515     uint32_t size;
516     char string[STAT_NAME_LEN];
517 } bxe_eth_q_stats_arr[] = {
518     { Q_STATS_OFFSET32(total_bytes_received_hi),
519                 8, "rx_bytes" },
520     { Q_STATS_OFFSET32(total_unicast_packets_received_hi),
521                 8, "rx_ucast_packets" },
522     { Q_STATS_OFFSET32(total_multicast_packets_received_hi),
523                 8, "rx_mcast_packets" },
524     { Q_STATS_OFFSET32(total_broadcast_packets_received_hi),
525                 8, "rx_bcast_packets" },
526     { Q_STATS_OFFSET32(no_buff_discard_hi),
527                 8, "rx_discards" },
528     { Q_STATS_OFFSET32(total_bytes_transmitted_hi),
529                 8, "tx_bytes" },
530     { Q_STATS_OFFSET32(total_unicast_packets_transmitted_hi),
531                 8, "tx_ucast_packets" },
532     { Q_STATS_OFFSET32(total_multicast_packets_transmitted_hi),
533                 8, "tx_mcast_packets" },
534     { Q_STATS_OFFSET32(total_broadcast_packets_transmitted_hi),
535                 8, "tx_bcast_packets" },
536     { Q_STATS_OFFSET32(total_tpa_aggregations_hi),
537                 8, "tpa_aggregations" },
538     { Q_STATS_OFFSET32(total_tpa_aggregated_frames_hi),
539                 8, "tpa_aggregated_frames"},
540     { Q_STATS_OFFSET32(total_tpa_bytes_hi),
541                 8, "tpa_bytes"},
542     { Q_STATS_OFFSET32(rx_calls),
543                 4, "rx_calls"},
544     { Q_STATS_OFFSET32(rx_pkts),
545                 4, "rx_pkts"},
546     { Q_STATS_OFFSET32(rx_tpa_pkts),
547                 4, "rx_tpa_pkts"},
548     { Q_STATS_OFFSET32(rx_erroneous_jumbo_sge_pkts),
549                 4, "rx_erroneous_jumbo_sge_pkts"},
550     { Q_STATS_OFFSET32(rx_bxe_service_rxsgl),
551                 4, "rx_bxe_service_rxsgl"},
552     { Q_STATS_OFFSET32(rx_jumbo_sge_pkts),
553                 4, "rx_jumbo_sge_pkts"},
554     { Q_STATS_OFFSET32(rx_soft_errors),
555                 4, "rx_soft_errors"},
556     { Q_STATS_OFFSET32(rx_hw_csum_errors),
557                 4, "rx_hw_csum_errors"},
558     { Q_STATS_OFFSET32(rx_ofld_frames_csum_ip),
559                 4, "rx_ofld_frames_csum_ip"},
560     { Q_STATS_OFFSET32(rx_ofld_frames_csum_tcp_udp),
561                 4, "rx_ofld_frames_csum_tcp_udp"},
562     { Q_STATS_OFFSET32(rx_budget_reached),
563                 4, "rx_budget_reached"},
564     { Q_STATS_OFFSET32(tx_pkts),
565                 4, "tx_pkts"},
566     { Q_STATS_OFFSET32(tx_soft_errors),
567                 4, "tx_soft_errors"},
568     { Q_STATS_OFFSET32(tx_ofld_frames_csum_ip),
569                 4, "tx_ofld_frames_csum_ip"},
570     { Q_STATS_OFFSET32(tx_ofld_frames_csum_tcp),
571                 4, "tx_ofld_frames_csum_tcp"},
572     { Q_STATS_OFFSET32(tx_ofld_frames_csum_udp),
573                 4, "tx_ofld_frames_csum_udp"},
574     { Q_STATS_OFFSET32(tx_ofld_frames_lso),
575                 4, "tx_ofld_frames_lso"},
576     { Q_STATS_OFFSET32(tx_ofld_frames_lso_hdr_splits),
577                 4, "tx_ofld_frames_lso_hdr_splits"},
578     { Q_STATS_OFFSET32(tx_encap_failures),
579                 4, "tx_encap_failures"},
580     { Q_STATS_OFFSET32(tx_hw_queue_full),
581                 4, "tx_hw_queue_full"},
582     { Q_STATS_OFFSET32(tx_hw_max_queue_depth),
583                 4, "tx_hw_max_queue_depth"},
584     { Q_STATS_OFFSET32(tx_dma_mapping_failure),
585                 4, "tx_dma_mapping_failure"},
586     { Q_STATS_OFFSET32(tx_max_drbr_queue_depth),
587                 4, "tx_max_drbr_queue_depth"},
588     { Q_STATS_OFFSET32(tx_window_violation_std),
589                 4, "tx_window_violation_std"},
590     { Q_STATS_OFFSET32(tx_window_violation_tso),
591                 4, "tx_window_violation_tso"},
592     { Q_STATS_OFFSET32(tx_chain_lost_mbuf),
593                 4, "tx_chain_lost_mbuf"},
594     { Q_STATS_OFFSET32(tx_frames_deferred),
595                 4, "tx_frames_deferred"},
596     { Q_STATS_OFFSET32(tx_queue_xoff),
597                 4, "tx_queue_xoff"},
598     { Q_STATS_OFFSET32(mbuf_defrag_attempts),
599                 4, "mbuf_defrag_attempts"},
600     { Q_STATS_OFFSET32(mbuf_defrag_failures),
601                 4, "mbuf_defrag_failures"},
602     { Q_STATS_OFFSET32(mbuf_rx_bd_alloc_failed),
603                 4, "mbuf_rx_bd_alloc_failed"},
604     { Q_STATS_OFFSET32(mbuf_rx_bd_mapping_failed),
605                 4, "mbuf_rx_bd_mapping_failed"},
606     { Q_STATS_OFFSET32(mbuf_rx_tpa_alloc_failed),
607                 4, "mbuf_rx_tpa_alloc_failed"},
608     { Q_STATS_OFFSET32(mbuf_rx_tpa_mapping_failed),
609                 4, "mbuf_rx_tpa_mapping_failed"},
610     { Q_STATS_OFFSET32(mbuf_rx_sge_alloc_failed),
611                 4, "mbuf_rx_sge_alloc_failed"},
612     { Q_STATS_OFFSET32(mbuf_rx_sge_mapping_failed),
613                 4, "mbuf_rx_sge_mapping_failed"},
614     { Q_STATS_OFFSET32(mbuf_alloc_tx),
615                 4, "mbuf_alloc_tx"},
616     { Q_STATS_OFFSET32(mbuf_alloc_rx),
617                 4, "mbuf_alloc_rx"},
618     { Q_STATS_OFFSET32(mbuf_alloc_sge),
619                 4, "mbuf_alloc_sge"},
620     { Q_STATS_OFFSET32(mbuf_alloc_tpa),
621                 4, "mbuf_alloc_tpa"},
622     { Q_STATS_OFFSET32(tx_queue_full_return),
623                 4, "tx_queue_full_return"},
624     { Q_STATS_OFFSET32(tx_request_link_down_failures),
625                 4, "tx_request_link_down_failures"},
626     { Q_STATS_OFFSET32(bd_avail_too_less_failures),
627                 4, "bd_avail_too_less_failures"},
628     { Q_STATS_OFFSET32(tx_mq_not_empty),
629                 4, "tx_mq_not_empty"}
630
631 };
632
633 #define BXE_NUM_ETH_STATS   ARRAY_SIZE(bxe_eth_stats_arr)
634 #define BXE_NUM_ETH_Q_STATS ARRAY_SIZE(bxe_eth_q_stats_arr)
635
636
637 static void    bxe_cmng_fns_init(struct bxe_softc *sc,
638                                  uint8_t          read_cfg,
639                                  uint8_t          cmng_type);
640 static int     bxe_get_cmng_fns_mode(struct bxe_softc *sc);
641 static void    storm_memset_cmng(struct bxe_softc *sc,
642                                  struct cmng_init *cmng,
643                                  uint8_t          port);
644 static void    bxe_set_reset_global(struct bxe_softc *sc);
645 static void    bxe_set_reset_in_progress(struct bxe_softc *sc);
646 static uint8_t bxe_reset_is_done(struct bxe_softc *sc,
647                                  int              engine);
648 static uint8_t bxe_clear_pf_load(struct bxe_softc *sc);
649 static uint8_t bxe_chk_parity_attn(struct bxe_softc *sc,
650                                    uint8_t          *global,
651                                    uint8_t          print);
652 static void    bxe_int_disable(struct bxe_softc *sc);
653 static int     bxe_release_leader_lock(struct bxe_softc *sc);
654 static void    bxe_pf_disable(struct bxe_softc *sc);
655 static void    bxe_free_fp_buffers(struct bxe_softc *sc);
656 static inline void bxe_update_rx_prod(struct bxe_softc    *sc,
657                                       struct bxe_fastpath *fp,
658                                       uint16_t            rx_bd_prod,
659                                       uint16_t            rx_cq_prod,
660                                       uint16_t            rx_sge_prod);
661 static void    bxe_link_report_locked(struct bxe_softc *sc);
662 static void    bxe_link_report(struct bxe_softc *sc);
663 static void    bxe_link_status_update(struct bxe_softc *sc);
664 static void    bxe_periodic_callout_func(void *xsc);
665 static void    bxe_periodic_start(struct bxe_softc *sc);
666 static void    bxe_periodic_stop(struct bxe_softc *sc);
667 static int     bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
668                                     uint16_t prev_index,
669                                     uint16_t index);
670 static int     bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
671                                      int                 queue);
672 static int     bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
673                                      uint16_t            index);
674 static uint8_t bxe_txeof(struct bxe_softc *sc,
675                          struct bxe_fastpath *fp);
676 static void    bxe_task_fp(struct bxe_fastpath *fp);
677 static __noinline void bxe_dump_mbuf(struct bxe_softc *sc,
678                                      struct mbuf      *m,
679                                      uint8_t          contents);
680 static int     bxe_alloc_mem(struct bxe_softc *sc);
681 static void    bxe_free_mem(struct bxe_softc *sc);
682 static int     bxe_alloc_fw_stats_mem(struct bxe_softc *sc);
683 static void    bxe_free_fw_stats_mem(struct bxe_softc *sc);
684 static int     bxe_interrupt_attach(struct bxe_softc *sc);
685 static void    bxe_interrupt_detach(struct bxe_softc *sc);
686 static void    bxe_set_rx_mode(struct bxe_softc *sc);
687 static int     bxe_init_locked(struct bxe_softc *sc);
688 static int     bxe_stop_locked(struct bxe_softc *sc);
689 static __noinline int bxe_nic_load(struct bxe_softc *sc,
690                                    int              load_mode);
691 static __noinline int bxe_nic_unload(struct bxe_softc *sc,
692                                      uint32_t         unload_mode,
693                                      uint8_t          keep_link);
694
695 static void bxe_handle_sp_tq(void *context, int pending);
696 static void bxe_handle_fp_tq(void *context, int pending);
697
698 static int bxe_add_cdev(struct bxe_softc *sc);
699 static void bxe_del_cdev(struct bxe_softc *sc);
700 static int bxe_alloc_buf_rings(struct bxe_softc *sc);
701 static void bxe_free_buf_rings(struct bxe_softc *sc);
702
703 /* calculate crc32 on a buffer (NOTE: crc32_length MUST be aligned to 8) */
704 uint32_t
705 calc_crc32(uint8_t  *crc32_packet,
706            uint32_t crc32_length,
707            uint32_t crc32_seed,
708            uint8_t  complement)
709 {
710    uint32_t byte         = 0;
711    uint32_t bit          = 0;
712    uint8_t  msb          = 0;
713    uint32_t temp         = 0;
714    uint32_t shft         = 0;
715    uint8_t  current_byte = 0;
716    uint32_t crc32_result = crc32_seed;
717    const uint32_t CRC32_POLY = 0x1edc6f41;
718
719    if ((crc32_packet == NULL) ||
720        (crc32_length == 0) ||
721        ((crc32_length % 8) != 0))
722     {
723         return (crc32_result);
724     }
725
726     for (byte = 0; byte < crc32_length; byte = byte + 1)
727     {
728         current_byte = crc32_packet[byte];
729         for (bit = 0; bit < 8; bit = bit + 1)
730         {
731             /* msb = crc32_result[31]; */
732             msb = (uint8_t)(crc32_result >> 31);
733
734             crc32_result = crc32_result << 1;
735
736             /* it (msb != current_byte[bit]) */
737             if (msb != (0x1 & (current_byte >> bit)))
738             {
739                 crc32_result = crc32_result ^ CRC32_POLY;
740                 /* crc32_result[0] = 1 */
741                 crc32_result |= 1;
742             }
743         }
744     }
745
746     /* Last step is to:
747      * 1. "mirror" every bit
748      * 2. swap the 4 bytes
749      * 3. complement each bit
750      */
751
752     /* Mirror */
753     temp = crc32_result;
754     shft = sizeof(crc32_result) * 8 - 1;
755
756     for (crc32_result >>= 1; crc32_result; crc32_result >>= 1)
757     {
758         temp <<= 1;
759         temp |= crc32_result & 1;
760         shft-- ;
761     }
762
763     /* temp[31-bit] = crc32_result[bit] */
764     temp <<= shft;
765
766     /* Swap */
767     /* crc32_result = {temp[7:0], temp[15:8], temp[23:16], temp[31:24]} */
768     {
769         uint32_t t0, t1, t2, t3;
770         t0 = (0x000000ff & (temp >> 24));
771         t1 = (0x0000ff00 & (temp >> 8));
772         t2 = (0x00ff0000 & (temp << 8));
773         t3 = (0xff000000 & (temp << 24));
774         crc32_result = t0 | t1 | t2 | t3;
775     }
776
777     /* Complement */
778     if (complement)
779     {
780         crc32_result = ~crc32_result;
781     }
782
783     return (crc32_result);
784 }
785
786 int
787 bxe_test_bit(int                    nr,
788              volatile unsigned long *addr)
789 {
790     return ((atomic_load_acq_long(addr) & (1 << nr)) != 0);
791 }
792
793 void
794 bxe_set_bit(unsigned int           nr,
795             volatile unsigned long *addr)
796 {
797     atomic_set_acq_long(addr, (1 << nr));
798 }
799
800 void
801 bxe_clear_bit(int                    nr,
802               volatile unsigned long *addr)
803 {
804     atomic_clear_acq_long(addr, (1 << nr));
805 }
806
807 int
808 bxe_test_and_set_bit(int                    nr,
809                        volatile unsigned long *addr)
810 {
811     unsigned long x;
812     nr = (1 << nr);
813     do {
814         x = *addr;
815     } while (atomic_cmpset_acq_long(addr, x, x | nr) == 0);
816     // if (x & nr) bit_was_set; else bit_was_not_set;
817     return (x & nr);
818 }
819
820 int
821 bxe_test_and_clear_bit(int                    nr,
822                        volatile unsigned long *addr)
823 {
824     unsigned long x;
825     nr = (1 << nr);
826     do {
827         x = *addr;
828     } while (atomic_cmpset_acq_long(addr, x, x & ~nr) == 0);
829     // if (x & nr) bit_was_set; else bit_was_not_set;
830     return (x & nr);
831 }
832
833 int
834 bxe_cmpxchg(volatile int *addr,
835             int          old,
836             int          new)
837 {
838     int x;
839     do {
840         x = *addr;
841     } while (atomic_cmpset_acq_int(addr, old, new) == 0);
842     return (x);
843 }
844
845 /*
846  * Get DMA memory from the OS.
847  *
848  * Validates that the OS has provided DMA buffers in response to a
849  * bus_dmamap_load call and saves the physical address of those buffers.
850  * When the callback is used the OS will return 0 for the mapping function
851  * (bus_dmamap_load) so we use the value of map_arg->maxsegs to pass any
852  * failures back to the caller.
853  *
854  * Returns:
855  *   Nothing.
856  */
857 static void
858 bxe_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
859 {
860     struct bxe_dma *dma = arg;
861
862     if (error) {
863         dma->paddr = 0;
864         dma->nseg  = 0;
865         BLOGE(dma->sc, "Failed DMA alloc '%s' (%d)!\n", dma->msg, error);
866     } else {
867         dma->paddr = segs->ds_addr;
868         dma->nseg  = nseg;
869     }
870 }
871
872 /*
873  * Allocate a block of memory and map it for DMA. No partial completions
874  * allowed and release any resources acquired if we can't acquire all
875  * resources.
876  *
877  * Returns:
878  *   0 = Success, !0 = Failure
879  */
880 int
881 bxe_dma_alloc(struct bxe_softc *sc,
882               bus_size_t       size,
883               struct bxe_dma   *dma,
884               const char       *msg)
885 {
886     int rc;
887
888     if (dma->size > 0) {
889         BLOGE(sc, "dma block '%s' already has size %lu\n", msg,
890               (unsigned long)dma->size);
891         return (1);
892     }
893
894     memset(dma, 0, sizeof(*dma)); /* sanity */
895     dma->sc   = sc;
896     dma->size = size;
897     snprintf(dma->msg, sizeof(dma->msg), "%s", msg);
898
899     rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
900                             BCM_PAGE_SIZE,      /* alignment */
901                             0,                  /* boundary limit */
902                             BUS_SPACE_MAXADDR,  /* restricted low */
903                             BUS_SPACE_MAXADDR,  /* restricted hi */
904                             NULL,               /* addr filter() */
905                             NULL,               /* addr filter() arg */
906                             size,               /* max map size */
907                             1,                  /* num discontinuous */
908                             size,               /* max seg size */
909                             BUS_DMA_ALLOCNOW,   /* flags */
910                             NULL,               /* lock() */
911                             NULL,               /* lock() arg */
912                             &dma->tag);         /* returned dma tag */
913     if (rc != 0) {
914         BLOGE(sc, "Failed to create dma tag for '%s' (%d)\n", msg, rc);
915         memset(dma, 0, sizeof(*dma));
916         return (1);
917     }
918
919     rc = bus_dmamem_alloc(dma->tag,
920                           (void **)&dma->vaddr,
921                           (BUS_DMA_NOWAIT | BUS_DMA_ZERO),
922                           &dma->map);
923     if (rc != 0) {
924         BLOGE(sc, "Failed to alloc dma mem for '%s' (%d)\n", msg, rc);
925         bus_dma_tag_destroy(dma->tag);
926         memset(dma, 0, sizeof(*dma));
927         return (1);
928     }
929
930     rc = bus_dmamap_load(dma->tag,
931                          dma->map,
932                          dma->vaddr,
933                          size,
934                          bxe_dma_map_addr, /* BLOGD in here */
935                          dma,
936                          BUS_DMA_NOWAIT);
937     if (rc != 0) {
938         BLOGE(sc, "Failed to load dma map for '%s' (%d)\n", msg, rc);
939         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
940         bus_dma_tag_destroy(dma->tag);
941         memset(dma, 0, sizeof(*dma));
942         return (1);
943     }
944
945     return (0);
946 }
947
948 void
949 bxe_dma_free(struct bxe_softc *sc,
950              struct bxe_dma   *dma)
951 {
952     if (dma->size > 0) {
953         DBASSERT(sc, (dma->tag != NULL), ("dma tag is NULL"));
954
955         bus_dmamap_sync(dma->tag, dma->map,
956                         (BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE));
957         bus_dmamap_unload(dma->tag, dma->map);
958         bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
959         bus_dma_tag_destroy(dma->tag);
960     }
961
962     memset(dma, 0, sizeof(*dma));
963 }
964
965 /*
966  * These indirect read and write routines are only during init.
967  * The locking is handled by the MCP.
968  */
969
970 void
971 bxe_reg_wr_ind(struct bxe_softc *sc,
972                uint32_t         addr,
973                uint32_t         val)
974 {
975     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
976     pci_write_config(sc->dev, PCICFG_GRC_DATA, val, 4);
977     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
978 }
979
980 uint32_t
981 bxe_reg_rd_ind(struct bxe_softc *sc,
982                uint32_t         addr)
983 {
984     uint32_t val;
985
986     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, addr, 4);
987     val = pci_read_config(sc->dev, PCICFG_GRC_DATA, 4);
988     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
989
990     return (val);
991 }
992
993 static int
994 bxe_acquire_hw_lock(struct bxe_softc *sc,
995                     uint32_t         resource)
996 {
997     uint32_t lock_status;
998     uint32_t resource_bit = (1 << resource);
999     int func = SC_FUNC(sc);
1000     uint32_t hw_lock_control_reg;
1001     int cnt;
1002
1003     /* validate the resource is within range */
1004     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1005         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1006             " resource_bit 0x%x\n", resource, resource_bit);
1007         return (-1);
1008     }
1009
1010     if (func <= 5) {
1011         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1012     } else {
1013         hw_lock_control_reg =
1014                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1015     }
1016
1017     /* validate the resource is not already taken */
1018     lock_status = REG_RD(sc, hw_lock_control_reg);
1019     if (lock_status & resource_bit) {
1020         BLOGE(sc, "resource (0x%x) in use (status 0x%x bit 0x%x)\n",
1021               resource, lock_status, resource_bit);
1022         return (-1);
1023     }
1024
1025     /* try every 5ms for 5 seconds */
1026     for (cnt = 0; cnt < 1000; cnt++) {
1027         REG_WR(sc, (hw_lock_control_reg + 4), resource_bit);
1028         lock_status = REG_RD(sc, hw_lock_control_reg);
1029         if (lock_status & resource_bit) {
1030             return (0);
1031         }
1032         DELAY(5000);
1033     }
1034
1035     BLOGE(sc, "Resource 0x%x resource_bit 0x%x lock timeout!\n",
1036         resource, resource_bit);
1037     return (-1);
1038 }
1039
1040 static int
1041 bxe_release_hw_lock(struct bxe_softc *sc,
1042                     uint32_t         resource)
1043 {
1044     uint32_t lock_status;
1045     uint32_t resource_bit = (1 << resource);
1046     int func = SC_FUNC(sc);
1047     uint32_t hw_lock_control_reg;
1048
1049     /* validate the resource is within range */
1050     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
1051         BLOGE(sc, "(resource 0x%x > HW_LOCK_MAX_RESOURCE_VALUE)"
1052             " resource_bit 0x%x\n", resource, resource_bit);
1053         return (-1);
1054     }
1055
1056     if (func <= 5) {
1057         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + (func * 8));
1058     } else {
1059         hw_lock_control_reg =
1060                 (MISC_REG_DRIVER_CONTROL_7 + ((func - 6) * 8));
1061     }
1062
1063     /* validate the resource is currently taken */
1064     lock_status = REG_RD(sc, hw_lock_control_reg);
1065     if (!(lock_status & resource_bit)) {
1066         BLOGE(sc, "resource (0x%x) not in use (status 0x%x bit 0x%x)\n",
1067               resource, lock_status, resource_bit);
1068         return (-1);
1069     }
1070
1071     REG_WR(sc, hw_lock_control_reg, resource_bit);
1072     return (0);
1073 }
1074 static void bxe_acquire_phy_lock(struct bxe_softc *sc)
1075 {
1076         BXE_PHY_LOCK(sc);
1077         bxe_acquire_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1078 }
1079
1080 static void bxe_release_phy_lock(struct bxe_softc *sc)
1081 {
1082         bxe_release_hw_lock(sc,HW_LOCK_RESOURCE_MDIO); 
1083         BXE_PHY_UNLOCK(sc);
1084 }
1085 /*
1086  * Per pf misc lock must be acquired before the per port mcp lock. Otherwise,
1087  * had we done things the other way around, if two pfs from the same port
1088  * would attempt to access nvram at the same time, we could run into a
1089  * scenario such as:
1090  * pf A takes the port lock.
1091  * pf B succeeds in taking the same lock since they are from the same port.
1092  * pf A takes the per pf misc lock. Performs eeprom access.
1093  * pf A finishes. Unlocks the per pf misc lock.
1094  * Pf B takes the lock and proceeds to perform it's own access.
1095  * pf A unlocks the per port lock, while pf B is still working (!).
1096  * mcp takes the per port lock and corrupts pf B's access (and/or has it's own
1097  * access corrupted by pf B).*
1098  */
1099 static int
1100 bxe_acquire_nvram_lock(struct bxe_softc *sc)
1101 {
1102     int port = SC_PORT(sc);
1103     int count, i;
1104     uint32_t val = 0;
1105
1106     /* acquire HW lock: protect against other PFs in PF Direct Assignment */
1107     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1108
1109     /* adjust timeout for emulation/FPGA */
1110     count = NVRAM_TIMEOUT_COUNT;
1111     if (CHIP_REV_IS_SLOW(sc)) {
1112         count *= 100;
1113     }
1114
1115     /* request access to nvram interface */
1116     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1117            (MCPR_NVM_SW_ARB_ARB_REQ_SET1 << port));
1118
1119     for (i = 0; i < count*10; i++) {
1120         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1121         if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1122             break;
1123         }
1124
1125         DELAY(5);
1126     }
1127
1128     if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1129         BLOGE(sc, "Cannot get access to nvram interface "
1130             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1131             port, val);
1132         return (-1);
1133     }
1134
1135     return (0);
1136 }
1137
1138 static int
1139 bxe_release_nvram_lock(struct bxe_softc *sc)
1140 {
1141     int port = SC_PORT(sc);
1142     int count, i;
1143     uint32_t val = 0;
1144
1145     /* adjust timeout for emulation/FPGA */
1146     count = NVRAM_TIMEOUT_COUNT;
1147     if (CHIP_REV_IS_SLOW(sc)) {
1148         count *= 100;
1149     }
1150
1151     /* relinquish nvram interface */
1152     REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
1153            (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << port));
1154
1155     for (i = 0; i < count*10; i++) {
1156         val = REG_RD(sc, MCP_REG_MCPR_NVM_SW_ARB);
1157         if (!(val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port))) {
1158             break;
1159         }
1160
1161         DELAY(5);
1162     }
1163
1164     if (val & (MCPR_NVM_SW_ARB_ARB_ARB1 << port)) {
1165         BLOGE(sc, "Cannot free access to nvram interface "
1166             "port %d val 0x%x (MCPR_NVM_SW_ARB_ARB_ARB1 << port)\n",
1167             port, val);
1168         return (-1);
1169     }
1170
1171     /* release HW lock: protect against other PFs in PF Direct Assignment */
1172     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_NVRAM);
1173
1174     return (0);
1175 }
1176
1177 static void
1178 bxe_enable_nvram_access(struct bxe_softc *sc)
1179 {
1180     uint32_t val;
1181
1182     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1183
1184     /* enable both bits, even on read */
1185     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1186            (val | MCPR_NVM_ACCESS_ENABLE_EN | MCPR_NVM_ACCESS_ENABLE_WR_EN));
1187 }
1188
1189 static void
1190 bxe_disable_nvram_access(struct bxe_softc *sc)
1191 {
1192     uint32_t val;
1193
1194     val = REG_RD(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE);
1195
1196     /* disable both bits, even after read */
1197     REG_WR(sc, MCP_REG_MCPR_NVM_ACCESS_ENABLE,
1198            (val & ~(MCPR_NVM_ACCESS_ENABLE_EN |
1199                     MCPR_NVM_ACCESS_ENABLE_WR_EN)));
1200 }
1201
1202 static int
1203 bxe_nvram_read_dword(struct bxe_softc *sc,
1204                      uint32_t         offset,
1205                      uint32_t         *ret_val,
1206                      uint32_t         cmd_flags)
1207 {
1208     int count, i, rc;
1209     uint32_t val;
1210
1211     /* build the command word */
1212     cmd_flags |= MCPR_NVM_COMMAND_DOIT;
1213
1214     /* need to clear DONE bit separately */
1215     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1216
1217     /* address of the NVRAM to read from */
1218     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1219            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1220
1221     /* issue a read command */
1222     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1223
1224     /* adjust timeout for emulation/FPGA */
1225     count = NVRAM_TIMEOUT_COUNT;
1226     if (CHIP_REV_IS_SLOW(sc)) {
1227         count *= 100;
1228     }
1229
1230     /* wait for completion */
1231     *ret_val = 0;
1232     rc = -1;
1233     for (i = 0; i < count; i++) {
1234         DELAY(5);
1235         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1236
1237         if (val & MCPR_NVM_COMMAND_DONE) {
1238             val = REG_RD(sc, MCP_REG_MCPR_NVM_READ);
1239             /* we read nvram data in cpu order
1240              * but ethtool sees it as an array of bytes
1241              * converting to big-endian will do the work
1242              */
1243             *ret_val = htobe32(val);
1244             rc = 0;
1245             break;
1246         }
1247     }
1248
1249     if (rc == -1) {
1250         BLOGE(sc, "nvram read timeout expired "
1251             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1252             offset, cmd_flags, val);
1253     }
1254
1255     return (rc);
1256 }
1257
1258 static int
1259 bxe_nvram_read(struct bxe_softc *sc,
1260                uint32_t         offset,
1261                uint8_t          *ret_buf,
1262                int              buf_size)
1263 {
1264     uint32_t cmd_flags;
1265     uint32_t val;
1266     int rc;
1267
1268     if ((offset & 0x03) || (buf_size & 0x03) || (buf_size == 0)) {
1269         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1270               offset, buf_size);
1271         return (-1);
1272     }
1273
1274     if ((offset + buf_size) > sc->devinfo.flash_size) {
1275         BLOGE(sc, "Invalid parameter, "
1276                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1277               offset, buf_size, sc->devinfo.flash_size);
1278         return (-1);
1279     }
1280
1281     /* request access to nvram interface */
1282     rc = bxe_acquire_nvram_lock(sc);
1283     if (rc) {
1284         return (rc);
1285     }
1286
1287     /* enable access to nvram interface */
1288     bxe_enable_nvram_access(sc);
1289
1290     /* read the first word(s) */
1291     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1292     while ((buf_size > sizeof(uint32_t)) && (rc == 0)) {
1293         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1294         memcpy(ret_buf, &val, 4);
1295
1296         /* advance to the next dword */
1297         offset += sizeof(uint32_t);
1298         ret_buf += sizeof(uint32_t);
1299         buf_size -= sizeof(uint32_t);
1300         cmd_flags = 0;
1301     }
1302
1303     if (rc == 0) {
1304         cmd_flags |= MCPR_NVM_COMMAND_LAST;
1305         rc = bxe_nvram_read_dword(sc, offset, &val, cmd_flags);
1306         memcpy(ret_buf, &val, 4);
1307     }
1308
1309     /* disable access to nvram interface */
1310     bxe_disable_nvram_access(sc);
1311     bxe_release_nvram_lock(sc);
1312
1313     return (rc);
1314 }
1315
1316 static int
1317 bxe_nvram_write_dword(struct bxe_softc *sc,
1318                       uint32_t         offset,
1319                       uint32_t         val,
1320                       uint32_t         cmd_flags)
1321 {
1322     int count, i, rc;
1323
1324     /* build the command word */
1325     cmd_flags |= (MCPR_NVM_COMMAND_DOIT | MCPR_NVM_COMMAND_WR);
1326
1327     /* need to clear DONE bit separately */
1328     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, MCPR_NVM_COMMAND_DONE);
1329
1330     /* write the data */
1331     REG_WR(sc, MCP_REG_MCPR_NVM_WRITE, val);
1332
1333     /* address of the NVRAM to write to */
1334     REG_WR(sc, MCP_REG_MCPR_NVM_ADDR,
1335            (offset & MCPR_NVM_ADDR_NVM_ADDR_VALUE));
1336
1337     /* issue the write command */
1338     REG_WR(sc, MCP_REG_MCPR_NVM_COMMAND, cmd_flags);
1339
1340     /* adjust timeout for emulation/FPGA */
1341     count = NVRAM_TIMEOUT_COUNT;
1342     if (CHIP_REV_IS_SLOW(sc)) {
1343         count *= 100;
1344     }
1345
1346     /* wait for completion */
1347     rc = -1;
1348     for (i = 0; i < count; i++) {
1349         DELAY(5);
1350         val = REG_RD(sc, MCP_REG_MCPR_NVM_COMMAND);
1351         if (val & MCPR_NVM_COMMAND_DONE) {
1352             rc = 0;
1353             break;
1354         }
1355     }
1356
1357     if (rc == -1) {
1358         BLOGE(sc, "nvram write timeout expired "
1359             "(offset 0x%x cmd_flags 0x%x val 0x%x)\n",
1360             offset, cmd_flags, val);
1361     }
1362
1363     return (rc);
1364 }
1365
1366 #define BYTE_OFFSET(offset) (8 * (offset & 0x03))
1367
1368 static int
1369 bxe_nvram_write1(struct bxe_softc *sc,
1370                  uint32_t         offset,
1371                  uint8_t          *data_buf,
1372                  int              buf_size)
1373 {
1374     uint32_t cmd_flags;
1375     uint32_t align_offset;
1376     uint32_t val;
1377     int rc;
1378
1379     if ((offset + buf_size) > sc->devinfo.flash_size) {
1380         BLOGE(sc, "Invalid parameter, "
1381                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1382               offset, buf_size, sc->devinfo.flash_size);
1383         return (-1);
1384     }
1385
1386     /* request access to nvram interface */
1387     rc = bxe_acquire_nvram_lock(sc);
1388     if (rc) {
1389         return (rc);
1390     }
1391
1392     /* enable access to nvram interface */
1393     bxe_enable_nvram_access(sc);
1394
1395     cmd_flags = (MCPR_NVM_COMMAND_FIRST | MCPR_NVM_COMMAND_LAST);
1396     align_offset = (offset & ~0x03);
1397     rc = bxe_nvram_read_dword(sc, align_offset, &val, cmd_flags);
1398
1399     if (rc == 0) {
1400         val &= ~(0xff << BYTE_OFFSET(offset));
1401         val |= (*data_buf << BYTE_OFFSET(offset));
1402
1403         /* nvram data is returned as an array of bytes
1404          * convert it back to cpu order
1405          */
1406         val = be32toh(val);
1407
1408         rc = bxe_nvram_write_dword(sc, align_offset, val, cmd_flags);
1409     }
1410
1411     /* disable access to nvram interface */
1412     bxe_disable_nvram_access(sc);
1413     bxe_release_nvram_lock(sc);
1414
1415     return (rc);
1416 }
1417
1418 static int
1419 bxe_nvram_write(struct bxe_softc *sc,
1420                 uint32_t         offset,
1421                 uint8_t          *data_buf,
1422                 int              buf_size)
1423 {
1424     uint32_t cmd_flags;
1425     uint32_t val;
1426     uint32_t written_so_far;
1427     int rc;
1428
1429     if (buf_size == 1) {
1430         return (bxe_nvram_write1(sc, offset, data_buf, buf_size));
1431     }
1432
1433     if ((offset & 0x03) || (buf_size & 0x03) /* || (buf_size == 0) */) {
1434         BLOGE(sc, "Invalid parameter, offset 0x%x buf_size 0x%x\n",
1435               offset, buf_size);
1436         return (-1);
1437     }
1438
1439     if (buf_size == 0) {
1440         return (0); /* nothing to do */
1441     }
1442
1443     if ((offset + buf_size) > sc->devinfo.flash_size) {
1444         BLOGE(sc, "Invalid parameter, "
1445                   "offset 0x%x + buf_size 0x%x > flash_size 0x%x\n",
1446               offset, buf_size, sc->devinfo.flash_size);
1447         return (-1);
1448     }
1449
1450     /* request access to nvram interface */
1451     rc = bxe_acquire_nvram_lock(sc);
1452     if (rc) {
1453         return (rc);
1454     }
1455
1456     /* enable access to nvram interface */
1457     bxe_enable_nvram_access(sc);
1458
1459     written_so_far = 0;
1460     cmd_flags = MCPR_NVM_COMMAND_FIRST;
1461     while ((written_so_far < buf_size) && (rc == 0)) {
1462         if (written_so_far == (buf_size - sizeof(uint32_t))) {
1463             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1464         } else if (((offset + 4) % NVRAM_PAGE_SIZE) == 0) {
1465             cmd_flags |= MCPR_NVM_COMMAND_LAST;
1466         } else if ((offset % NVRAM_PAGE_SIZE) == 0) {
1467             cmd_flags |= MCPR_NVM_COMMAND_FIRST;
1468         }
1469
1470         memcpy(&val, data_buf, 4);
1471
1472         rc = bxe_nvram_write_dword(sc, offset, val, cmd_flags);
1473
1474         /* advance to the next dword */
1475         offset += sizeof(uint32_t);
1476         data_buf += sizeof(uint32_t);
1477         written_so_far += sizeof(uint32_t);
1478         cmd_flags = 0;
1479     }
1480
1481     /* disable access to nvram interface */
1482     bxe_disable_nvram_access(sc);
1483     bxe_release_nvram_lock(sc);
1484
1485     return (rc);
1486 }
1487
1488 /* copy command into DMAE command memory and set DMAE command Go */
1489 void
1490 bxe_post_dmae(struct bxe_softc    *sc,
1491               struct dmae_cmd *dmae,
1492               int                 idx)
1493 {
1494     uint32_t cmd_offset;
1495     int i;
1496
1497     cmd_offset = (DMAE_REG_CMD_MEM + (sizeof(struct dmae_cmd) * idx));
1498     for (i = 0; i < ((sizeof(struct dmae_cmd) / 4)); i++) {
1499         REG_WR(sc, (cmd_offset + (i * 4)), *(((uint32_t *)dmae) + i));
1500     }
1501
1502     REG_WR(sc, dmae_reg_go_c[idx], 1);
1503 }
1504
1505 uint32_t
1506 bxe_dmae_opcode_add_comp(uint32_t opcode,
1507                          uint8_t  comp_type)
1508 {
1509     return (opcode | ((comp_type << DMAE_CMD_C_DST_SHIFT) |
1510                       DMAE_CMD_C_TYPE_ENABLE));
1511 }
1512
1513 uint32_t
1514 bxe_dmae_opcode_clr_src_reset(uint32_t opcode)
1515 {
1516     return (opcode & ~DMAE_CMD_SRC_RESET);
1517 }
1518
1519 uint32_t
1520 bxe_dmae_opcode(struct bxe_softc *sc,
1521                 uint8_t          src_type,
1522                 uint8_t          dst_type,
1523                 uint8_t          with_comp,
1524                 uint8_t          comp_type)
1525 {
1526     uint32_t opcode = 0;
1527
1528     opcode |= ((src_type << DMAE_CMD_SRC_SHIFT) |
1529                (dst_type << DMAE_CMD_DST_SHIFT));
1530
1531     opcode |= (DMAE_CMD_SRC_RESET | DMAE_CMD_DST_RESET);
1532
1533     opcode |= (SC_PORT(sc) ? DMAE_CMD_PORT_1 : DMAE_CMD_PORT_0);
1534
1535     opcode |= ((SC_VN(sc) << DMAE_CMD_E1HVN_SHIFT) |
1536                (SC_VN(sc) << DMAE_CMD_DST_VN_SHIFT));
1537
1538     opcode |= (DMAE_COM_SET_ERR << DMAE_CMD_ERR_POLICY_SHIFT);
1539
1540 #ifdef __BIG_ENDIAN
1541     opcode |= DMAE_CMD_ENDIANITY_B_DW_SWAP;
1542 #else
1543     opcode |= DMAE_CMD_ENDIANITY_DW_SWAP;
1544 #endif
1545
1546     if (with_comp) {
1547         opcode = bxe_dmae_opcode_add_comp(opcode, comp_type);
1548     }
1549
1550     return (opcode);
1551 }
1552
1553 static void
1554 bxe_prep_dmae_with_comp(struct bxe_softc    *sc,
1555                         struct dmae_cmd *dmae,
1556                         uint8_t             src_type,
1557                         uint8_t             dst_type)
1558 {
1559     memset(dmae, 0, sizeof(struct dmae_cmd));
1560
1561     /* set the opcode */
1562     dmae->opcode = bxe_dmae_opcode(sc, src_type, dst_type,
1563                                    TRUE, DMAE_COMP_PCI);
1564
1565     /* fill in the completion parameters */
1566     dmae->comp_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_comp));
1567     dmae->comp_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_comp));
1568     dmae->comp_val     = DMAE_COMP_VAL;
1569 }
1570
1571 /* issue a DMAE command over the init channel and wait for completion */
1572 static int
1573 bxe_issue_dmae_with_comp(struct bxe_softc    *sc,
1574                          struct dmae_cmd *dmae)
1575 {
1576     uint32_t *wb_comp = BXE_SP(sc, wb_comp);
1577     int timeout = CHIP_REV_IS_SLOW(sc) ? 400000 : 4000;
1578
1579     BXE_DMAE_LOCK(sc);
1580
1581     /* reset completion */
1582     *wb_comp = 0;
1583
1584     /* post the command on the channel used for initializations */
1585     bxe_post_dmae(sc, dmae, INIT_DMAE_C(sc));
1586
1587     /* wait for completion */
1588     DELAY(5);
1589
1590     while ((*wb_comp & ~DMAE_PCI_ERR_FLAG) != DMAE_COMP_VAL) {
1591         if (!timeout ||
1592             (sc->recovery_state != BXE_RECOVERY_DONE &&
1593              sc->recovery_state != BXE_RECOVERY_NIC_LOADING)) {
1594             BLOGE(sc, "DMAE timeout! *wb_comp 0x%x recovery_state 0x%x\n",
1595                 *wb_comp, sc->recovery_state);
1596             BXE_DMAE_UNLOCK(sc);
1597             return (DMAE_TIMEOUT);
1598         }
1599
1600         timeout--;
1601         DELAY(50);
1602     }
1603
1604     if (*wb_comp & DMAE_PCI_ERR_FLAG) {
1605         BLOGE(sc, "DMAE PCI error! *wb_comp 0x%x recovery_state 0x%x\n",
1606                 *wb_comp, sc->recovery_state);
1607         BXE_DMAE_UNLOCK(sc);
1608         return (DMAE_PCI_ERROR);
1609     }
1610
1611     BXE_DMAE_UNLOCK(sc);
1612     return (0);
1613 }
1614
1615 void
1616 bxe_read_dmae(struct bxe_softc *sc,
1617               uint32_t         src_addr,
1618               uint32_t         len32)
1619 {
1620     struct dmae_cmd dmae;
1621     uint32_t *data;
1622     int i, rc;
1623
1624     DBASSERT(sc, (len32 <= 4), ("DMAE read length is %d", len32));
1625
1626     if (!sc->dmae_ready) {
1627         data = BXE_SP(sc, wb_data[0]);
1628
1629         for (i = 0; i < len32; i++) {
1630             data[i] = (CHIP_IS_E1(sc)) ?
1631                           bxe_reg_rd_ind(sc, (src_addr + (i * 4))) :
1632                           REG_RD(sc, (src_addr + (i * 4)));
1633         }
1634
1635         return;
1636     }
1637
1638     /* set opcode and fixed command fields */
1639     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_GRC, DMAE_DST_PCI);
1640
1641     /* fill in addresses and len */
1642     dmae.src_addr_lo = (src_addr >> 2); /* GRC addr has dword resolution */
1643     dmae.src_addr_hi = 0;
1644     dmae.dst_addr_lo = U64_LO(BXE_SP_MAPPING(sc, wb_data));
1645     dmae.dst_addr_hi = U64_HI(BXE_SP_MAPPING(sc, wb_data));
1646     dmae.len         = len32;
1647
1648     /* issue the command and wait for completion */
1649     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1650         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1651     };
1652 }
1653
1654 void
1655 bxe_write_dmae(struct bxe_softc *sc,
1656                bus_addr_t       dma_addr,
1657                uint32_t         dst_addr,
1658                uint32_t         len32)
1659 {
1660     struct dmae_cmd dmae;
1661     int rc;
1662
1663     if (!sc->dmae_ready) {
1664         DBASSERT(sc, (len32 <= 4), ("DMAE not ready and length is %d", len32));
1665
1666         if (CHIP_IS_E1(sc)) {
1667             ecore_init_ind_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1668         } else {
1669             ecore_init_str_wr(sc, dst_addr, BXE_SP(sc, wb_data[0]), len32);
1670         }
1671
1672         return;
1673     }
1674
1675     /* set opcode and fixed command fields */
1676     bxe_prep_dmae_with_comp(sc, &dmae, DMAE_SRC_PCI, DMAE_DST_GRC);
1677
1678     /* fill in addresses and len */
1679     dmae.src_addr_lo = U64_LO(dma_addr);
1680     dmae.src_addr_hi = U64_HI(dma_addr);
1681     dmae.dst_addr_lo = (dst_addr >> 2); /* GRC addr has dword resolution */
1682     dmae.dst_addr_hi = 0;
1683     dmae.len         = len32;
1684
1685     /* issue the command and wait for completion */
1686     if ((rc = bxe_issue_dmae_with_comp(sc, &dmae)) != 0) {
1687         bxe_panic(sc, ("DMAE failed (%d)\n", rc));
1688     }
1689 }
1690
1691 void
1692 bxe_write_dmae_phys_len(struct bxe_softc *sc,
1693                         bus_addr_t       phys_addr,
1694                         uint32_t         addr,
1695                         uint32_t         len)
1696 {
1697     int dmae_wr_max = DMAE_LEN32_WR_MAX(sc);
1698     int offset = 0;
1699
1700     while (len > dmae_wr_max) {
1701         bxe_write_dmae(sc,
1702                        (phys_addr + offset), /* src DMA address */
1703                        (addr + offset),      /* dst GRC address */
1704                        dmae_wr_max);
1705         offset += (dmae_wr_max * 4);
1706         len -= dmae_wr_max;
1707     }
1708
1709     bxe_write_dmae(sc,
1710                    (phys_addr + offset), /* src DMA address */
1711                    (addr + offset),      /* dst GRC address */
1712                    len);
1713 }
1714
1715 void
1716 bxe_set_ctx_validation(struct bxe_softc   *sc,
1717                        struct eth_context *cxt,
1718                        uint32_t           cid)
1719 {
1720     /* ustorm cxt validation */
1721     cxt->ustorm_ag_context.cdu_usage =
1722         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1723             CDU_REGION_NUMBER_UCM_AG, ETH_CONNECTION_TYPE);
1724     /* xcontext validation */
1725     cxt->xstorm_ag_context.cdu_reserved =
1726         CDU_RSRVD_VALUE_TYPE_A(HW_CID(sc, cid),
1727             CDU_REGION_NUMBER_XCM_AG, ETH_CONNECTION_TYPE);
1728 }
1729
1730 static void
1731 bxe_storm_memset_hc_timeout(struct bxe_softc *sc,
1732                             uint8_t          port,
1733                             uint8_t          fw_sb_id,
1734                             uint8_t          sb_index,
1735                             uint8_t          ticks)
1736 {
1737     uint32_t addr =
1738         (BAR_CSTRORM_INTMEM +
1739          CSTORM_STATUS_BLOCK_DATA_TIMEOUT_OFFSET(fw_sb_id, sb_index));
1740
1741     REG_WR8(sc, addr, ticks);
1742
1743     BLOGD(sc, DBG_LOAD,
1744           "port %d fw_sb_id %d sb_index %d ticks %d\n",
1745           port, fw_sb_id, sb_index, ticks);
1746 }
1747
1748 static void
1749 bxe_storm_memset_hc_disable(struct bxe_softc *sc,
1750                             uint8_t          port,
1751                             uint16_t         fw_sb_id,
1752                             uint8_t          sb_index,
1753                             uint8_t          disable)
1754 {
1755     uint32_t enable_flag =
1756         (disable) ? 0 : (1 << HC_INDEX_DATA_HC_ENABLED_SHIFT);
1757     uint32_t addr =
1758         (BAR_CSTRORM_INTMEM +
1759          CSTORM_STATUS_BLOCK_DATA_FLAGS_OFFSET(fw_sb_id, sb_index));
1760     uint8_t flags;
1761
1762     /* clear and set */
1763     flags = REG_RD8(sc, addr);
1764     flags &= ~HC_INDEX_DATA_HC_ENABLED;
1765     flags |= enable_flag;
1766     REG_WR8(sc, addr, flags);
1767
1768     BLOGD(sc, DBG_LOAD,
1769           "port %d fw_sb_id %d sb_index %d disable %d\n",
1770           port, fw_sb_id, sb_index, disable);
1771 }
1772
1773 void
1774 bxe_update_coalesce_sb_index(struct bxe_softc *sc,
1775                              uint8_t          fw_sb_id,
1776                              uint8_t          sb_index,
1777                              uint8_t          disable,
1778                              uint16_t         usec)
1779 {
1780     int port = SC_PORT(sc);
1781     uint8_t ticks = (usec / 4); /* XXX ??? */
1782
1783     bxe_storm_memset_hc_timeout(sc, port, fw_sb_id, sb_index, ticks);
1784
1785     disable = (disable) ? 1 : ((usec) ? 0 : 1);
1786     bxe_storm_memset_hc_disable(sc, port, fw_sb_id, sb_index, disable);
1787 }
1788
1789 void
1790 elink_cb_udelay(struct bxe_softc *sc,
1791                 uint32_t         usecs)
1792 {
1793     DELAY(usecs);
1794 }
1795
1796 uint32_t
1797 elink_cb_reg_read(struct bxe_softc *sc,
1798                   uint32_t         reg_addr)
1799 {
1800     return (REG_RD(sc, reg_addr));
1801 }
1802
1803 void
1804 elink_cb_reg_write(struct bxe_softc *sc,
1805                    uint32_t         reg_addr,
1806                    uint32_t         val)
1807 {
1808     REG_WR(sc, reg_addr, val);
1809 }
1810
1811 void
1812 elink_cb_reg_wb_write(struct bxe_softc *sc,
1813                       uint32_t         offset,
1814                       uint32_t         *wb_write,
1815                       uint16_t         len)
1816 {
1817     REG_WR_DMAE(sc, offset, wb_write, len);
1818 }
1819
1820 void
1821 elink_cb_reg_wb_read(struct bxe_softc *sc,
1822                      uint32_t         offset,
1823                      uint32_t         *wb_write,
1824                      uint16_t         len)
1825 {
1826     REG_RD_DMAE(sc, offset, wb_write, len);
1827 }
1828
1829 uint8_t
1830 elink_cb_path_id(struct bxe_softc *sc)
1831 {
1832     return (SC_PATH(sc));
1833 }
1834
1835 void
1836 elink_cb_event_log(struct bxe_softc     *sc,
1837                    const elink_log_id_t elink_log_id,
1838                    ...)
1839 {
1840     /* XXX */
1841     BLOGI(sc, "ELINK EVENT LOG (%d)\n", elink_log_id);
1842 }
1843
1844 static int
1845 bxe_set_spio(struct bxe_softc *sc,
1846              int              spio,
1847              uint32_t         mode)
1848 {
1849     uint32_t spio_reg;
1850
1851     /* Only 2 SPIOs are configurable */
1852     if ((spio != MISC_SPIO_SPIO4) && (spio != MISC_SPIO_SPIO5)) {
1853         BLOGE(sc, "Invalid SPIO 0x%x mode 0x%x\n", spio, mode);
1854         return (-1);
1855     }
1856
1857     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1858
1859     /* read SPIO and mask except the float bits */
1860     spio_reg = (REG_RD(sc, MISC_REG_SPIO) & MISC_SPIO_FLOAT);
1861
1862     switch (mode) {
1863     case MISC_SPIO_OUTPUT_LOW:
1864         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output low\n", spio);
1865         /* clear FLOAT and set CLR */
1866         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1867         spio_reg |=  (spio << MISC_SPIO_CLR_POS);
1868         break;
1869
1870     case MISC_SPIO_OUTPUT_HIGH:
1871         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> output high\n", spio);
1872         /* clear FLOAT and set SET */
1873         spio_reg &= ~(spio << MISC_SPIO_FLOAT_POS);
1874         spio_reg |=  (spio << MISC_SPIO_SET_POS);
1875         break;
1876
1877     case MISC_SPIO_INPUT_HI_Z:
1878         BLOGD(sc, DBG_LOAD, "Set SPIO 0x%x -> input\n", spio);
1879         /* set FLOAT */
1880         spio_reg |= (spio << MISC_SPIO_FLOAT_POS);
1881         break;
1882
1883     default:
1884         break;
1885     }
1886
1887     REG_WR(sc, MISC_REG_SPIO, spio_reg);
1888     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_SPIO);
1889
1890     return (0);
1891 }
1892
1893 static int
1894 bxe_gpio_read(struct bxe_softc *sc,
1895               int              gpio_num,
1896               uint8_t          port)
1897 {
1898     /* The GPIO should be swapped if swap register is set and active */
1899     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1900                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1901     int gpio_shift = (gpio_num +
1902                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1903     uint32_t gpio_mask = (1 << gpio_shift);
1904     uint32_t gpio_reg;
1905
1906     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1907         BLOGE(sc, "Invalid GPIO %d port 0x%x gpio_port %d gpio_shift %d"
1908             " gpio_mask 0x%x\n", gpio_num, port, gpio_port, gpio_shift,
1909             gpio_mask);
1910         return (-1);
1911     }
1912
1913     /* read GPIO value */
1914     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1915
1916     /* get the requested pin value */
1917     return ((gpio_reg & gpio_mask) == gpio_mask) ? 1 : 0;
1918 }
1919
1920 static int
1921 bxe_gpio_write(struct bxe_softc *sc,
1922                int              gpio_num,
1923                uint32_t         mode,
1924                uint8_t          port)
1925 {
1926     /* The GPIO should be swapped if swap register is set and active */
1927     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
1928                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
1929     int gpio_shift = (gpio_num +
1930                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
1931     uint32_t gpio_mask = (1 << gpio_shift);
1932     uint32_t gpio_reg;
1933
1934     if (gpio_num > MISC_REGISTERS_GPIO_3) {
1935         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
1936             " gpio_shift %d gpio_mask 0x%x\n",
1937             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
1938         return (-1);
1939     }
1940
1941     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1942
1943     /* read GPIO and mask except the float bits */
1944     gpio_reg = (REG_RD(sc, MISC_REG_GPIO) & MISC_REGISTERS_GPIO_FLOAT);
1945
1946     switch (mode) {
1947     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
1948         BLOGD(sc, DBG_PHY,
1949               "Set GPIO %d (shift %d) -> output low\n",
1950               gpio_num, gpio_shift);
1951         /* clear FLOAT and set CLR */
1952         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1953         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_CLR_POS);
1954         break;
1955
1956     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
1957         BLOGD(sc, DBG_PHY,
1958               "Set GPIO %d (shift %d) -> output high\n",
1959               gpio_num, gpio_shift);
1960         /* clear FLOAT and set SET */
1961         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1962         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_SET_POS);
1963         break;
1964
1965     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
1966         BLOGD(sc, DBG_PHY,
1967               "Set GPIO %d (shift %d) -> input\n",
1968               gpio_num, gpio_shift);
1969         /* set FLOAT */
1970         gpio_reg |= (gpio_mask << MISC_REGISTERS_GPIO_FLOAT_POS);
1971         break;
1972
1973     default:
1974         break;
1975     }
1976
1977     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
1978     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1979
1980     return (0);
1981 }
1982
1983 static int
1984 bxe_gpio_mult_write(struct bxe_softc *sc,
1985                     uint8_t          pins,
1986                     uint32_t         mode)
1987 {
1988     uint32_t gpio_reg;
1989
1990     /* any port swapping should be handled by caller */
1991
1992     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
1993
1994     /* read GPIO and mask except the float bits */
1995     gpio_reg = REG_RD(sc, MISC_REG_GPIO);
1996     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_FLOAT_POS);
1997     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_CLR_POS);
1998     gpio_reg &= ~(pins << MISC_REGISTERS_GPIO_SET_POS);
1999
2000     switch (mode) {
2001     case MISC_REGISTERS_GPIO_OUTPUT_LOW:
2002         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output low\n", pins);
2003         /* set CLR */
2004         gpio_reg |= (pins << MISC_REGISTERS_GPIO_CLR_POS);
2005         break;
2006
2007     case MISC_REGISTERS_GPIO_OUTPUT_HIGH:
2008         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> output high\n", pins);
2009         /* set SET */
2010         gpio_reg |= (pins << MISC_REGISTERS_GPIO_SET_POS);
2011         break;
2012
2013     case MISC_REGISTERS_GPIO_INPUT_HI_Z:
2014         BLOGD(sc, DBG_PHY, "Set GPIO 0x%x -> input\n", pins);
2015         /* set FLOAT */
2016         gpio_reg |= (pins << MISC_REGISTERS_GPIO_FLOAT_POS);
2017         break;
2018
2019     default:
2020         BLOGE(sc, "Invalid GPIO mode assignment pins 0x%x mode 0x%x"
2021             " gpio_reg 0x%x\n", pins, mode, gpio_reg);
2022         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2023         return (-1);
2024     }
2025
2026     REG_WR(sc, MISC_REG_GPIO, gpio_reg);
2027     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2028
2029     return (0);
2030 }
2031
2032 static int
2033 bxe_gpio_int_write(struct bxe_softc *sc,
2034                    int              gpio_num,
2035                    uint32_t         mode,
2036                    uint8_t          port)
2037 {
2038     /* The GPIO should be swapped if swap register is set and active */
2039     int gpio_port = ((REG_RD(sc, NIG_REG_PORT_SWAP) &&
2040                       REG_RD(sc, NIG_REG_STRAP_OVERRIDE)) ^ port);
2041     int gpio_shift = (gpio_num +
2042                       (gpio_port ? MISC_REGISTERS_GPIO_PORT_SHIFT : 0));
2043     uint32_t gpio_mask = (1 << gpio_shift);
2044     uint32_t gpio_reg;
2045
2046     if (gpio_num > MISC_REGISTERS_GPIO_3) {
2047         BLOGE(sc, "Invalid GPIO %d mode 0x%x port 0x%x gpio_port %d"
2048             " gpio_shift %d gpio_mask 0x%x\n",
2049             gpio_num, mode, port, gpio_port, gpio_shift, gpio_mask);
2050         return (-1);
2051     }
2052
2053     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2054
2055     /* read GPIO int */
2056     gpio_reg = REG_RD(sc, MISC_REG_GPIO_INT);
2057
2058     switch (mode) {
2059     case MISC_REGISTERS_GPIO_INT_OUTPUT_CLR:
2060         BLOGD(sc, DBG_PHY,
2061               "Clear GPIO INT %d (shift %d) -> output low\n",
2062               gpio_num, gpio_shift);
2063         /* clear SET and set CLR */
2064         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2065         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2066         break;
2067
2068     case MISC_REGISTERS_GPIO_INT_OUTPUT_SET:
2069         BLOGD(sc, DBG_PHY,
2070               "Set GPIO INT %d (shift %d) -> output high\n",
2071               gpio_num, gpio_shift);
2072         /* clear CLR and set SET */
2073         gpio_reg &= ~(gpio_mask << MISC_REGISTERS_GPIO_INT_CLR_POS);
2074         gpio_reg |=  (gpio_mask << MISC_REGISTERS_GPIO_INT_SET_POS);
2075         break;
2076
2077     default:
2078         break;
2079     }
2080
2081     REG_WR(sc, MISC_REG_GPIO_INT, gpio_reg);
2082     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_GPIO);
2083
2084     return (0);
2085 }
2086
2087 uint32_t
2088 elink_cb_gpio_read(struct bxe_softc *sc,
2089                    uint16_t         gpio_num,
2090                    uint8_t          port)
2091 {
2092     return (bxe_gpio_read(sc, gpio_num, port));
2093 }
2094
2095 uint8_t
2096 elink_cb_gpio_write(struct bxe_softc *sc,
2097                     uint16_t         gpio_num,
2098                     uint8_t          mode, /* 0=low 1=high */
2099                     uint8_t          port)
2100 {
2101     return (bxe_gpio_write(sc, gpio_num, mode, port));
2102 }
2103
2104 uint8_t
2105 elink_cb_gpio_mult_write(struct bxe_softc *sc,
2106                          uint8_t          pins,
2107                          uint8_t          mode) /* 0=low 1=high */
2108 {
2109     return (bxe_gpio_mult_write(sc, pins, mode));
2110 }
2111
2112 uint8_t
2113 elink_cb_gpio_int_write(struct bxe_softc *sc,
2114                         uint16_t         gpio_num,
2115                         uint8_t          mode, /* 0=low 1=high */
2116                         uint8_t          port)
2117 {
2118     return (bxe_gpio_int_write(sc, gpio_num, mode, port));
2119 }
2120
2121 void
2122 elink_cb_notify_link_changed(struct bxe_softc *sc)
2123 {
2124     REG_WR(sc, (MISC_REG_AEU_GENERAL_ATTN_12 +
2125                 (SC_FUNC(sc) * sizeof(uint32_t))), 1);
2126 }
2127
2128 /* send the MCP a request, block until there is a reply */
2129 uint32_t
2130 elink_cb_fw_command(struct bxe_softc *sc,
2131                     uint32_t         command,
2132                     uint32_t         param)
2133 {
2134     int mb_idx = SC_FW_MB_IDX(sc);
2135     uint32_t seq;
2136     uint32_t rc = 0;
2137     uint32_t cnt = 1;
2138     uint8_t delay = CHIP_REV_IS_SLOW(sc) ? 100 : 10;
2139
2140     BXE_FWMB_LOCK(sc);
2141
2142     seq = ++sc->fw_seq;
2143     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_param, param);
2144     SHMEM_WR(sc, func_mb[mb_idx].drv_mb_header, (command | seq));
2145
2146     BLOGD(sc, DBG_PHY,
2147           "wrote command 0x%08x to FW MB param 0x%08x\n",
2148           (command | seq), param);
2149
2150     /* Let the FW do it's magic. GIve it up to 5 seconds... */
2151     do {
2152         DELAY(delay * 1000);
2153         rc = SHMEM_RD(sc, func_mb[mb_idx].fw_mb_header);
2154     } while ((seq != (rc & FW_MSG_SEQ_NUMBER_MASK)) && (cnt++ < 500));
2155
2156     BLOGD(sc, DBG_PHY,
2157           "[after %d ms] read 0x%x seq 0x%x from FW MB\n",
2158           cnt*delay, rc, seq);
2159
2160     /* is this a reply to our command? */
2161     if (seq == (rc & FW_MSG_SEQ_NUMBER_MASK)) {
2162         rc &= FW_MSG_CODE_MASK;
2163     } else {
2164         /* Ruh-roh! */
2165         BLOGE(sc, "FW failed to respond!\n");
2166         // XXX bxe_fw_dump(sc);
2167         rc = 0;
2168     }
2169
2170     BXE_FWMB_UNLOCK(sc);
2171     return (rc);
2172 }
2173
2174 static uint32_t
2175 bxe_fw_command(struct bxe_softc *sc,
2176                uint32_t         command,
2177                uint32_t         param)
2178 {
2179     return (elink_cb_fw_command(sc, command, param));
2180 }
2181
2182 static void
2183 __storm_memset_dma_mapping(struct bxe_softc *sc,
2184                            uint32_t         addr,
2185                            bus_addr_t       mapping)
2186 {
2187     REG_WR(sc, addr, U64_LO(mapping));
2188     REG_WR(sc, (addr + 4), U64_HI(mapping));
2189 }
2190
2191 static void
2192 storm_memset_spq_addr(struct bxe_softc *sc,
2193                       bus_addr_t       mapping,
2194                       uint16_t         abs_fid)
2195 {
2196     uint32_t addr = (XSEM_REG_FAST_MEMORY +
2197                      XSTORM_SPQ_PAGE_BASE_OFFSET(abs_fid));
2198     __storm_memset_dma_mapping(sc, addr, mapping);
2199 }
2200
2201 static void
2202 storm_memset_vf_to_pf(struct bxe_softc *sc,
2203                       uint16_t         abs_fid,
2204                       uint16_t         pf_id)
2205 {
2206     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2207     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2208     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2209     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_VF_TO_PF_OFFSET(abs_fid)), pf_id);
2210 }
2211
2212 static void
2213 storm_memset_func_en(struct bxe_softc *sc,
2214                      uint16_t         abs_fid,
2215                      uint8_t          enable)
2216 {
2217     REG_WR8(sc, (BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2218     REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2219     REG_WR8(sc, (BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2220     REG_WR8(sc, (BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(abs_fid)), enable);
2221 }
2222
2223 static void
2224 storm_memset_eq_data(struct bxe_softc       *sc,
2225                      struct event_ring_data *eq_data,
2226                      uint16_t               pfid)
2227 {
2228     uint32_t addr;
2229     size_t size;
2230
2231     addr = (BAR_CSTRORM_INTMEM + CSTORM_EVENT_RING_DATA_OFFSET(pfid));
2232     size = sizeof(struct event_ring_data);
2233     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)eq_data);
2234 }
2235
2236 static void
2237 storm_memset_eq_prod(struct bxe_softc *sc,
2238                      uint16_t         eq_prod,
2239                      uint16_t         pfid)
2240 {
2241     uint32_t addr = (BAR_CSTRORM_INTMEM +
2242                      CSTORM_EVENT_RING_PROD_OFFSET(pfid));
2243     REG_WR16(sc, addr, eq_prod);
2244 }
2245
2246 /*
2247  * Post a slowpath command.
2248  *
2249  * A slowpath command is used to propogate a configuration change through
2250  * the controller in a controlled manner, allowing each STORM processor and
2251  * other H/W blocks to phase in the change.  The commands sent on the
2252  * slowpath are referred to as ramrods.  Depending on the ramrod used the
2253  * completion of the ramrod will occur in different ways.  Here's a
2254  * breakdown of ramrods and how they complete:
2255  *
2256  * RAMROD_CMD_ID_ETH_PORT_SETUP
2257  *   Used to setup the leading connection on a port.  Completes on the
2258  *   Receive Completion Queue (RCQ) of that port (typically fp[0]).
2259  *
2260  * RAMROD_CMD_ID_ETH_CLIENT_SETUP
2261  *   Used to setup an additional connection on a port.  Completes on the
2262  *   RCQ of the multi-queue/RSS connection being initialized.
2263  *
2264  * RAMROD_CMD_ID_ETH_STAT_QUERY
2265  *   Used to force the storm processors to update the statistics database
2266  *   in host memory.  This ramrod is send on the leading connection CID and
2267  *   completes as an index increment of the CSTORM on the default status
2268  *   block.
2269  *
2270  * RAMROD_CMD_ID_ETH_UPDATE
2271  *   Used to update the state of the leading connection, usually to udpate
2272  *   the RSS indirection table.  Completes on the RCQ of the leading
2273  *   connection. (Not currently used under FreeBSD until OS support becomes
2274  *   available.)
2275  *
2276  * RAMROD_CMD_ID_ETH_HALT
2277  *   Used when tearing down a connection prior to driver unload.  Completes
2278  *   on the RCQ of the multi-queue/RSS connection being torn down.  Don't
2279  *   use this on the leading connection.
2280  *
2281  * RAMROD_CMD_ID_ETH_SET_MAC
2282  *   Sets the Unicast/Broadcast/Multicast used by the port.  Completes on
2283  *   the RCQ of the leading connection.
2284  *
2285  * RAMROD_CMD_ID_ETH_CFC_DEL
2286  *   Used when tearing down a conneciton prior to driver unload.  Completes
2287  *   on the RCQ of the leading connection (since the current connection
2288  *   has been completely removed from controller memory).
2289  *
2290  * RAMROD_CMD_ID_ETH_PORT_DEL
2291  *   Used to tear down the leading connection prior to driver unload,
2292  *   typically fp[0].  Completes as an index increment of the CSTORM on the
2293  *   default status block.
2294  *
2295  * RAMROD_CMD_ID_ETH_FORWARD_SETUP
2296  *   Used for connection offload.  Completes on the RCQ of the multi-queue
2297  *   RSS connection that is being offloaded.  (Not currently used under
2298  *   FreeBSD.)
2299  *
2300  * There can only be one command pending per function.
2301  *
2302  * Returns:
2303  *   0 = Success, !0 = Failure.
2304  */
2305
2306 /* must be called under the spq lock */
2307 static inline
2308 struct eth_spe *bxe_sp_get_next(struct bxe_softc *sc)
2309 {
2310     struct eth_spe *next_spe = sc->spq_prod_bd;
2311
2312     if (sc->spq_prod_bd == sc->spq_last_bd) {
2313         /* wrap back to the first eth_spq */
2314         sc->spq_prod_bd = sc->spq;
2315         sc->spq_prod_idx = 0;
2316     } else {
2317         sc->spq_prod_bd++;
2318         sc->spq_prod_idx++;
2319     }
2320
2321     return (next_spe);
2322 }
2323
2324 /* must be called under the spq lock */
2325 static inline
2326 void bxe_sp_prod_update(struct bxe_softc *sc)
2327 {
2328     int func = SC_FUNC(sc);
2329
2330     /*
2331      * Make sure that BD data is updated before writing the producer.
2332      * BD data is written to the memory, the producer is read from the
2333      * memory, thus we need a full memory barrier to ensure the ordering.
2334      */
2335     mb();
2336
2337     REG_WR16(sc, (BAR_XSTRORM_INTMEM + XSTORM_SPQ_PROD_OFFSET(func)),
2338              sc->spq_prod_idx);
2339
2340     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
2341                       BUS_SPACE_BARRIER_WRITE);
2342 }
2343
2344 /**
2345  * bxe_is_contextless_ramrod - check if the current command ends on EQ
2346  *
2347  * @cmd:      command to check
2348  * @cmd_type: command type
2349  */
2350 static inline
2351 int bxe_is_contextless_ramrod(int cmd,
2352                               int cmd_type)
2353 {
2354     if ((cmd_type == NONE_CONNECTION_TYPE) ||
2355         (cmd == RAMROD_CMD_ID_ETH_FORWARD_SETUP) ||
2356         (cmd == RAMROD_CMD_ID_ETH_CLASSIFICATION_RULES) ||
2357         (cmd == RAMROD_CMD_ID_ETH_FILTER_RULES) ||
2358         (cmd == RAMROD_CMD_ID_ETH_MULTICAST_RULES) ||
2359         (cmd == RAMROD_CMD_ID_ETH_SET_MAC) ||
2360         (cmd == RAMROD_CMD_ID_ETH_RSS_UPDATE)) {
2361         return (TRUE);
2362     } else {
2363         return (FALSE);
2364     }
2365 }
2366
2367 /**
2368  * bxe_sp_post - place a single command on an SP ring
2369  *
2370  * @sc:         driver handle
2371  * @command:    command to place (e.g. SETUP, FILTER_RULES, etc.)
2372  * @cid:        SW CID the command is related to
2373  * @data_hi:    command private data address (high 32 bits)
2374  * @data_lo:    command private data address (low 32 bits)
2375  * @cmd_type:   command type (e.g. NONE, ETH)
2376  *
2377  * SP data is handled as if it's always an address pair, thus data fields are
2378  * not swapped to little endian in upper functions. Instead this function swaps
2379  * data as if it's two uint32 fields.
2380  */
2381 int
2382 bxe_sp_post(struct bxe_softc *sc,
2383             int              command,
2384             int              cid,
2385             uint32_t         data_hi,
2386             uint32_t         data_lo,
2387             int              cmd_type)
2388 {
2389     struct eth_spe *spe;
2390     uint16_t type;
2391     int common;
2392
2393     common = bxe_is_contextless_ramrod(command, cmd_type);
2394
2395     BXE_SP_LOCK(sc);
2396
2397     if (common) {
2398         if (!atomic_load_acq_long(&sc->eq_spq_left)) {
2399             BLOGE(sc, "EQ ring is full!\n");
2400             BXE_SP_UNLOCK(sc);
2401             return (-1);
2402         }
2403     } else {
2404         if (!atomic_load_acq_long(&sc->cq_spq_left)) {
2405             BLOGE(sc, "SPQ ring is full!\n");
2406             BXE_SP_UNLOCK(sc);
2407             return (-1);
2408         }
2409     }
2410
2411     spe = bxe_sp_get_next(sc);
2412
2413     /* CID needs port number to be encoded int it */
2414     spe->hdr.conn_and_cmd_data =
2415         htole32((command << SPE_HDR_T_CMD_ID_SHIFT) | HW_CID(sc, cid));
2416
2417     type = (cmd_type << SPE_HDR_T_CONN_TYPE_SHIFT) & SPE_HDR_T_CONN_TYPE;
2418
2419     /* TBD: Check if it works for VFs */
2420     type |= ((SC_FUNC(sc) << SPE_HDR_T_FUNCTION_ID_SHIFT) &
2421              SPE_HDR_T_FUNCTION_ID);
2422
2423     spe->hdr.type = htole16(type);
2424
2425     spe->data.update_data_addr.hi = htole32(data_hi);
2426     spe->data.update_data_addr.lo = htole32(data_lo);
2427
2428     /*
2429      * It's ok if the actual decrement is issued towards the memory
2430      * somewhere between the lock and unlock. Thus no more explict
2431      * memory barrier is needed.
2432      */
2433     if (common) {
2434         atomic_subtract_acq_long(&sc->eq_spq_left, 1);
2435     } else {
2436         atomic_subtract_acq_long(&sc->cq_spq_left, 1);
2437     }
2438
2439     BLOGD(sc, DBG_SP, "SPQE -> %#jx\n", (uintmax_t)sc->spq_dma.paddr);
2440     BLOGD(sc, DBG_SP, "FUNC_RDATA -> %p / %#jx\n",
2441           BXE_SP(sc, func_rdata), (uintmax_t)BXE_SP_MAPPING(sc, func_rdata));
2442     BLOGD(sc, DBG_SP,
2443           "SPQE[%x] (%x:%x) (cmd, common?) (%d,%d) hw_cid %x data (%x:%x) type(0x%x) left (CQ, EQ) (%lx,%lx)\n",
2444           sc->spq_prod_idx,
2445           (uint32_t)U64_HI(sc->spq_dma.paddr),
2446           (uint32_t)(U64_LO(sc->spq_dma.paddr) + (uint8_t *)sc->spq_prod_bd - (uint8_t *)sc->spq),
2447           command,
2448           common,
2449           HW_CID(sc, cid),
2450           data_hi,
2451           data_lo,
2452           type,
2453           atomic_load_acq_long(&sc->cq_spq_left),
2454           atomic_load_acq_long(&sc->eq_spq_left));
2455
2456     bxe_sp_prod_update(sc);
2457
2458     BXE_SP_UNLOCK(sc);
2459     return (0);
2460 }
2461
2462 /**
2463  * bxe_debug_print_ind_table - prints the indirection table configuration.
2464  *
2465  * @sc: driver hanlde
2466  * @p:  pointer to rss configuration
2467  */
2468
2469 /*
2470  * FreeBSD Device probe function.
2471  *
2472  * Compares the device found to the driver's list of supported devices and
2473  * reports back to the bsd loader whether this is the right driver for the device.
2474  * This is the driver entry function called from the "kldload" command.
2475  *
2476  * Returns:
2477  *   BUS_PROBE_DEFAULT on success, positive value on failure.
2478  */
2479 static int
2480 bxe_probe(device_t dev)
2481 {
2482     struct bxe_softc *sc;
2483     struct bxe_device_type *t;
2484     char *descbuf;
2485     uint16_t did, sdid, svid, vid;
2486
2487     /* Find our device structure */
2488     sc = device_get_softc(dev);
2489     sc->dev = dev;
2490     t = bxe_devs;
2491
2492     /* Get the data for the device to be probed. */
2493     vid  = pci_get_vendor(dev);
2494     did  = pci_get_device(dev);
2495     svid = pci_get_subvendor(dev);
2496     sdid = pci_get_subdevice(dev);
2497
2498     BLOGD(sc, DBG_LOAD,
2499           "%s(); VID = 0x%04X, DID = 0x%04X, SVID = 0x%04X, "
2500           "SDID = 0x%04X\n", __FUNCTION__, vid, did, svid, sdid);
2501
2502     /* Look through the list of known devices for a match. */
2503     while (t->bxe_name != NULL) {
2504         if ((vid == t->bxe_vid) && (did == t->bxe_did) &&
2505             ((svid == t->bxe_svid) || (t->bxe_svid == PCI_ANY_ID)) &&
2506             ((sdid == t->bxe_sdid) || (t->bxe_sdid == PCI_ANY_ID))) {
2507             descbuf = malloc(BXE_DEVDESC_MAX, M_TEMP, M_NOWAIT);
2508             if (descbuf == NULL)
2509                 return (ENOMEM);
2510
2511             /* Print out the device identity. */
2512             snprintf(descbuf, BXE_DEVDESC_MAX,
2513                      "%s (%c%d) BXE v:%s\n", t->bxe_name,
2514                      (((pci_read_config(dev, PCIR_REVID, 4) &
2515                         0xf0) >> 4) + 'A'),
2516                      (pci_read_config(dev, PCIR_REVID, 4) & 0xf),
2517                      BXE_DRIVER_VERSION);
2518
2519             device_set_desc_copy(dev, descbuf);
2520             free(descbuf, M_TEMP);
2521             return (BUS_PROBE_DEFAULT);
2522         }
2523         t++;
2524     }
2525
2526     return (ENXIO);
2527 }
2528
2529 static void
2530 bxe_init_mutexes(struct bxe_softc *sc)
2531 {
2532 #ifdef BXE_CORE_LOCK_SX
2533     snprintf(sc->core_sx_name, sizeof(sc->core_sx_name),
2534              "bxe%d_core_lock", sc->unit);
2535     sx_init(&sc->core_sx, sc->core_sx_name);
2536 #else
2537     snprintf(sc->core_mtx_name, sizeof(sc->core_mtx_name),
2538              "bxe%d_core_lock", sc->unit);
2539     mtx_init(&sc->core_mtx, sc->core_mtx_name, NULL, MTX_DEF);
2540 #endif
2541
2542     snprintf(sc->sp_mtx_name, sizeof(sc->sp_mtx_name),
2543              "bxe%d_sp_lock", sc->unit);
2544     mtx_init(&sc->sp_mtx, sc->sp_mtx_name, NULL, MTX_DEF);
2545
2546     snprintf(sc->dmae_mtx_name, sizeof(sc->dmae_mtx_name),
2547              "bxe%d_dmae_lock", sc->unit);
2548     mtx_init(&sc->dmae_mtx, sc->dmae_mtx_name, NULL, MTX_DEF);
2549
2550     snprintf(sc->port.phy_mtx_name, sizeof(sc->port.phy_mtx_name),
2551              "bxe%d_phy_lock", sc->unit);
2552     mtx_init(&sc->port.phy_mtx, sc->port.phy_mtx_name, NULL, MTX_DEF);
2553
2554     snprintf(sc->fwmb_mtx_name, sizeof(sc->fwmb_mtx_name),
2555              "bxe%d_fwmb_lock", sc->unit);
2556     mtx_init(&sc->fwmb_mtx, sc->fwmb_mtx_name, NULL, MTX_DEF);
2557
2558     snprintf(sc->print_mtx_name, sizeof(sc->print_mtx_name),
2559              "bxe%d_print_lock", sc->unit);
2560     mtx_init(&(sc->print_mtx), sc->print_mtx_name, NULL, MTX_DEF);
2561
2562     snprintf(sc->stats_mtx_name, sizeof(sc->stats_mtx_name),
2563              "bxe%d_stats_lock", sc->unit);
2564     mtx_init(&(sc->stats_mtx), sc->stats_mtx_name, NULL, MTX_DEF);
2565
2566     snprintf(sc->mcast_mtx_name, sizeof(sc->mcast_mtx_name),
2567              "bxe%d_mcast_lock", sc->unit);
2568     mtx_init(&(sc->mcast_mtx), sc->mcast_mtx_name, NULL, MTX_DEF);
2569 }
2570
2571 static void
2572 bxe_release_mutexes(struct bxe_softc *sc)
2573 {
2574 #ifdef BXE_CORE_LOCK_SX
2575     sx_destroy(&sc->core_sx);
2576 #else
2577     if (mtx_initialized(&sc->core_mtx)) {
2578         mtx_destroy(&sc->core_mtx);
2579     }
2580 #endif
2581
2582     if (mtx_initialized(&sc->sp_mtx)) {
2583         mtx_destroy(&sc->sp_mtx);
2584     }
2585
2586     if (mtx_initialized(&sc->dmae_mtx)) {
2587         mtx_destroy(&sc->dmae_mtx);
2588     }
2589
2590     if (mtx_initialized(&sc->port.phy_mtx)) {
2591         mtx_destroy(&sc->port.phy_mtx);
2592     }
2593
2594     if (mtx_initialized(&sc->fwmb_mtx)) {
2595         mtx_destroy(&sc->fwmb_mtx);
2596     }
2597
2598     if (mtx_initialized(&sc->print_mtx)) {
2599         mtx_destroy(&sc->print_mtx);
2600     }
2601
2602     if (mtx_initialized(&sc->stats_mtx)) {
2603         mtx_destroy(&sc->stats_mtx);
2604     }
2605
2606     if (mtx_initialized(&sc->mcast_mtx)) {
2607         mtx_destroy(&sc->mcast_mtx);
2608     }
2609 }
2610
2611 static void
2612 bxe_tx_disable(struct bxe_softc* sc)
2613 {
2614     struct ifnet *ifp = sc->ifnet;
2615
2616     /* tell the stack the driver is stopped and TX queue is full */
2617     if (ifp != NULL) {
2618         ifp->if_drv_flags = 0;
2619     }
2620 }
2621
2622 static void
2623 bxe_drv_pulse(struct bxe_softc *sc)
2624 {
2625     SHMEM_WR(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb,
2626              sc->fw_drv_pulse_wr_seq);
2627 }
2628
2629 static inline uint16_t
2630 bxe_tx_avail(struct bxe_softc *sc,
2631              struct bxe_fastpath *fp)
2632 {
2633     int16_t  used;
2634     uint16_t prod;
2635     uint16_t cons;
2636
2637     prod = fp->tx_bd_prod;
2638     cons = fp->tx_bd_cons;
2639
2640     used = SUB_S16(prod, cons);
2641
2642     return (int16_t)(sc->tx_ring_size) - used;
2643 }
2644
2645 static inline int
2646 bxe_tx_queue_has_work(struct bxe_fastpath *fp)
2647 {
2648     uint16_t hw_cons;
2649
2650     mb(); /* status block fields can change */
2651     hw_cons = le16toh(*fp->tx_cons_sb);
2652     return (hw_cons != fp->tx_pkt_cons);
2653 }
2654
2655 static inline uint8_t
2656 bxe_has_tx_work(struct bxe_fastpath *fp)
2657 {
2658     /* expand this for multi-cos if ever supported */
2659     return (bxe_tx_queue_has_work(fp)) ? TRUE : FALSE;
2660 }
2661
2662 static inline int
2663 bxe_has_rx_work(struct bxe_fastpath *fp)
2664 {
2665     uint16_t rx_cq_cons_sb;
2666
2667     mb(); /* status block fields can change */
2668     rx_cq_cons_sb = le16toh(*fp->rx_cq_cons_sb);
2669     if ((rx_cq_cons_sb & RCQ_MAX) == RCQ_MAX)
2670         rx_cq_cons_sb++;
2671     return (fp->rx_cq_cons != rx_cq_cons_sb);
2672 }
2673
2674 static void
2675 bxe_sp_event(struct bxe_softc    *sc,
2676              struct bxe_fastpath *fp,
2677              union eth_rx_cqe    *rr_cqe)
2678 {
2679     int cid = SW_CID(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2680     int command = CQE_CMD(rr_cqe->ramrod_cqe.conn_and_cmd_data);
2681     enum ecore_queue_cmd drv_cmd = ECORE_Q_CMD_MAX;
2682     struct ecore_queue_sp_obj *q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
2683
2684     BLOGD(sc, DBG_SP, "fp=%d cid=%d got ramrod #%d state is %x type is %d\n",
2685           fp->index, cid, command, sc->state, rr_cqe->ramrod_cqe.ramrod_type);
2686
2687     switch (command) {
2688     case (RAMROD_CMD_ID_ETH_CLIENT_UPDATE):
2689         BLOGD(sc, DBG_SP, "got UPDATE ramrod. CID %d\n", cid);
2690         drv_cmd = ECORE_Q_CMD_UPDATE;
2691         break;
2692
2693     case (RAMROD_CMD_ID_ETH_CLIENT_SETUP):
2694         BLOGD(sc, DBG_SP, "got MULTI[%d] setup ramrod\n", cid);
2695         drv_cmd = ECORE_Q_CMD_SETUP;
2696         break;
2697
2698     case (RAMROD_CMD_ID_ETH_TX_QUEUE_SETUP):
2699         BLOGD(sc, DBG_SP, "got MULTI[%d] tx-only setup ramrod\n", cid);
2700         drv_cmd = ECORE_Q_CMD_SETUP_TX_ONLY;
2701         break;
2702
2703     case (RAMROD_CMD_ID_ETH_HALT):
2704         BLOGD(sc, DBG_SP, "got MULTI[%d] halt ramrod\n", cid);
2705         drv_cmd = ECORE_Q_CMD_HALT;
2706         break;
2707
2708     case (RAMROD_CMD_ID_ETH_TERMINATE):
2709         BLOGD(sc, DBG_SP, "got MULTI[%d] teminate ramrod\n", cid);
2710         drv_cmd = ECORE_Q_CMD_TERMINATE;
2711         break;
2712
2713     case (RAMROD_CMD_ID_ETH_EMPTY):
2714         BLOGD(sc, DBG_SP, "got MULTI[%d] empty ramrod\n", cid);
2715         drv_cmd = ECORE_Q_CMD_EMPTY;
2716         break;
2717
2718     default:
2719         BLOGD(sc, DBG_SP, "ERROR: unexpected MC reply (%d) on fp[%d]\n",
2720               command, fp->index);
2721         return;
2722     }
2723
2724     if ((drv_cmd != ECORE_Q_CMD_MAX) &&
2725         q_obj->complete_cmd(sc, q_obj, drv_cmd)) {
2726         /*
2727          * q_obj->complete_cmd() failure means that this was
2728          * an unexpected completion.
2729          *
2730          * In this case we don't want to increase the sc->spq_left
2731          * because apparently we haven't sent this command the first
2732          * place.
2733          */
2734         // bxe_panic(sc, ("Unexpected SP completion\n"));
2735         return;
2736     }
2737
2738     atomic_add_acq_long(&sc->cq_spq_left, 1);
2739
2740     BLOGD(sc, DBG_SP, "sc->cq_spq_left 0x%lx\n",
2741           atomic_load_acq_long(&sc->cq_spq_left));
2742 }
2743
2744 /*
2745  * The current mbuf is part of an aggregation. Move the mbuf into the TPA
2746  * aggregation queue, put an empty mbuf back onto the receive chain, and mark
2747  * the current aggregation queue as in-progress.
2748  */
2749 static void
2750 bxe_tpa_start(struct bxe_softc            *sc,
2751               struct bxe_fastpath         *fp,
2752               uint16_t                    queue,
2753               uint16_t                    cons,
2754               uint16_t                    prod,
2755               struct eth_fast_path_rx_cqe *cqe)
2756 {
2757     struct bxe_sw_rx_bd tmp_bd;
2758     struct bxe_sw_rx_bd *rx_buf;
2759     struct eth_rx_bd *rx_bd;
2760     int max_agg_queues;
2761     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
2762     uint16_t index;
2763
2764     BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA START "
2765                        "cons=%d prod=%d\n",
2766           fp->index, queue, cons, prod);
2767
2768     max_agg_queues = MAX_AGG_QS(sc);
2769
2770     KASSERT((queue < max_agg_queues),
2771             ("fp[%02d] invalid aggr queue (%d >= %d)!",
2772              fp->index, queue, max_agg_queues));
2773
2774     KASSERT((tpa_info->state == BXE_TPA_STATE_STOP),
2775             ("fp[%02d].tpa[%02d] starting aggr on queue not stopped!",
2776              fp->index, queue));
2777
2778     /* copy the existing mbuf and mapping from the TPA pool */
2779     tmp_bd = tpa_info->bd;
2780
2781     if (tmp_bd.m == NULL) {
2782         uint32_t *tmp;
2783
2784         tmp = (uint32_t *)cqe;
2785
2786         BLOGE(sc, "fp[%02d].tpa[%02d] cons[%d] prod[%d]mbuf not allocated!\n",
2787               fp->index, queue, cons, prod);
2788         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2789             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2790             
2791         /* XXX Error handling? */
2792         return;
2793     }
2794
2795     /* change the TPA queue to the start state */
2796     tpa_info->state            = BXE_TPA_STATE_START;
2797     tpa_info->placement_offset = cqe->placement_offset;
2798     tpa_info->parsing_flags    = le16toh(cqe->pars_flags.flags);
2799     tpa_info->vlan_tag         = le16toh(cqe->vlan_tag);
2800     tpa_info->len_on_bd        = le16toh(cqe->len_on_bd);
2801
2802     fp->rx_tpa_queue_used |= (1 << queue);
2803
2804     /*
2805      * If all the buffer descriptors are filled with mbufs then fill in
2806      * the current consumer index with a new BD. Else if a maximum Rx
2807      * buffer limit is imposed then fill in the next producer index.
2808      */
2809     index = (sc->max_rx_bufs != RX_BD_USABLE) ?
2810                 prod : cons;
2811
2812     /* move the received mbuf and mapping to TPA pool */
2813     tpa_info->bd = fp->rx_mbuf_chain[cons];
2814
2815     /* release any existing RX BD mbuf mappings */
2816     if (cons != index) {
2817         rx_buf = &fp->rx_mbuf_chain[cons];
2818
2819         if (rx_buf->m_map != NULL) {
2820             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
2821                             BUS_DMASYNC_POSTREAD);
2822             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
2823         }
2824
2825         /*
2826          * We get here when the maximum number of rx buffers is less than
2827          * RX_BD_USABLE. The mbuf is already saved above so it's OK to NULL
2828          * it out here without concern of a memory leak.
2829          */
2830         fp->rx_mbuf_chain[cons].m = NULL;
2831     }
2832
2833     /* update the Rx SW BD with the mbuf info from the TPA pool */
2834     fp->rx_mbuf_chain[index] = tmp_bd;
2835
2836     /* update the Rx BD with the empty mbuf phys address from the TPA pool */
2837     rx_bd = &fp->rx_chain[index];
2838     rx_bd->addr_hi = htole32(U64_HI(tpa_info->seg.ds_addr));
2839     rx_bd->addr_lo = htole32(U64_LO(tpa_info->seg.ds_addr));
2840 }
2841
2842 /*
2843  * When a TPA aggregation is completed, loop through the individual mbufs
2844  * of the aggregation, combining them into a single mbuf which will be sent
2845  * up the stack. Refill all freed SGEs with mbufs as we go along.
2846  */
2847 static int
2848 bxe_fill_frag_mbuf(struct bxe_softc          *sc,
2849                    struct bxe_fastpath       *fp,
2850                    struct bxe_sw_tpa_info    *tpa_info,
2851                    uint16_t                  queue,
2852                    uint16_t                  pages,
2853                    struct mbuf               *m,
2854                                struct eth_end_agg_rx_cqe *cqe,
2855                    uint16_t                  cqe_idx)
2856 {
2857     struct mbuf *m_frag;
2858     uint32_t frag_len, frag_size, i;
2859     uint16_t sge_idx;
2860     int rc = 0;
2861     int j;
2862
2863     frag_size = le16toh(cqe->pkt_len) - tpa_info->len_on_bd;
2864
2865     BLOGD(sc, DBG_LRO,
2866           "fp[%02d].tpa[%02d] TPA fill len_on_bd=%d frag_size=%d pages=%d\n",
2867           fp->index, queue, tpa_info->len_on_bd, frag_size, pages);
2868
2869     /* make sure the aggregated frame is not too big to handle */
2870     if (pages > 8 * PAGES_PER_SGE) {
2871
2872         uint32_t *tmp = (uint32_t *)cqe;
2873
2874         BLOGE(sc, "fp[%02d].sge[0x%04x] has too many pages (%d)! "
2875                   "pkt_len=%d len_on_bd=%d frag_size=%d\n",
2876               fp->index, cqe_idx, pages, le16toh(cqe->pkt_len),
2877               tpa_info->len_on_bd, frag_size);
2878
2879         BLOGE(sc, "cqe [0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x]\n",
2880             *tmp, *(tmp+1), *(tmp+2), *(tmp+3), *(tmp+4), *(tmp+5), *(tmp+6), *(tmp+7)); 
2881
2882         bxe_panic(sc, ("sge page count error\n"));
2883         return (EINVAL);
2884     }
2885
2886     /*
2887      * Scan through the scatter gather list pulling individual mbufs into a
2888      * single mbuf for the host stack.
2889      */
2890     for (i = 0, j = 0; i < pages; i += PAGES_PER_SGE, j++) {
2891         sge_idx = RX_SGE(le16toh(cqe->sgl_or_raw_data.sgl[j]));
2892
2893         /*
2894          * Firmware gives the indices of the SGE as if the ring is an array
2895          * (meaning that the "next" element will consume 2 indices).
2896          */
2897         frag_len = min(frag_size, (uint32_t)(SGE_PAGES));
2898
2899         BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA fill i=%d j=%d "
2900                            "sge_idx=%d frag_size=%d frag_len=%d\n",
2901               fp->index, queue, i, j, sge_idx, frag_size, frag_len);
2902
2903         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
2904
2905         /* allocate a new mbuf for the SGE */
2906         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
2907         if (rc) {
2908             /* Leave all remaining SGEs in the ring! */
2909             return (rc);
2910         }
2911
2912         /* update the fragment length */
2913         m_frag->m_len = frag_len;
2914
2915         /* concatenate the fragment to the head mbuf */
2916         m_cat(m, m_frag);
2917         fp->eth_q_stats.mbuf_alloc_sge--;
2918
2919         /* update the TPA mbuf size and remaining fragment size */
2920         m->m_pkthdr.len += frag_len;
2921         frag_size -= frag_len;
2922     }
2923
2924     BLOGD(sc, DBG_LRO,
2925           "fp[%02d].tpa[%02d] TPA fill done frag_size=%d\n",
2926           fp->index, queue, frag_size);
2927
2928     return (rc);
2929 }
2930
2931 static inline void
2932 bxe_clear_sge_mask_next_elems(struct bxe_fastpath *fp)
2933 {
2934     int i, j;
2935
2936     for (i = 1; i <= RX_SGE_NUM_PAGES; i++) {
2937         int idx = RX_SGE_TOTAL_PER_PAGE * i - 1;
2938
2939         for (j = 0; j < 2; j++) {
2940             BIT_VEC64_CLEAR_BIT(fp->sge_mask, idx);
2941             idx--;
2942         }
2943     }
2944 }
2945
2946 static inline void
2947 bxe_init_sge_ring_bit_mask(struct bxe_fastpath *fp)
2948 {
2949     /* set the mask to all 1's, it's faster to compare to 0 than to 0xf's */
2950     memset(fp->sge_mask, 0xff, sizeof(fp->sge_mask));
2951
2952     /*
2953      * Clear the two last indices in the page to 1. These are the indices that
2954      * correspond to the "next" element, hence will never be indicated and
2955      * should be removed from the calculations.
2956      */
2957     bxe_clear_sge_mask_next_elems(fp);
2958 }
2959
2960 static inline void
2961 bxe_update_last_max_sge(struct bxe_fastpath *fp,
2962                         uint16_t            idx)
2963 {
2964     uint16_t last_max = fp->last_max_sge;
2965
2966     if (SUB_S16(idx, last_max) > 0) {
2967         fp->last_max_sge = idx;
2968     }
2969 }
2970
2971 static inline void
2972 bxe_update_sge_prod(struct bxe_softc          *sc,
2973                     struct bxe_fastpath       *fp,
2974                     uint16_t                  sge_len,
2975                     union eth_sgl_or_raw_data *cqe)
2976 {
2977     uint16_t last_max, last_elem, first_elem;
2978     uint16_t delta = 0;
2979     uint16_t i;
2980
2981     if (!sge_len) {
2982         return;
2983     }
2984
2985     /* first mark all used pages */
2986     for (i = 0; i < sge_len; i++) {
2987         BIT_VEC64_CLEAR_BIT(fp->sge_mask,
2988                             RX_SGE(le16toh(cqe->sgl[i])));
2989     }
2990
2991     BLOGD(sc, DBG_LRO,
2992           "fp[%02d] fp_cqe->sgl[%d] = %d\n",
2993           fp->index, sge_len - 1,
2994           le16toh(cqe->sgl[sge_len - 1]));
2995
2996     /* assume that the last SGE index is the biggest */
2997     bxe_update_last_max_sge(fp,
2998                             le16toh(cqe->sgl[sge_len - 1]));
2999
3000     last_max = RX_SGE(fp->last_max_sge);
3001     last_elem = last_max >> BIT_VEC64_ELEM_SHIFT;
3002     first_elem = RX_SGE(fp->rx_sge_prod) >> BIT_VEC64_ELEM_SHIFT;
3003
3004     /* if ring is not full */
3005     if (last_elem + 1 != first_elem) {
3006         last_elem++;
3007     }
3008
3009     /* now update the prod */
3010     for (i = first_elem; i != last_elem; i = RX_SGE_NEXT_MASK_ELEM(i)) {
3011         if (__predict_true(fp->sge_mask[i])) {
3012             break;
3013         }
3014
3015         fp->sge_mask[i] = BIT_VEC64_ELEM_ONE_MASK;
3016         delta += BIT_VEC64_ELEM_SZ;
3017     }
3018
3019     if (delta > 0) {
3020         fp->rx_sge_prod += delta;
3021         /* clear page-end entries */
3022         bxe_clear_sge_mask_next_elems(fp);
3023     }
3024
3025     BLOGD(sc, DBG_LRO,
3026           "fp[%02d] fp->last_max_sge=%d fp->rx_sge_prod=%d\n",
3027           fp->index, fp->last_max_sge, fp->rx_sge_prod);
3028 }
3029
3030 /*
3031  * The aggregation on the current TPA queue has completed. Pull the individual
3032  * mbuf fragments together into a single mbuf, perform all necessary checksum
3033  * calculations, and send the resuting mbuf to the stack.
3034  */
3035 static void
3036 bxe_tpa_stop(struct bxe_softc          *sc,
3037              struct bxe_fastpath       *fp,
3038              struct bxe_sw_tpa_info    *tpa_info,
3039              uint16_t                  queue,
3040              uint16_t                  pages,
3041                          struct eth_end_agg_rx_cqe *cqe,
3042              uint16_t                  cqe_idx)
3043 {
3044     struct ifnet *ifp = sc->ifnet;
3045     struct mbuf *m;
3046     int rc = 0;
3047
3048     BLOGD(sc, DBG_LRO,
3049           "fp[%02d].tpa[%02d] pad=%d pkt_len=%d pages=%d vlan=%d\n",
3050           fp->index, queue, tpa_info->placement_offset,
3051           le16toh(cqe->pkt_len), pages, tpa_info->vlan_tag);
3052
3053     m = tpa_info->bd.m;
3054
3055     /* allocate a replacement before modifying existing mbuf */
3056     rc = bxe_alloc_rx_tpa_mbuf(fp, queue);
3057     if (rc) {
3058         /* drop the frame and log an error */
3059         fp->eth_q_stats.rx_soft_errors++;
3060         goto bxe_tpa_stop_exit;
3061     }
3062
3063     /* we have a replacement, fixup the current mbuf */
3064     m_adj(m, tpa_info->placement_offset);
3065     m->m_pkthdr.len = m->m_len = tpa_info->len_on_bd;
3066
3067     /* mark the checksums valid (taken care of by the firmware) */
3068     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3069     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3070     m->m_pkthdr.csum_data = 0xffff;
3071     m->m_pkthdr.csum_flags |= (CSUM_IP_CHECKED |
3072                                CSUM_IP_VALID   |
3073                                CSUM_DATA_VALID |
3074                                CSUM_PSEUDO_HDR);
3075
3076     /* aggregate all of the SGEs into a single mbuf */
3077     rc = bxe_fill_frag_mbuf(sc, fp, tpa_info, queue, pages, m, cqe, cqe_idx);
3078     if (rc) {
3079         /* drop the packet and log an error */
3080         fp->eth_q_stats.rx_soft_errors++;
3081         m_freem(m);
3082     } else {
3083         if (tpa_info->parsing_flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3084             m->m_pkthdr.ether_vtag = tpa_info->vlan_tag;
3085             m->m_flags |= M_VLANTAG;
3086         }
3087
3088         /* assign packet to this interface interface */
3089         m->m_pkthdr.rcvif = ifp;
3090
3091 #if __FreeBSD_version >= 800000
3092         /* specify what RSS queue was used for this flow */
3093         m->m_pkthdr.flowid = fp->index;
3094         BXE_SET_FLOWID(m);
3095 #endif
3096
3097         ifp->if_ipackets++;
3098         fp->eth_q_stats.rx_tpa_pkts++;
3099
3100         /* pass the frame to the stack */
3101         (*ifp->if_input)(ifp, m);
3102     }
3103
3104     /* we passed an mbuf up the stack or dropped the frame */
3105     fp->eth_q_stats.mbuf_alloc_tpa--;
3106
3107 bxe_tpa_stop_exit:
3108
3109     fp->rx_tpa_info[queue].state = BXE_TPA_STATE_STOP;
3110     fp->rx_tpa_queue_used &= ~(1 << queue);
3111 }
3112
3113 static uint8_t
3114 bxe_service_rxsgl(
3115                  struct bxe_fastpath *fp,
3116                  uint16_t len,
3117                  uint16_t lenonbd,
3118                  struct mbuf *m,
3119                  struct eth_fast_path_rx_cqe *cqe_fp)
3120 {
3121     struct mbuf *m_frag;
3122     uint16_t frags, frag_len;
3123     uint16_t sge_idx = 0;
3124     uint16_t j;
3125     uint8_t i, rc = 0;
3126     uint32_t frag_size;
3127
3128     /* adjust the mbuf */
3129     m->m_len = lenonbd;
3130
3131     frag_size =  len - lenonbd;
3132     frags = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3133
3134     for (i = 0, j = 0; i < frags; i += PAGES_PER_SGE, j++) {
3135         sge_idx = RX_SGE(le16toh(cqe_fp->sgl_or_raw_data.sgl[j]));
3136
3137         m_frag = fp->rx_sge_mbuf_chain[sge_idx].m;
3138         frag_len = min(frag_size, (uint32_t)(SGE_PAGE_SIZE));
3139         m_frag->m_len = frag_len;
3140
3141        /* allocate a new mbuf for the SGE */
3142         rc = bxe_alloc_rx_sge_mbuf(fp, sge_idx);
3143         if (rc) {
3144             /* Leave all remaining SGEs in the ring! */
3145             return (rc);
3146         }
3147         fp->eth_q_stats.mbuf_alloc_sge--;
3148
3149         /* concatenate the fragment to the head mbuf */
3150         m_cat(m, m_frag);
3151
3152         frag_size -= frag_len;
3153     }
3154
3155     bxe_update_sge_prod(fp->sc, fp, frags, &cqe_fp->sgl_or_raw_data);
3156
3157     return rc;
3158 }
3159
3160 static uint8_t
3161 bxe_rxeof(struct bxe_softc    *sc,
3162           struct bxe_fastpath *fp)
3163 {
3164     struct ifnet *ifp = sc->ifnet;
3165     uint16_t bd_cons, bd_prod, bd_prod_fw, comp_ring_cons;
3166     uint16_t hw_cq_cons, sw_cq_cons, sw_cq_prod;
3167     int rx_pkts = 0;
3168     int rc = 0;
3169
3170     BXE_FP_RX_LOCK(fp);
3171
3172     /* CQ "next element" is of the size of the regular element */
3173     hw_cq_cons = le16toh(*fp->rx_cq_cons_sb);
3174     if ((hw_cq_cons & RCQ_USABLE_PER_PAGE) == RCQ_USABLE_PER_PAGE) {
3175         hw_cq_cons++;
3176     }
3177
3178     bd_cons = fp->rx_bd_cons;
3179     bd_prod = fp->rx_bd_prod;
3180     bd_prod_fw = bd_prod;
3181     sw_cq_cons = fp->rx_cq_cons;
3182     sw_cq_prod = fp->rx_cq_prod;
3183
3184     /*
3185      * Memory barrier necessary as speculative reads of the rx
3186      * buffer can be ahead of the index in the status block
3187      */
3188     rmb();
3189
3190     BLOGD(sc, DBG_RX,
3191           "fp[%02d] Rx START hw_cq_cons=%u sw_cq_cons=%u\n",
3192           fp->index, hw_cq_cons, sw_cq_cons);
3193
3194     while (sw_cq_cons != hw_cq_cons) {
3195         struct bxe_sw_rx_bd *rx_buf = NULL;
3196         union eth_rx_cqe *cqe;
3197         struct eth_fast_path_rx_cqe *cqe_fp;
3198         uint8_t cqe_fp_flags;
3199         enum eth_rx_cqe_type cqe_fp_type;
3200         uint16_t len, lenonbd,  pad;
3201         struct mbuf *m = NULL;
3202
3203         comp_ring_cons = RCQ(sw_cq_cons);
3204         bd_prod = RX_BD(bd_prod);
3205         bd_cons = RX_BD(bd_cons);
3206
3207         cqe          = &fp->rcq_chain[comp_ring_cons];
3208         cqe_fp       = &cqe->fast_path_cqe;
3209         cqe_fp_flags = cqe_fp->type_error_flags;
3210         cqe_fp_type  = cqe_fp_flags & ETH_FAST_PATH_RX_CQE_TYPE;
3211
3212         BLOGD(sc, DBG_RX,
3213               "fp[%02d] Rx hw_cq_cons=%d hw_sw_cons=%d "
3214               "BD prod=%d cons=%d CQE type=0x%x err=0x%x "
3215               "status=0x%x rss_hash=0x%x vlan=0x%x len=%u lenonbd=%u\n",
3216               fp->index,
3217               hw_cq_cons,
3218               sw_cq_cons,
3219               bd_prod,
3220               bd_cons,
3221               CQE_TYPE(cqe_fp_flags),
3222               cqe_fp_flags,
3223               cqe_fp->status_flags,
3224               le32toh(cqe_fp->rss_hash_result),
3225               le16toh(cqe_fp->vlan_tag),
3226               le16toh(cqe_fp->pkt_len_or_gro_seg_len),
3227               le16toh(cqe_fp->len_on_bd));
3228
3229         /* is this a slowpath msg? */
3230         if (__predict_false(CQE_TYPE_SLOW(cqe_fp_type))) {
3231             bxe_sp_event(sc, fp, cqe);
3232             goto next_cqe;
3233         }
3234
3235         rx_buf = &fp->rx_mbuf_chain[bd_cons];
3236
3237         if (!CQE_TYPE_FAST(cqe_fp_type)) {
3238             struct bxe_sw_tpa_info *tpa_info;
3239             uint16_t frag_size, pages;
3240             uint8_t queue;
3241
3242             if (CQE_TYPE_START(cqe_fp_type)) {
3243                 bxe_tpa_start(sc, fp, cqe_fp->queue_index,
3244                               bd_cons, bd_prod, cqe_fp);
3245                 m = NULL; /* packet not ready yet */
3246                 goto next_rx;
3247             }
3248
3249             KASSERT(CQE_TYPE_STOP(cqe_fp_type),
3250                     ("CQE type is not STOP! (0x%x)\n", cqe_fp_type));
3251
3252             queue = cqe->end_agg_cqe.queue_index;
3253             tpa_info = &fp->rx_tpa_info[queue];
3254
3255             BLOGD(sc, DBG_LRO, "fp[%02d].tpa[%02d] TPA STOP\n",
3256                   fp->index, queue);
3257
3258             frag_size = (le16toh(cqe->end_agg_cqe.pkt_len) -
3259                          tpa_info->len_on_bd);
3260             pages = SGE_PAGE_ALIGN(frag_size) >> SGE_PAGE_SHIFT;
3261
3262             bxe_tpa_stop(sc, fp, tpa_info, queue, pages,
3263                          &cqe->end_agg_cqe, comp_ring_cons);
3264
3265             bxe_update_sge_prod(sc, fp, pages, &cqe->end_agg_cqe.sgl_or_raw_data);
3266
3267             goto next_cqe;
3268         }
3269
3270         /* non TPA */
3271
3272         /* is this an error packet? */
3273         if (__predict_false(cqe_fp_flags &
3274                             ETH_FAST_PATH_RX_CQE_PHY_DECODE_ERR_FLG)) {
3275             BLOGE(sc, "flags 0x%x rx packet %u\n", cqe_fp_flags, sw_cq_cons);
3276             fp->eth_q_stats.rx_soft_errors++;
3277             goto next_rx;
3278         }
3279
3280         len = le16toh(cqe_fp->pkt_len_or_gro_seg_len);
3281         lenonbd = le16toh(cqe_fp->len_on_bd);
3282         pad = cqe_fp->placement_offset;
3283
3284         m = rx_buf->m;
3285
3286         if (__predict_false(m == NULL)) {
3287             BLOGE(sc, "No mbuf in rx chain descriptor %d for fp[%02d]\n",
3288                   bd_cons, fp->index);
3289             goto next_rx;
3290         }
3291
3292         /* XXX double copy if packet length under a threshold */
3293
3294         /*
3295          * If all the buffer descriptors are filled with mbufs then fill in
3296          * the current consumer index with a new BD. Else if a maximum Rx
3297          * buffer limit is imposed then fill in the next producer index.
3298          */
3299         rc = bxe_alloc_rx_bd_mbuf(fp, bd_cons,
3300                                   (sc->max_rx_bufs != RX_BD_USABLE) ?
3301                                       bd_prod : bd_cons);
3302         if (rc != 0) {
3303
3304             /* we simply reuse the received mbuf and don't post it to the stack */
3305             m = NULL;
3306
3307             BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
3308                   fp->index, rc);
3309             fp->eth_q_stats.rx_soft_errors++;
3310
3311             if (sc->max_rx_bufs != RX_BD_USABLE) {
3312                 /* copy this consumer index to the producer index */
3313                 memcpy(&fp->rx_mbuf_chain[bd_prod], rx_buf,
3314                        sizeof(struct bxe_sw_rx_bd));
3315                 memset(rx_buf, 0, sizeof(struct bxe_sw_rx_bd));
3316             }
3317
3318             goto next_rx;
3319         }
3320
3321         /* current mbuf was detached from the bd */
3322         fp->eth_q_stats.mbuf_alloc_rx--;
3323
3324         /* we allocated a replacement mbuf, fixup the current one */
3325         m_adj(m, pad);
3326         m->m_pkthdr.len = m->m_len = len;
3327
3328         if ((len > 60) && (len > lenonbd)) {
3329             fp->eth_q_stats.rx_bxe_service_rxsgl++;
3330             rc = bxe_service_rxsgl(fp, len, lenonbd, m, cqe_fp);
3331             if (rc)
3332                 break;
3333             fp->eth_q_stats.rx_jumbo_sge_pkts++;
3334         } else if (lenonbd < len) {
3335             fp->eth_q_stats.rx_erroneous_jumbo_sge_pkts++;
3336         }
3337
3338         /* assign packet to this interface interface */
3339         m->m_pkthdr.rcvif = ifp;
3340
3341         /* assume no hardware checksum has complated */
3342         m->m_pkthdr.csum_flags = 0;
3343
3344         /* validate checksum if offload enabled */
3345         if (ifp->if_capenable & IFCAP_RXCSUM) {
3346             /* check for a valid IP frame */
3347             if (!(cqe->fast_path_cqe.status_flags &
3348                   ETH_FAST_PATH_RX_CQE_IP_XSUM_NO_VALIDATION_FLG)) {
3349                 m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED;
3350                 if (__predict_false(cqe_fp_flags &
3351                                     ETH_FAST_PATH_RX_CQE_IP_BAD_XSUM_FLG)) {
3352                     fp->eth_q_stats.rx_hw_csum_errors++;
3353                 } else {
3354                     fp->eth_q_stats.rx_ofld_frames_csum_ip++;
3355                     m->m_pkthdr.csum_flags |= CSUM_IP_VALID;
3356                 }
3357             }
3358
3359             /* check for a valid TCP/UDP frame */
3360             if (!(cqe->fast_path_cqe.status_flags &
3361                   ETH_FAST_PATH_RX_CQE_L4_XSUM_NO_VALIDATION_FLG)) {
3362                 if (__predict_false(cqe_fp_flags &
3363                                     ETH_FAST_PATH_RX_CQE_L4_BAD_XSUM_FLG)) {
3364                     fp->eth_q_stats.rx_hw_csum_errors++;
3365                 } else {
3366                     fp->eth_q_stats.rx_ofld_frames_csum_tcp_udp++;
3367                     m->m_pkthdr.csum_data = 0xFFFF;
3368                     m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID |
3369                                                CSUM_PSEUDO_HDR);
3370                 }
3371             }
3372         }
3373
3374         /* if there is a VLAN tag then flag that info */
3375         if (cqe->fast_path_cqe.pars_flags.flags & PARSING_FLAGS_INNER_VLAN_EXIST) {
3376             m->m_pkthdr.ether_vtag = cqe->fast_path_cqe.vlan_tag;
3377             m->m_flags |= M_VLANTAG;
3378         }
3379
3380 #if __FreeBSD_version >= 800000
3381         /* specify what RSS queue was used for this flow */
3382         m->m_pkthdr.flowid = fp->index;
3383         BXE_SET_FLOWID(m);
3384 #endif
3385
3386 next_rx:
3387
3388         bd_cons    = RX_BD_NEXT(bd_cons);
3389         bd_prod    = RX_BD_NEXT(bd_prod);
3390         bd_prod_fw = RX_BD_NEXT(bd_prod_fw);
3391
3392         /* pass the frame to the stack */
3393         if (__predict_true(m != NULL)) {
3394             ifp->if_ipackets++;
3395             rx_pkts++;
3396             (*ifp->if_input)(ifp, m);
3397         }
3398
3399 next_cqe:
3400
3401         sw_cq_prod = RCQ_NEXT(sw_cq_prod);
3402         sw_cq_cons = RCQ_NEXT(sw_cq_cons);
3403
3404         /* limit spinning on the queue */
3405         if (rc != 0)
3406             break;
3407
3408         if (rx_pkts == sc->rx_budget) {
3409             fp->eth_q_stats.rx_budget_reached++;
3410             break;
3411         }
3412     } /* while work to do */
3413
3414     fp->rx_bd_cons = bd_cons;
3415     fp->rx_bd_prod = bd_prod_fw;
3416     fp->rx_cq_cons = sw_cq_cons;
3417     fp->rx_cq_prod = sw_cq_prod;
3418
3419     /* Update producers */
3420     bxe_update_rx_prod(sc, fp, bd_prod_fw, sw_cq_prod, fp->rx_sge_prod);
3421
3422     fp->eth_q_stats.rx_pkts += rx_pkts;
3423     fp->eth_q_stats.rx_calls++;
3424
3425     BXE_FP_RX_UNLOCK(fp);
3426
3427     return (sw_cq_cons != hw_cq_cons);
3428 }
3429
3430 static uint16_t
3431 bxe_free_tx_pkt(struct bxe_softc    *sc,
3432                 struct bxe_fastpath *fp,
3433                 uint16_t            idx)
3434 {
3435     struct bxe_sw_tx_bd *tx_buf = &fp->tx_mbuf_chain[idx];
3436     struct eth_tx_start_bd *tx_start_bd;
3437     uint16_t bd_idx = TX_BD(tx_buf->first_bd);
3438     uint16_t new_cons;
3439     int nbd;
3440
3441     /* unmap the mbuf from non-paged memory */
3442     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
3443
3444     tx_start_bd = &fp->tx_chain[bd_idx].start_bd;
3445     nbd = le16toh(tx_start_bd->nbd) - 1;
3446
3447     new_cons = (tx_buf->first_bd + nbd);
3448
3449     /* free the mbuf */
3450     if (__predict_true(tx_buf->m != NULL)) {
3451         m_freem(tx_buf->m);
3452         fp->eth_q_stats.mbuf_alloc_tx--;
3453     } else {
3454         fp->eth_q_stats.tx_chain_lost_mbuf++;
3455     }
3456
3457     tx_buf->m = NULL;
3458     tx_buf->first_bd = 0;
3459
3460     return (new_cons);
3461 }
3462
3463 /* transmit timeout watchdog */
3464 static int
3465 bxe_watchdog(struct bxe_softc    *sc,
3466              struct bxe_fastpath *fp)
3467 {
3468     BXE_FP_TX_LOCK(fp);
3469
3470     if ((fp->watchdog_timer == 0) || (--fp->watchdog_timer)) {
3471         BXE_FP_TX_UNLOCK(fp);
3472         return (0);
3473     }
3474
3475     BLOGE(sc, "TX watchdog timeout on fp[%02d], resetting!\n", fp->index);
3476     if(sc->trigger_grcdump) {
3477          /* taking grcdump */
3478          bxe_grc_dump(sc);
3479     }
3480
3481     BXE_FP_TX_UNLOCK(fp);
3482
3483     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_REINIT);
3484     taskqueue_enqueue(sc->chip_tq, &sc->chip_tq_task);
3485
3486     return (-1);
3487 }
3488
3489 /* processes transmit completions */
3490 static uint8_t
3491 bxe_txeof(struct bxe_softc    *sc,
3492           struct bxe_fastpath *fp)
3493 {
3494     struct ifnet *ifp = sc->ifnet;
3495     uint16_t bd_cons, hw_cons, sw_cons, pkt_cons;
3496     uint16_t tx_bd_avail;
3497
3498     BXE_FP_TX_LOCK_ASSERT(fp);
3499
3500     bd_cons = fp->tx_bd_cons;
3501     hw_cons = le16toh(*fp->tx_cons_sb);
3502     sw_cons = fp->tx_pkt_cons;
3503
3504     while (sw_cons != hw_cons) {
3505         pkt_cons = TX_BD(sw_cons);
3506
3507         BLOGD(sc, DBG_TX,
3508               "TX: fp[%d]: hw_cons=%u sw_cons=%u pkt_cons=%u\n",
3509               fp->index, hw_cons, sw_cons, pkt_cons);
3510
3511         bd_cons = bxe_free_tx_pkt(sc, fp, pkt_cons);
3512
3513         sw_cons++;
3514     }
3515
3516     fp->tx_pkt_cons = sw_cons;
3517     fp->tx_bd_cons  = bd_cons;
3518
3519     BLOGD(sc, DBG_TX,
3520           "TX done: fp[%d]: hw_cons=%u sw_cons=%u sw_prod=%u\n",
3521           fp->index, hw_cons, fp->tx_pkt_cons, fp->tx_pkt_prod);
3522
3523     mb();
3524
3525     tx_bd_avail = bxe_tx_avail(sc, fp);
3526
3527     if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
3528         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3529     } else {
3530         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3531     }
3532
3533     if (fp->tx_pkt_prod != fp->tx_pkt_cons) {
3534         /* reset the watchdog timer if there are pending transmits */
3535         fp->watchdog_timer = BXE_TX_TIMEOUT;
3536         return (TRUE);
3537     } else {
3538         /* clear watchdog when there are no pending transmits */
3539         fp->watchdog_timer = 0;
3540         return (FALSE);
3541     }
3542 }
3543
3544 static void
3545 bxe_drain_tx_queues(struct bxe_softc *sc)
3546 {
3547     struct bxe_fastpath *fp;
3548     int i, count;
3549
3550     /* wait until all TX fastpath tasks have completed */
3551     for (i = 0; i < sc->num_queues; i++) {
3552         fp = &sc->fp[i];
3553
3554         count = 1000;
3555
3556         while (bxe_has_tx_work(fp)) {
3557
3558             BXE_FP_TX_LOCK(fp);
3559             bxe_txeof(sc, fp);
3560             BXE_FP_TX_UNLOCK(fp);
3561
3562             if (count == 0) {
3563                 BLOGE(sc, "Timeout waiting for fp[%d] "
3564                           "transmits to complete!\n", i);
3565                 bxe_panic(sc, ("tx drain failure\n"));
3566                 return;
3567             }
3568
3569             count--;
3570             DELAY(1000);
3571             rmb();
3572         }
3573     }
3574
3575     return;
3576 }
3577
3578 static int
3579 bxe_del_all_macs(struct bxe_softc          *sc,
3580                  struct ecore_vlan_mac_obj *mac_obj,
3581                  int                       mac_type,
3582                  uint8_t                   wait_for_comp)
3583 {
3584     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
3585     int rc;
3586
3587     /* wait for completion of requested */
3588     if (wait_for_comp) {
3589         bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
3590     }
3591
3592     /* Set the mac type of addresses we want to clear */
3593     bxe_set_bit(mac_type, &vlan_mac_flags);
3594
3595     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags, &ramrod_flags);
3596     if (rc < 0) {
3597         BLOGE(sc, "Failed to delete MACs (%d) mac_type %d wait_for_comp 0x%x\n",
3598             rc, mac_type, wait_for_comp);
3599     }
3600
3601     return (rc);
3602 }
3603
3604 static int
3605 bxe_fill_accept_flags(struct bxe_softc *sc,
3606                       uint32_t         rx_mode,
3607                       unsigned long    *rx_accept_flags,
3608                       unsigned long    *tx_accept_flags)
3609 {
3610     /* Clear the flags first */
3611     *rx_accept_flags = 0;
3612     *tx_accept_flags = 0;
3613
3614     switch (rx_mode) {
3615     case BXE_RX_MODE_NONE:
3616         /*
3617          * 'drop all' supersedes any accept flags that may have been
3618          * passed to the function.
3619          */
3620         break;
3621
3622     case BXE_RX_MODE_NORMAL:
3623         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3624         bxe_set_bit(ECORE_ACCEPT_MULTICAST, rx_accept_flags);
3625         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3626
3627         /* internal switching mode */
3628         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3629         bxe_set_bit(ECORE_ACCEPT_MULTICAST, tx_accept_flags);
3630         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3631
3632         break;
3633
3634     case BXE_RX_MODE_ALLMULTI:
3635         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3636         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3637         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3638
3639         /* internal switching mode */
3640         bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3641         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3642         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3643
3644         break;
3645
3646     case BXE_RX_MODE_PROMISC:
3647         /*
3648          * According to deffinition of SI mode, iface in promisc mode
3649          * should receive matched and unmatched (in resolution of port)
3650          * unicast packets.
3651          */
3652         bxe_set_bit(ECORE_ACCEPT_UNMATCHED, rx_accept_flags);
3653         bxe_set_bit(ECORE_ACCEPT_UNICAST, rx_accept_flags);
3654         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, rx_accept_flags);
3655         bxe_set_bit(ECORE_ACCEPT_BROADCAST, rx_accept_flags);
3656
3657         /* internal switching mode */
3658         bxe_set_bit(ECORE_ACCEPT_ALL_MULTICAST, tx_accept_flags);
3659         bxe_set_bit(ECORE_ACCEPT_BROADCAST, tx_accept_flags);
3660
3661         if (IS_MF_SI(sc)) {
3662             bxe_set_bit(ECORE_ACCEPT_ALL_UNICAST, tx_accept_flags);
3663         } else {
3664             bxe_set_bit(ECORE_ACCEPT_UNICAST, tx_accept_flags);
3665         }
3666
3667         break;
3668
3669     default:
3670         BLOGE(sc, "Unknown rx_mode (0x%x)\n", rx_mode);
3671         return (-1);
3672     }
3673
3674     /* Set ACCEPT_ANY_VLAN as we do not enable filtering by VLAN */
3675     if (rx_mode != BXE_RX_MODE_NONE) {
3676         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, rx_accept_flags);
3677         bxe_set_bit(ECORE_ACCEPT_ANY_VLAN, tx_accept_flags);
3678     }
3679
3680     return (0);
3681 }
3682
3683 static int
3684 bxe_set_q_rx_mode(struct bxe_softc *sc,
3685                   uint8_t          cl_id,
3686                   unsigned long    rx_mode_flags,
3687                   unsigned long    rx_accept_flags,
3688                   unsigned long    tx_accept_flags,
3689                   unsigned long    ramrod_flags)
3690 {
3691     struct ecore_rx_mode_ramrod_params ramrod_param;
3692     int rc;
3693
3694     memset(&ramrod_param, 0, sizeof(ramrod_param));
3695
3696     /* Prepare ramrod parameters */
3697     ramrod_param.cid = 0;
3698     ramrod_param.cl_id = cl_id;
3699     ramrod_param.rx_mode_obj = &sc->rx_mode_obj;
3700     ramrod_param.func_id = SC_FUNC(sc);
3701
3702     ramrod_param.pstate = &sc->sp_state;
3703     ramrod_param.state = ECORE_FILTER_RX_MODE_PENDING;
3704
3705     ramrod_param.rdata = BXE_SP(sc, rx_mode_rdata);
3706     ramrod_param.rdata_mapping = BXE_SP_MAPPING(sc, rx_mode_rdata);
3707
3708     bxe_set_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
3709
3710     ramrod_param.ramrod_flags = ramrod_flags;
3711     ramrod_param.rx_mode_flags = rx_mode_flags;
3712
3713     ramrod_param.rx_accept_flags = rx_accept_flags;
3714     ramrod_param.tx_accept_flags = tx_accept_flags;
3715
3716     rc = ecore_config_rx_mode(sc, &ramrod_param);
3717     if (rc < 0) {
3718         BLOGE(sc, "Set rx_mode %d cli_id 0x%x rx_mode_flags 0x%x "
3719             "rx_accept_flags 0x%x tx_accept_flags 0x%x "
3720             "ramrod_flags 0x%x rc %d failed\n", sc->rx_mode, cl_id,
3721             (uint32_t)rx_mode_flags, (uint32_t)rx_accept_flags,
3722             (uint32_t)tx_accept_flags, (uint32_t)ramrod_flags, rc);
3723         return (rc);
3724     }
3725
3726     return (0);
3727 }
3728
3729 static int
3730 bxe_set_storm_rx_mode(struct bxe_softc *sc)
3731 {
3732     unsigned long rx_mode_flags = 0, ramrod_flags = 0;
3733     unsigned long rx_accept_flags = 0, tx_accept_flags = 0;
3734     int rc;
3735
3736     rc = bxe_fill_accept_flags(sc, sc->rx_mode, &rx_accept_flags,
3737                                &tx_accept_flags);
3738     if (rc) {
3739         return (rc);
3740     }
3741
3742     bxe_set_bit(RAMROD_RX, &ramrod_flags);
3743     bxe_set_bit(RAMROD_TX, &ramrod_flags);
3744
3745     /* XXX ensure all fastpath have same cl_id and/or move it to bxe_softc */
3746     return (bxe_set_q_rx_mode(sc, sc->fp[0].cl_id, rx_mode_flags,
3747                               rx_accept_flags, tx_accept_flags,
3748                               ramrod_flags));
3749 }
3750
3751 /* returns the "mcp load_code" according to global load_count array */
3752 static int
3753 bxe_nic_load_no_mcp(struct bxe_softc *sc)
3754 {
3755     int path = SC_PATH(sc);
3756     int port = SC_PORT(sc);
3757
3758     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3759           path, load_count[path][0], load_count[path][1],
3760           load_count[path][2]);
3761     load_count[path][0]++;
3762     load_count[path][1 + port]++;
3763     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3764           path, load_count[path][0], load_count[path][1],
3765           load_count[path][2]);
3766     if (load_count[path][0] == 1) {
3767         return (FW_MSG_CODE_DRV_LOAD_COMMON);
3768     } else if (load_count[path][1 + port] == 1) {
3769         return (FW_MSG_CODE_DRV_LOAD_PORT);
3770     } else {
3771         return (FW_MSG_CODE_DRV_LOAD_FUNCTION);
3772     }
3773 }
3774
3775 /* returns the "mcp load_code" according to global load_count array */
3776 static int
3777 bxe_nic_unload_no_mcp(struct bxe_softc *sc)
3778 {
3779     int port = SC_PORT(sc);
3780     int path = SC_PATH(sc);
3781
3782     BLOGI(sc, "NO MCP - load counts[%d]      %d, %d, %d\n",
3783           path, load_count[path][0], load_count[path][1],
3784           load_count[path][2]);
3785     load_count[path][0]--;
3786     load_count[path][1 + port]--;
3787     BLOGI(sc, "NO MCP - new load counts[%d]  %d, %d, %d\n",
3788           path, load_count[path][0], load_count[path][1],
3789           load_count[path][2]);
3790     if (load_count[path][0] == 0) {
3791         return (FW_MSG_CODE_DRV_UNLOAD_COMMON);
3792     } else if (load_count[path][1 + port] == 0) {
3793         return (FW_MSG_CODE_DRV_UNLOAD_PORT);
3794     } else {
3795         return (FW_MSG_CODE_DRV_UNLOAD_FUNCTION);
3796     }
3797 }
3798
3799 /* request unload mode from the MCP: COMMON, PORT or FUNCTION */
3800 static uint32_t
3801 bxe_send_unload_req(struct bxe_softc *sc,
3802                     int              unload_mode)
3803 {
3804     uint32_t reset_code = 0;
3805
3806     /* Select the UNLOAD request mode */
3807     if (unload_mode == UNLOAD_NORMAL) {
3808         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3809     } else {
3810         reset_code = DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS;
3811     }
3812
3813     /* Send the request to the MCP */
3814     if (!BXE_NOMCP(sc)) {
3815         reset_code = bxe_fw_command(sc, reset_code, 0);
3816     } else {
3817         reset_code = bxe_nic_unload_no_mcp(sc);
3818     }
3819
3820     return (reset_code);
3821 }
3822
3823 /* send UNLOAD_DONE command to the MCP */
3824 static void
3825 bxe_send_unload_done(struct bxe_softc *sc,
3826                      uint8_t          keep_link)
3827 {
3828     uint32_t reset_param =
3829         keep_link ? DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET : 0;
3830
3831     /* Report UNLOAD_DONE to MCP */
3832     if (!BXE_NOMCP(sc)) {
3833         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, reset_param);
3834     }
3835 }
3836
3837 static int
3838 bxe_func_wait_started(struct bxe_softc *sc)
3839 {
3840     int tout = 50;
3841
3842     if (!sc->port.pmf) {
3843         return (0);
3844     }
3845
3846     /*
3847      * (assumption: No Attention from MCP at this stage)
3848      * PMF probably in the middle of TX disable/enable transaction
3849      * 1. Sync IRS for default SB
3850      * 2. Sync SP queue - this guarantees us that attention handling started
3851      * 3. Wait, that TX disable/enable transaction completes
3852      *
3853      * 1+2 guarantee that if DCBX attention was scheduled it already changed
3854      * pending bit of transaction from STARTED-->TX_STOPPED, if we already
3855      * received completion for the transaction the state is TX_STOPPED.
3856      * State will return to STARTED after completion of TX_STOPPED-->STARTED
3857      * transaction.
3858      */
3859
3860     /* XXX make sure default SB ISR is done */
3861     /* need a way to synchronize an irq (intr_mtx?) */
3862
3863     /* XXX flush any work queues */
3864
3865     while (ecore_func_get_state(sc, &sc->func_obj) !=
3866            ECORE_F_STATE_STARTED && tout--) {
3867         DELAY(20000);
3868     }
3869
3870     if (ecore_func_get_state(sc, &sc->func_obj) != ECORE_F_STATE_STARTED) {
3871         /*
3872          * Failed to complete the transaction in a "good way"
3873          * Force both transactions with CLR bit.
3874          */
3875         struct ecore_func_state_params func_params = { NULL };
3876
3877         BLOGE(sc, "Unexpected function state! "
3878                   "Forcing STARTED-->TX_STOPPED-->STARTED\n");
3879
3880         func_params.f_obj = &sc->func_obj;
3881         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3882
3883         /* STARTED-->TX_STOPPED */
3884         func_params.cmd = ECORE_F_CMD_TX_STOP;
3885         ecore_func_state_change(sc, &func_params);
3886
3887         /* TX_STOPPED-->STARTED */
3888         func_params.cmd = ECORE_F_CMD_TX_START;
3889         return (ecore_func_state_change(sc, &func_params));
3890     }
3891
3892     return (0);
3893 }
3894
3895 static int
3896 bxe_stop_queue(struct bxe_softc *sc,
3897                int              index)
3898 {
3899     struct bxe_fastpath *fp = &sc->fp[index];
3900     struct ecore_queue_state_params q_params = { NULL };
3901     int rc;
3902
3903     BLOGD(sc, DBG_LOAD, "stopping queue %d cid %d\n", index, fp->index);
3904
3905     q_params.q_obj = &sc->sp_objs[fp->index].q_obj;
3906     /* We want to wait for completion in this context */
3907     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
3908
3909     /* Stop the primary connection: */
3910
3911     /* ...halt the connection */
3912     q_params.cmd = ECORE_Q_CMD_HALT;
3913     rc = ecore_queue_state_change(sc, &q_params);
3914     if (rc) {
3915         return (rc);
3916     }
3917
3918     /* ...terminate the connection */
3919     q_params.cmd = ECORE_Q_CMD_TERMINATE;
3920     memset(&q_params.params.terminate, 0, sizeof(q_params.params.terminate));
3921     q_params.params.terminate.cid_index = FIRST_TX_COS_INDEX;
3922     rc = ecore_queue_state_change(sc, &q_params);
3923     if (rc) {
3924         return (rc);
3925     }
3926
3927     /* ...delete cfc entry */
3928     q_params.cmd = ECORE_Q_CMD_CFC_DEL;
3929     memset(&q_params.params.cfc_del, 0, sizeof(q_params.params.cfc_del));
3930     q_params.params.cfc_del.cid_index = FIRST_TX_COS_INDEX;
3931     return (ecore_queue_state_change(sc, &q_params));
3932 }
3933
3934 /* wait for the outstanding SP commands */
3935 static inline uint8_t
3936 bxe_wait_sp_comp(struct bxe_softc *sc,
3937                  unsigned long    mask)
3938 {
3939     unsigned long tmp;
3940     int tout = 5000; /* wait for 5 secs tops */
3941
3942     while (tout--) {
3943         mb();
3944         if (!(atomic_load_acq_long(&sc->sp_state) & mask)) {
3945             return (TRUE);
3946         }
3947
3948         DELAY(1000);
3949     }
3950
3951     mb();
3952
3953     tmp = atomic_load_acq_long(&sc->sp_state);
3954     if (tmp & mask) {
3955         BLOGE(sc, "Filtering completion timed out: "
3956                   "sp_state 0x%lx, mask 0x%lx\n",
3957               tmp, mask);
3958         return (FALSE);
3959     }
3960
3961     return (FALSE);
3962 }
3963
3964 static int
3965 bxe_func_stop(struct bxe_softc *sc)
3966 {
3967     struct ecore_func_state_params func_params = { NULL };
3968     int rc;
3969
3970     /* prepare parameters for function state transitions */
3971     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
3972     func_params.f_obj = &sc->func_obj;
3973     func_params.cmd = ECORE_F_CMD_STOP;
3974
3975     /*
3976      * Try to stop the function the 'good way'. If it fails (in case
3977      * of a parity error during bxe_chip_cleanup()) and we are
3978      * not in a debug mode, perform a state transaction in order to
3979      * enable further HW_RESET transaction.
3980      */
3981     rc = ecore_func_state_change(sc, &func_params);
3982     if (rc) {
3983         BLOGE(sc, "FUNC_STOP ramrod failed. "
3984                   "Running a dry transaction (%d)\n", rc);
3985         bxe_set_bit(RAMROD_DRV_CLR_ONLY, &func_params.ramrod_flags);
3986         return (ecore_func_state_change(sc, &func_params));
3987     }
3988
3989     return (0);
3990 }
3991
3992 static int
3993 bxe_reset_hw(struct bxe_softc *sc,
3994              uint32_t         load_code)
3995 {
3996     struct ecore_func_state_params func_params = { NULL };
3997
3998     /* Prepare parameters for function state transitions */
3999     bxe_set_bit(RAMROD_COMP_WAIT, &func_params.ramrod_flags);
4000
4001     func_params.f_obj = &sc->func_obj;
4002     func_params.cmd = ECORE_F_CMD_HW_RESET;
4003
4004     func_params.params.hw_init.load_phase = load_code;
4005
4006     return (ecore_func_state_change(sc, &func_params));
4007 }
4008
4009 static void
4010 bxe_int_disable_sync(struct bxe_softc *sc,
4011                      int              disable_hw)
4012 {
4013     if (disable_hw) {
4014         /* prevent the HW from sending interrupts */
4015         bxe_int_disable(sc);
4016     }
4017
4018     /* XXX need a way to synchronize ALL irqs (intr_mtx?) */
4019     /* make sure all ISRs are done */
4020
4021     /* XXX make sure sp_task is not running */
4022     /* cancel and flush work queues */
4023 }
4024
4025 static void
4026 bxe_chip_cleanup(struct bxe_softc *sc,
4027                  uint32_t         unload_mode,
4028                  uint8_t          keep_link)
4029 {
4030     int port = SC_PORT(sc);
4031     struct ecore_mcast_ramrod_params rparam = { NULL };
4032     uint32_t reset_code;
4033     int i, rc = 0;
4034
4035     bxe_drain_tx_queues(sc);
4036
4037     /* give HW time to discard old tx messages */
4038     DELAY(1000);
4039
4040     /* Clean all ETH MACs */
4041     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_ETH_MAC, FALSE);
4042     if (rc < 0) {
4043         BLOGE(sc, "Failed to delete all ETH MACs (%d)\n", rc);
4044     }
4045
4046     /* Clean up UC list  */
4047     rc = bxe_del_all_macs(sc, &sc->sp_objs[0].mac_obj, ECORE_UC_LIST_MAC, TRUE);
4048     if (rc < 0) {
4049         BLOGE(sc, "Failed to delete UC MACs list (%d)\n", rc);
4050     }
4051
4052     /* Disable LLH */
4053     if (!CHIP_IS_E1(sc)) {
4054         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
4055     }
4056
4057     /* Set "drop all" to stop Rx */
4058
4059     /*
4060      * We need to take the BXE_MCAST_LOCK() here in order to prevent
4061      * a race between the completion code and this code.
4062      */
4063     BXE_MCAST_LOCK(sc);
4064
4065     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
4066         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
4067     } else {
4068         bxe_set_storm_rx_mode(sc);
4069     }
4070
4071     /* Clean up multicast configuration */
4072     rparam.mcast_obj = &sc->mcast_obj;
4073     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4074     if (rc < 0) {
4075         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4076     }
4077
4078     BXE_MCAST_UNLOCK(sc);
4079
4080     // XXX bxe_iov_chip_cleanup(sc);
4081
4082     /*
4083      * Send the UNLOAD_REQUEST to the MCP. This will return if
4084      * this function should perform FUNCTION, PORT, or COMMON HW
4085      * reset.
4086      */
4087     reset_code = bxe_send_unload_req(sc, unload_mode);
4088
4089     /*
4090      * (assumption: No Attention from MCP at this stage)
4091      * PMF probably in the middle of TX disable/enable transaction
4092      */
4093     rc = bxe_func_wait_started(sc);
4094     if (rc) {
4095         BLOGE(sc, "bxe_func_wait_started failed (%d)\n", rc);
4096     }
4097
4098     /*
4099      * Close multi and leading connections
4100      * Completions for ramrods are collected in a synchronous way
4101      */
4102     for (i = 0; i < sc->num_queues; i++) {
4103         if (bxe_stop_queue(sc, i)) {
4104             goto unload_error;
4105         }
4106     }
4107
4108     /*
4109      * If SP settings didn't get completed so far - something
4110      * very wrong has happen.
4111      */
4112     if (!bxe_wait_sp_comp(sc, ~0x0UL)) {
4113         BLOGE(sc, "Common slow path ramrods got stuck!(%d)\n", rc);
4114     }
4115
4116 unload_error:
4117
4118     rc = bxe_func_stop(sc);
4119     if (rc) {
4120         BLOGE(sc, "Function stop failed!(%d)\n", rc);
4121     }
4122
4123     /* disable HW interrupts */
4124     bxe_int_disable_sync(sc, TRUE);
4125
4126     /* detach interrupts */
4127     bxe_interrupt_detach(sc);
4128
4129     /* Reset the chip */
4130     rc = bxe_reset_hw(sc, reset_code);
4131     if (rc) {
4132         BLOGE(sc, "Hardware reset failed(%d)\n", rc);
4133     }
4134
4135     /* Report UNLOAD_DONE to MCP */
4136     bxe_send_unload_done(sc, keep_link);
4137 }
4138
4139 static void
4140 bxe_disable_close_the_gate(struct bxe_softc *sc)
4141 {
4142     uint32_t val;
4143     int port = SC_PORT(sc);
4144
4145     BLOGD(sc, DBG_LOAD,
4146           "Disabling 'close the gates'\n");
4147
4148     if (CHIP_IS_E1(sc)) {
4149         uint32_t addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
4150                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
4151         val = REG_RD(sc, addr);
4152         val &= ~(0x300);
4153         REG_WR(sc, addr, val);
4154     } else {
4155         val = REG_RD(sc, MISC_REG_AEU_GENERAL_MASK);
4156         val &= ~(MISC_AEU_GENERAL_MASK_REG_AEU_PXP_CLOSE_MASK |
4157                  MISC_AEU_GENERAL_MASK_REG_AEU_NIG_CLOSE_MASK);
4158         REG_WR(sc, MISC_REG_AEU_GENERAL_MASK, val);
4159     }
4160 }
4161
4162 /*
4163  * Cleans the object that have internal lists without sending
4164  * ramrods. Should be run when interrutps are disabled.
4165  */
4166 static void
4167 bxe_squeeze_objects(struct bxe_softc *sc)
4168 {
4169     unsigned long ramrod_flags = 0, vlan_mac_flags = 0;
4170     struct ecore_mcast_ramrod_params rparam = { NULL };
4171     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
4172     int rc;
4173
4174     /* Cleanup MACs' object first... */
4175
4176     /* Wait for completion of requested */
4177     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
4178     /* Perform a dry cleanup */
4179     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &ramrod_flags);
4180
4181     /* Clean ETH primary MAC */
4182     bxe_set_bit(ECORE_ETH_MAC, &vlan_mac_flags);
4183     rc = mac_obj->delete_all(sc, &sc->sp_objs->mac_obj, &vlan_mac_flags,
4184                              &ramrod_flags);
4185     if (rc != 0) {
4186         BLOGE(sc, "Failed to clean ETH MACs (%d)\n", rc);
4187     }
4188
4189     /* Cleanup UC list */
4190     vlan_mac_flags = 0;
4191     bxe_set_bit(ECORE_UC_LIST_MAC, &vlan_mac_flags);
4192     rc = mac_obj->delete_all(sc, mac_obj, &vlan_mac_flags,
4193                              &ramrod_flags);
4194     if (rc != 0) {
4195         BLOGE(sc, "Failed to clean UC list MACs (%d)\n", rc);
4196     }
4197
4198     /* Now clean mcast object... */
4199
4200     rparam.mcast_obj = &sc->mcast_obj;
4201     bxe_set_bit(RAMROD_DRV_CLR_ONLY, &rparam.ramrod_flags);
4202
4203     /* Add a DEL command... */
4204     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
4205     if (rc < 0) {
4206         BLOGE(sc, "Failed to send DEL MCAST command (%d)\n", rc);
4207     }
4208
4209     /* now wait until all pending commands are cleared */
4210
4211     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4212     while (rc != 0) {
4213         if (rc < 0) {
4214             BLOGE(sc, "Failed to clean MCAST object (%d)\n", rc);
4215             return;
4216         }
4217
4218         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
4219     }
4220 }
4221
4222 /* stop the controller */
4223 static __noinline int
4224 bxe_nic_unload(struct bxe_softc *sc,
4225                uint32_t         unload_mode,
4226                uint8_t          keep_link)
4227 {
4228     uint8_t global = FALSE;
4229     uint32_t val;
4230     int i;
4231
4232     BXE_CORE_LOCK_ASSERT(sc);
4233
4234     sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
4235
4236     for (i = 0; i < sc->num_queues; i++) {
4237         struct bxe_fastpath *fp;
4238
4239         fp = &sc->fp[i];
4240         BXE_FP_TX_LOCK(fp);
4241         BXE_FP_TX_UNLOCK(fp);
4242     }
4243
4244     BLOGD(sc, DBG_LOAD, "Starting NIC unload...\n");
4245
4246     /* mark driver as unloaded in shmem2 */
4247     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
4248         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
4249         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
4250                   val & ~DRV_FLAGS_CAPABILITIES_LOADED_L2);
4251     }
4252
4253     if (IS_PF(sc) && sc->recovery_state != BXE_RECOVERY_DONE &&
4254         (sc->state == BXE_STATE_CLOSED || sc->state == BXE_STATE_ERROR)) {
4255         /*
4256          * We can get here if the driver has been unloaded
4257          * during parity error recovery and is either waiting for a
4258          * leader to complete or for other functions to unload and
4259          * then ifconfig down has been issued. In this case we want to
4260          * unload and let other functions to complete a recovery
4261          * process.
4262          */
4263         sc->recovery_state = BXE_RECOVERY_DONE;
4264         sc->is_leader = 0;
4265         bxe_release_leader_lock(sc);
4266         mb();
4267
4268         BLOGD(sc, DBG_LOAD, "Releasing a leadership...\n");
4269         BLOGE(sc, "Can't unload in closed or error state recover_state 0x%x"
4270             " state = 0x%x\n", sc->recovery_state, sc->state);
4271         return (-1);
4272     }
4273
4274     /*
4275      * Nothing to do during unload if previous bxe_nic_load()
4276      * did not completed succesfully - all resourses are released.
4277      */
4278     if ((sc->state == BXE_STATE_CLOSED) ||
4279         (sc->state == BXE_STATE_ERROR)) {
4280         return (0);
4281     }
4282
4283     sc->state = BXE_STATE_CLOSING_WAITING_HALT;
4284     mb();
4285
4286     /* stop tx */
4287     bxe_tx_disable(sc);
4288
4289     sc->rx_mode = BXE_RX_MODE_NONE;
4290     /* XXX set rx mode ??? */
4291
4292     if (IS_PF(sc) && !sc->grcdump_done) {
4293         /* set ALWAYS_ALIVE bit in shmem */
4294         sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
4295
4296         bxe_drv_pulse(sc);
4297
4298         bxe_stats_handle(sc, STATS_EVENT_STOP);
4299         bxe_save_statistics(sc);
4300     }
4301
4302     /* wait till consumers catch up with producers in all queues */
4303     bxe_drain_tx_queues(sc);
4304
4305     /* if VF indicate to PF this function is going down (PF will delete sp
4306      * elements and clear initializations
4307      */
4308     if (IS_VF(sc)) {
4309         ; /* bxe_vfpf_close_vf(sc); */
4310     } else if (unload_mode != UNLOAD_RECOVERY) {
4311         /* if this is a normal/close unload need to clean up chip */
4312         if (!sc->grcdump_done)
4313             bxe_chip_cleanup(sc, unload_mode, keep_link);
4314     } else {
4315         /* Send the UNLOAD_REQUEST to the MCP */
4316         bxe_send_unload_req(sc, unload_mode);
4317
4318         /*
4319          * Prevent transactions to host from the functions on the
4320          * engine that doesn't reset global blocks in case of global
4321          * attention once gloabl blocks are reset and gates are opened
4322          * (the engine which leader will perform the recovery
4323          * last).
4324          */
4325         if (!CHIP_IS_E1x(sc)) {
4326             bxe_pf_disable(sc);
4327         }
4328
4329         /* disable HW interrupts */
4330         bxe_int_disable_sync(sc, TRUE);
4331
4332         /* detach interrupts */
4333         bxe_interrupt_detach(sc);
4334
4335         /* Report UNLOAD_DONE to MCP */
4336         bxe_send_unload_done(sc, FALSE);
4337     }
4338
4339     /*
4340      * At this stage no more interrupts will arrive so we may safely clean
4341      * the queue'able objects here in case they failed to get cleaned so far.
4342      */
4343     if (IS_PF(sc)) {
4344         bxe_squeeze_objects(sc);
4345     }
4346
4347     /* There should be no more pending SP commands at this stage */
4348     sc->sp_state = 0;
4349
4350     sc->port.pmf = 0;
4351
4352     bxe_free_fp_buffers(sc);
4353
4354     if (IS_PF(sc)) {
4355         bxe_free_mem(sc);
4356     }
4357
4358     bxe_free_fw_stats_mem(sc);
4359
4360     sc->state = BXE_STATE_CLOSED;
4361
4362     /*
4363      * Check if there are pending parity attentions. If there are - set
4364      * RECOVERY_IN_PROGRESS.
4365      */
4366     if (IS_PF(sc) && bxe_chk_parity_attn(sc, &global, FALSE)) {
4367         bxe_set_reset_in_progress(sc);
4368
4369         /* Set RESET_IS_GLOBAL if needed */
4370         if (global) {
4371             bxe_set_reset_global(sc);
4372         }
4373     }
4374
4375     /*
4376      * The last driver must disable a "close the gate" if there is no
4377      * parity attention or "process kill" pending.
4378      */
4379     if (IS_PF(sc) && !bxe_clear_pf_load(sc) &&
4380         bxe_reset_is_done(sc, SC_PATH(sc))) {
4381         bxe_disable_close_the_gate(sc);
4382     }
4383
4384     BLOGD(sc, DBG_LOAD, "Ended NIC unload\n");
4385
4386     return (0);
4387 }
4388
4389 /*
4390  * Called by the OS to set various media options (i.e. link, speed, etc.) when
4391  * the user runs "ifconfig bxe media ..." or "ifconfig bxe mediaopt ...".
4392  */
4393 static int
4394 bxe_ifmedia_update(struct ifnet *ifp)
4395 {
4396     struct bxe_softc *sc = (struct bxe_softc *)ifp->if_softc;
4397     struct ifmedia *ifm;
4398
4399     ifm = &sc->ifmedia;
4400
4401     /* We only support Ethernet media type. */
4402     if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
4403         return (EINVAL);
4404     }
4405
4406     switch (IFM_SUBTYPE(ifm->ifm_media)) {
4407     case IFM_AUTO:
4408          break;
4409     case IFM_10G_CX4:
4410     case IFM_10G_SR:
4411     case IFM_10G_T:
4412     case IFM_10G_TWINAX:
4413     default:
4414         /* We don't support changing the media type. */
4415         BLOGD(sc, DBG_LOAD, "Invalid media type (%d)\n",
4416               IFM_SUBTYPE(ifm->ifm_media));
4417         return (EINVAL);
4418     }
4419
4420     return (0);
4421 }
4422
4423 /*
4424  * Called by the OS to get the current media status (i.e. link, speed, etc.).
4425  */
4426 static void
4427 bxe_ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
4428 {
4429     struct bxe_softc *sc = ifp->if_softc;
4430
4431     /* Report link down if the driver isn't running. */
4432     if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
4433         ifmr->ifm_active |= IFM_NONE;
4434         return;
4435     }
4436
4437     /* Setup the default interface info. */
4438     ifmr->ifm_status = IFM_AVALID;
4439     ifmr->ifm_active = IFM_ETHER;
4440
4441     if (sc->link_vars.link_up) {
4442         ifmr->ifm_status |= IFM_ACTIVE;
4443     } else {
4444         ifmr->ifm_active |= IFM_NONE;
4445         return;
4446     }
4447
4448     ifmr->ifm_active |= sc->media;
4449
4450     if (sc->link_vars.duplex == DUPLEX_FULL) {
4451         ifmr->ifm_active |= IFM_FDX;
4452     } else {
4453         ifmr->ifm_active |= IFM_HDX;
4454     }
4455 }
4456
4457 static void
4458 bxe_handle_chip_tq(void *context,
4459                    int  pending)
4460 {
4461     struct bxe_softc *sc = (struct bxe_softc *)context;
4462     long work = atomic_load_acq_long(&sc->chip_tq_flags);
4463
4464     switch (work)
4465     {
4466     case CHIP_TQ_REINIT:
4467         if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
4468             /* restart the interface */
4469             BLOGD(sc, DBG_LOAD, "Restarting the interface...\n");
4470             bxe_periodic_stop(sc);
4471             BXE_CORE_LOCK(sc);
4472             bxe_stop_locked(sc);
4473             bxe_init_locked(sc);
4474             BXE_CORE_UNLOCK(sc);
4475         }
4476         break;
4477
4478     default:
4479         break;
4480     }
4481 }
4482
4483 /*
4484  * Handles any IOCTL calls from the operating system.
4485  *
4486  * Returns:
4487  *   0 = Success, >0 Failure
4488  */
4489 static int
4490 bxe_ioctl(struct ifnet *ifp,
4491           u_long       command,
4492           caddr_t      data)
4493 {
4494     struct bxe_softc *sc = ifp->if_softc;
4495     struct ifreq *ifr = (struct ifreq *)data;
4496     int mask = 0;
4497     int reinit = 0;
4498     int error = 0;
4499
4500     int mtu_min = (ETH_MIN_PACKET_SIZE - ETH_HLEN);
4501     int mtu_max = (MJUM9BYTES - ETH_OVERHEAD - IP_HEADER_ALIGNMENT_PADDING);
4502
4503     switch (command)
4504     {
4505     case SIOCSIFMTU:
4506         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFMTU ioctl (mtu=%d)\n",
4507               ifr->ifr_mtu);
4508
4509         if (sc->mtu == ifr->ifr_mtu) {
4510             /* nothing to change */
4511             break;
4512         }
4513
4514         if ((ifr->ifr_mtu < mtu_min) || (ifr->ifr_mtu > mtu_max)) {
4515             BLOGE(sc, "Unsupported MTU size %d (range is %d-%d)\n",
4516                   ifr->ifr_mtu, mtu_min, mtu_max);
4517             error = EINVAL;
4518             break;
4519         }
4520
4521         atomic_store_rel_int((volatile unsigned int *)&sc->mtu,
4522                              (unsigned long)ifr->ifr_mtu);
4523         atomic_store_rel_long((volatile unsigned long *)&ifp->if_mtu,
4524                               (unsigned long)ifr->ifr_mtu);
4525
4526         reinit = 1;
4527         break;
4528
4529     case SIOCSIFFLAGS:
4530         /* toggle the interface state up or down */
4531         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFFLAGS ioctl\n");
4532
4533         BXE_CORE_LOCK(sc);
4534         /* check if the interface is up */
4535         if (ifp->if_flags & IFF_UP) {
4536             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4537                 /* set the receive mode flags */
4538                 bxe_set_rx_mode(sc);
4539             } else if(sc->state != BXE_STATE_DISABLED) {
4540                 bxe_init_locked(sc);
4541             }
4542         } else {
4543             if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4544                 bxe_periodic_stop(sc);
4545                 bxe_stop_locked(sc);
4546             }
4547         }
4548         BXE_CORE_UNLOCK(sc);
4549
4550         break;
4551
4552     case SIOCADDMULTI:
4553     case SIOCDELMULTI:
4554         /* add/delete multicast addresses */
4555         BLOGD(sc, DBG_IOCTL, "Received SIOCADDMULTI/SIOCDELMULTI ioctl\n");
4556
4557         /* check if the interface is up */
4558         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
4559             /* set the receive mode flags */
4560             BXE_CORE_LOCK(sc);
4561             bxe_set_rx_mode(sc);
4562             BXE_CORE_UNLOCK(sc); 
4563         }
4564
4565         break;
4566
4567     case SIOCSIFCAP:
4568         /* find out which capabilities have changed */
4569         mask = (ifr->ifr_reqcap ^ ifp->if_capenable);
4570
4571         BLOGD(sc, DBG_IOCTL, "Received SIOCSIFCAP ioctl (mask=0x%08x)\n",
4572               mask);
4573
4574         /* toggle the LRO capabilites enable flag */
4575         if (mask & IFCAP_LRO) {
4576             ifp->if_capenable ^= IFCAP_LRO;
4577             BLOGD(sc, DBG_IOCTL, "Turning LRO %s\n",
4578                   (ifp->if_capenable & IFCAP_LRO) ? "ON" : "OFF");
4579             reinit = 1;
4580         }
4581
4582         /* toggle the TXCSUM checksum capabilites enable flag */
4583         if (mask & IFCAP_TXCSUM) {
4584             ifp->if_capenable ^= IFCAP_TXCSUM;
4585             BLOGD(sc, DBG_IOCTL, "Turning TXCSUM %s\n",
4586                   (ifp->if_capenable & IFCAP_TXCSUM) ? "ON" : "OFF");
4587             if (ifp->if_capenable & IFCAP_TXCSUM) {
4588                 ifp->if_hwassist = (CSUM_IP       |
4589                                     CSUM_TCP      |
4590                                     CSUM_UDP      |
4591                                     CSUM_TSO      |
4592                                     CSUM_TCP_IPV6 |
4593                                     CSUM_UDP_IPV6);
4594             } else {
4595                 ifp->if_hwassist = 0;
4596             }
4597         }
4598
4599         /* toggle the RXCSUM checksum capabilities enable flag */
4600         if (mask & IFCAP_RXCSUM) {
4601             ifp->if_capenable ^= IFCAP_RXCSUM;
4602             BLOGD(sc, DBG_IOCTL, "Turning RXCSUM %s\n",
4603                   (ifp->if_capenable & IFCAP_RXCSUM) ? "ON" : "OFF");
4604             if (ifp->if_capenable & IFCAP_RXCSUM) {
4605                 ifp->if_hwassist = (CSUM_IP       |
4606                                     CSUM_TCP      |
4607                                     CSUM_UDP      |
4608                                     CSUM_TSO      |
4609                                     CSUM_TCP_IPV6 |
4610                                     CSUM_UDP_IPV6);
4611             } else {
4612                 ifp->if_hwassist = 0;
4613             }
4614         }
4615
4616         /* toggle TSO4 capabilities enabled flag */
4617         if (mask & IFCAP_TSO4) {
4618             ifp->if_capenable ^= IFCAP_TSO4;
4619             BLOGD(sc, DBG_IOCTL, "Turning TSO4 %s\n",
4620                   (ifp->if_capenable & IFCAP_TSO4) ? "ON" : "OFF");
4621         }
4622
4623         /* toggle TSO6 capabilities enabled flag */
4624         if (mask & IFCAP_TSO6) {
4625             ifp->if_capenable ^= IFCAP_TSO6;
4626             BLOGD(sc, DBG_IOCTL, "Turning TSO6 %s\n",
4627                   (ifp->if_capenable & IFCAP_TSO6) ? "ON" : "OFF");
4628         }
4629
4630         /* toggle VLAN_HWTSO capabilities enabled flag */
4631         if (mask & IFCAP_VLAN_HWTSO) {
4632             ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
4633             BLOGD(sc, DBG_IOCTL, "Turning VLAN_HWTSO %s\n",
4634                   (ifp->if_capenable & IFCAP_VLAN_HWTSO) ? "ON" : "OFF");
4635         }
4636
4637         /* toggle VLAN_HWCSUM capabilities enabled flag */
4638         if (mask & IFCAP_VLAN_HWCSUM) {
4639             /* XXX investigate this... */
4640             BLOGE(sc, "Changing VLAN_HWCSUM is not supported!\n");
4641             error = EINVAL;
4642         }
4643
4644         /* toggle VLAN_MTU capabilities enable flag */
4645         if (mask & IFCAP_VLAN_MTU) {
4646             /* XXX investigate this... */
4647             BLOGE(sc, "Changing VLAN_MTU is not supported!\n");
4648             error = EINVAL;
4649         }
4650
4651         /* toggle VLAN_HWTAGGING capabilities enabled flag */
4652         if (mask & IFCAP_VLAN_HWTAGGING) {
4653             /* XXX investigate this... */
4654             BLOGE(sc, "Changing VLAN_HWTAGGING is not supported!\n");
4655             error = EINVAL;
4656         }
4657
4658         /* toggle VLAN_HWFILTER capabilities enabled flag */
4659         if (mask & IFCAP_VLAN_HWFILTER) {
4660             /* XXX investigate this... */
4661             BLOGE(sc, "Changing VLAN_HWFILTER is not supported!\n");
4662             error = EINVAL;
4663         }
4664
4665         /* XXX not yet...
4666          * IFCAP_WOL_MAGIC
4667          */
4668
4669         break;
4670
4671     case SIOCSIFMEDIA:
4672     case SIOCGIFMEDIA:
4673         /* set/get interface media */
4674         BLOGD(sc, DBG_IOCTL,
4675               "Received SIOCSIFMEDIA/SIOCGIFMEDIA ioctl (cmd=%lu)\n",
4676               (command & 0xff));
4677         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
4678         break;
4679
4680     default:
4681         BLOGD(sc, DBG_IOCTL, "Received Unknown Ioctl (cmd=%lu)\n",
4682               (command & 0xff));
4683         error = ether_ioctl(ifp, command, data);
4684         break;
4685     }
4686
4687     if (reinit && (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
4688         BLOGD(sc, DBG_LOAD | DBG_IOCTL,
4689               "Re-initializing hardware from IOCTL change\n");
4690         bxe_periodic_stop(sc);
4691         BXE_CORE_LOCK(sc);
4692         bxe_stop_locked(sc);
4693         bxe_init_locked(sc);
4694         BXE_CORE_UNLOCK(sc);
4695     }
4696
4697     return (error);
4698 }
4699
4700 static __noinline void
4701 bxe_dump_mbuf(struct bxe_softc *sc,
4702               struct mbuf      *m,
4703               uint8_t          contents)
4704 {
4705     char * type;
4706     int i = 0;
4707
4708     if (!(sc->debug & DBG_MBUF)) {
4709         return;
4710     }
4711
4712     if (m == NULL) {
4713         BLOGD(sc, DBG_MBUF, "mbuf: null pointer\n");
4714         return;
4715     }
4716
4717     while (m) {
4718
4719 #if __FreeBSD_version >= 1000000
4720         BLOGD(sc, DBG_MBUF,
4721               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4722               i, m, m->m_len, m->m_flags,
4723               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4724
4725         if (m->m_flags & M_PKTHDR) {
4726              BLOGD(sc, DBG_MBUF,
4727                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4728                    i, m->m_pkthdr.len, m->m_flags,
4729                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4730                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4731                    "\22M_PROMISC\23M_NOFREE",
4732                    (int)m->m_pkthdr.csum_flags,
4733                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4734                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4735                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4736                    "\14CSUM_PSEUDO_HDR");
4737         }
4738 #else
4739         BLOGD(sc, DBG_MBUF,
4740               "%02d: mbuf=%p m_len=%d m_flags=0x%b m_data=%p\n",
4741               i, m, m->m_len, m->m_flags,
4742               "\20\1M_EXT\2M_PKTHDR\3M_EOR\4M_RDONLY", m->m_data);
4743
4744         if (m->m_flags & M_PKTHDR) {
4745              BLOGD(sc, DBG_MBUF,
4746                    "%02d: - m_pkthdr: tot_len=%d flags=0x%b csum_flags=%b\n",
4747                    i, m->m_pkthdr.len, m->m_flags,
4748                    "\20\12M_BCAST\13M_MCAST\14M_FRAG"
4749                    "\15M_FIRSTFRAG\16M_LASTFRAG\21M_VLANTAG"
4750                    "\22M_PROMISC\23M_NOFREE",
4751                    (int)m->m_pkthdr.csum_flags,
4752                    "\20\1CSUM_IP\2CSUM_TCP\3CSUM_UDP\4CSUM_IP_FRAGS"
4753                    "\5CSUM_FRAGMENT\6CSUM_TSO\11CSUM_IP_CHECKED"
4754                    "\12CSUM_IP_VALID\13CSUM_DATA_VALID"
4755                    "\14CSUM_PSEUDO_HDR");
4756         }
4757 #endif /* #if __FreeBSD_version >= 1000000 */
4758
4759         if (m->m_flags & M_EXT) {
4760             switch (m->m_ext.ext_type) {
4761             case EXT_CLUSTER:    type = "EXT_CLUSTER";    break;
4762             case EXT_SFBUF:      type = "EXT_SFBUF";      break;
4763             case EXT_JUMBOP:     type = "EXT_JUMBOP";     break;
4764             case EXT_JUMBO9:     type = "EXT_JUMBO9";     break;
4765             case EXT_JUMBO16:    type = "EXT_JUMBO16";    break;
4766             case EXT_PACKET:     type = "EXT_PACKET";     break;
4767             case EXT_MBUF:       type = "EXT_MBUF";       break;
4768             case EXT_NET_DRV:    type = "EXT_NET_DRV";    break;
4769             case EXT_MOD_TYPE:   type = "EXT_MOD_TYPE";   break;
4770             case EXT_DISPOSABLE: type = "EXT_DISPOSABLE"; break;
4771             case EXT_EXTREF:     type = "EXT_EXTREF";     break;
4772             default:             type = "UNKNOWN";        break;
4773             }
4774
4775             BLOGD(sc, DBG_MBUF,
4776                   "%02d: - m_ext: %p ext_size=%d type=%s\n",
4777                   i, m->m_ext.ext_buf, m->m_ext.ext_size, type);
4778         }
4779
4780         if (contents) {
4781             bxe_dump_mbuf_data(sc, "mbuf data", m, TRUE);
4782         }
4783
4784         m = m->m_next;
4785         i++;
4786     }
4787 }
4788
4789 /*
4790  * Checks to ensure the 13 bd sliding window is >= MSS for TSO.
4791  * Check that (13 total bds - 3 bds) = 10 bd window >= MSS.
4792  * The window: 3 bds are = 1 for headers BD + 2 for parse BD and last BD
4793  * The headers comes in a seperate bd in FreeBSD so 13-3=10.
4794  * Returns: 0 if OK to send, 1 if packet needs further defragmentation
4795  */
4796 static int
4797 bxe_chktso_window(struct bxe_softc  *sc,
4798                   int               nsegs,
4799                   bus_dma_segment_t *segs,
4800                   struct mbuf       *m)
4801 {
4802     uint32_t num_wnds, wnd_size, wnd_sum;
4803     int32_t frag_idx, wnd_idx;
4804     unsigned short lso_mss;
4805     int defrag;
4806
4807     defrag = 0;
4808     wnd_sum = 0;
4809     wnd_size = 10;
4810     num_wnds = nsegs - wnd_size;
4811     lso_mss = htole16(m->m_pkthdr.tso_segsz);
4812
4813     /*
4814      * Total header lengths Eth+IP+TCP in first FreeBSD mbuf so calculate the
4815      * first window sum of data while skipping the first assuming it is the
4816      * header in FreeBSD.
4817      */
4818     for (frag_idx = 1; (frag_idx <= wnd_size); frag_idx++) {
4819         wnd_sum += htole16(segs[frag_idx].ds_len);
4820     }
4821
4822     /* check the first 10 bd window size */
4823     if (wnd_sum < lso_mss) {
4824         return (1);
4825     }
4826
4827     /* run through the windows */
4828     for (wnd_idx = 0; wnd_idx < num_wnds; wnd_idx++, frag_idx++) {
4829         /* subtract the first mbuf->m_len of the last wndw(-header) */
4830         wnd_sum -= htole16(segs[wnd_idx+1].ds_len);
4831         /* add the next mbuf len to the len of our new window */
4832         wnd_sum += htole16(segs[frag_idx].ds_len);
4833         if (wnd_sum < lso_mss) {
4834             return (1);
4835         }
4836     }
4837
4838     return (0);
4839 }
4840
4841 static uint8_t
4842 bxe_set_pbd_csum_e2(struct bxe_fastpath *fp,
4843                     struct mbuf         *m,
4844                     uint32_t            *parsing_data)
4845 {
4846     struct ether_vlan_header *eh = NULL;
4847     struct ip *ip4 = NULL;
4848     struct ip6_hdr *ip6 = NULL;
4849     caddr_t ip = NULL;
4850     struct tcphdr *th = NULL;
4851     int e_hlen, ip_hlen, l4_off;
4852     uint16_t proto;
4853
4854     if (m->m_pkthdr.csum_flags == CSUM_IP) {
4855         /* no L4 checksum offload needed */
4856         return (0);
4857     }
4858
4859     /* get the Ethernet header */
4860     eh = mtod(m, struct ether_vlan_header *);
4861
4862     /* handle VLAN encapsulation if present */
4863     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4864         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4865         proto  = ntohs(eh->evl_proto);
4866     } else {
4867         e_hlen = ETHER_HDR_LEN;
4868         proto  = ntohs(eh->evl_encap_proto);
4869     }
4870
4871     switch (proto) {
4872     case ETHERTYPE_IP:
4873         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4874         ip4 = (m->m_len < sizeof(struct ip)) ?
4875                   (struct ip *)m->m_next->m_data :
4876                   (struct ip *)(m->m_data + e_hlen);
4877         /* ip_hl is number of 32-bit words */
4878         ip_hlen = (ip4->ip_hl << 2);
4879         ip = (caddr_t)ip4;
4880         break;
4881     case ETHERTYPE_IPV6:
4882         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4883         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4884                   (struct ip6_hdr *)m->m_next->m_data :
4885                   (struct ip6_hdr *)(m->m_data + e_hlen);
4886         /* XXX cannot support offload with IPv6 extensions */
4887         ip_hlen = sizeof(struct ip6_hdr);
4888         ip = (caddr_t)ip6;
4889         break;
4890     default:
4891         /* We can't offload in this case... */
4892         /* XXX error stat ??? */
4893         return (0);
4894     }
4895
4896     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4897     l4_off = (e_hlen + ip_hlen);
4898
4899     *parsing_data |=
4900         (((l4_off >> 1) << ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W_SHIFT) &
4901          ETH_TX_PARSE_BD_E2_L4_HDR_START_OFFSET_W);
4902
4903     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4904                                   CSUM_TSO |
4905                                   CSUM_TCP_IPV6)) {
4906         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
4907         th = (struct tcphdr *)(ip + ip_hlen);
4908         /* th_off is number of 32-bit words */
4909         *parsing_data |= ((th->th_off <<
4910                            ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW_SHIFT) &
4911                           ETH_TX_PARSE_BD_E2_TCP_HDR_LENGTH_DW);
4912         return (l4_off + (th->th_off << 2)); /* entire header length */
4913     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
4914                                          CSUM_UDP_IPV6)) {
4915         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
4916         return (l4_off + sizeof(struct udphdr)); /* entire header length */
4917     } else {
4918         /* XXX error stat ??? */
4919         return (0);
4920     }
4921 }
4922
4923 static uint8_t
4924 bxe_set_pbd_csum(struct bxe_fastpath        *fp,
4925                  struct mbuf                *m,
4926                  struct eth_tx_parse_bd_e1x *pbd)
4927 {
4928     struct ether_vlan_header *eh = NULL;
4929     struct ip *ip4 = NULL;
4930     struct ip6_hdr *ip6 = NULL;
4931     caddr_t ip = NULL;
4932     struct tcphdr *th = NULL;
4933     struct udphdr *uh = NULL;
4934     int e_hlen, ip_hlen;
4935     uint16_t proto;
4936     uint8_t hlen;
4937     uint16_t tmp_csum;
4938     uint32_t *tmp_uh;
4939
4940     /* get the Ethernet header */
4941     eh = mtod(m, struct ether_vlan_header *);
4942
4943     /* handle VLAN encapsulation if present */
4944     if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
4945         e_hlen = (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
4946         proto  = ntohs(eh->evl_proto);
4947     } else {
4948         e_hlen = ETHER_HDR_LEN;
4949         proto  = ntohs(eh->evl_encap_proto);
4950     }
4951
4952     switch (proto) {
4953     case ETHERTYPE_IP:
4954         /* get the IP header, if mbuf len < 20 then header in next mbuf */
4955         ip4 = (m->m_len < sizeof(struct ip)) ?
4956                   (struct ip *)m->m_next->m_data :
4957                   (struct ip *)(m->m_data + e_hlen);
4958         /* ip_hl is number of 32-bit words */
4959         ip_hlen = (ip4->ip_hl << 1);
4960         ip = (caddr_t)ip4;
4961         break;
4962     case ETHERTYPE_IPV6:
4963         /* get the IPv6 header, if mbuf len < 40 then header in next mbuf */
4964         ip6 = (m->m_len < sizeof(struct ip6_hdr)) ?
4965                   (struct ip6_hdr *)m->m_next->m_data :
4966                   (struct ip6_hdr *)(m->m_data + e_hlen);
4967         /* XXX cannot support offload with IPv6 extensions */
4968         ip_hlen = (sizeof(struct ip6_hdr) >> 1);
4969         ip = (caddr_t)ip6;
4970         break;
4971     default:
4972         /* We can't offload in this case... */
4973         /* XXX error stat ??? */
4974         return (0);
4975     }
4976
4977     hlen = (e_hlen >> 1);
4978
4979     /* note that rest of global_data is indirectly zeroed here */
4980     if (m->m_flags & M_VLANTAG) {
4981         pbd->global_data =
4982             htole16(hlen | (1 << ETH_TX_PARSE_BD_E1X_LLC_SNAP_EN_SHIFT));
4983     } else {
4984         pbd->global_data = htole16(hlen);
4985     }
4986
4987     pbd->ip_hlen_w = ip_hlen;
4988
4989     hlen += pbd->ip_hlen_w;
4990
4991     /* XXX assuming L4 header is contiguous to IPv4/IPv6 in the same mbuf */
4992
4993     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
4994                                   CSUM_TSO |
4995                                   CSUM_TCP_IPV6)) {
4996         th = (struct tcphdr *)(ip + (ip_hlen << 1));
4997         /* th_off is number of 32-bit words */
4998         hlen += (uint16_t)(th->th_off << 1);
4999     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5000                                          CSUM_UDP_IPV6)) {
5001         uh = (struct udphdr *)(ip + (ip_hlen << 1));
5002         hlen += (sizeof(struct udphdr) / 2);
5003     } else {
5004         /* valid case as only CSUM_IP was set */
5005         return (0);
5006     }
5007
5008     pbd->total_hlen_w = htole16(hlen);
5009
5010     if (m->m_pkthdr.csum_flags & (CSUM_TCP |
5011                                   CSUM_TSO |
5012                                   CSUM_TCP_IPV6)) {
5013         fp->eth_q_stats.tx_ofld_frames_csum_tcp++;
5014         pbd->tcp_pseudo_csum = ntohs(th->th_sum);
5015     } else if (m->m_pkthdr.csum_flags & (CSUM_UDP |
5016                                          CSUM_UDP_IPV6)) {
5017         fp->eth_q_stats.tx_ofld_frames_csum_udp++;
5018
5019         /*
5020          * Everest1 (i.e. 57710, 57711, 57711E) does not natively support UDP
5021          * checksums and does not know anything about the UDP header and where
5022          * the checksum field is located. It only knows about TCP. Therefore
5023          * we "lie" to the hardware for outgoing UDP packets w/ checksum
5024          * offload. Since the checksum field offset for TCP is 16 bytes and
5025          * for UDP it is 6 bytes we pass a pointer to the hardware that is 10
5026          * bytes less than the start of the UDP header. This allows the
5027          * hardware to write the checksum in the correct spot. But the
5028          * hardware will compute a checksum which includes the last 10 bytes
5029          * of the IP header. To correct this we tweak the stack computed
5030          * pseudo checksum by folding in the calculation of the inverse
5031          * checksum for those final 10 bytes of the IP header. This allows
5032          * the correct checksum to be computed by the hardware.
5033          */
5034
5035         /* set pointer 10 bytes before UDP header */
5036         tmp_uh = (uint32_t *)((uint8_t *)uh - 10);
5037
5038         /* calculate a pseudo header checksum over the first 10 bytes */
5039         tmp_csum = in_pseudo(*tmp_uh,
5040                              *(tmp_uh + 1),
5041                              *(uint16_t *)(tmp_uh + 2));
5042
5043         pbd->tcp_pseudo_csum = ntohs(in_addword(uh->uh_sum, ~tmp_csum));
5044     }
5045
5046     return (hlen * 2); /* entire header length, number of bytes */
5047 }
5048
5049 static void
5050 bxe_set_pbd_lso_e2(struct mbuf *m,
5051                    uint32_t    *parsing_data)
5052 {
5053     *parsing_data |= ((m->m_pkthdr.tso_segsz <<
5054                        ETH_TX_PARSE_BD_E2_LSO_MSS_SHIFT) &
5055                       ETH_TX_PARSE_BD_E2_LSO_MSS);
5056
5057     /* XXX test for IPv6 with extension header... */
5058 }
5059
5060 static void
5061 bxe_set_pbd_lso(struct mbuf                *m,
5062                 struct eth_tx_parse_bd_e1x *pbd)
5063 {
5064     struct ether_vlan_header *eh = NULL;
5065     struct ip *ip = NULL;
5066     struct tcphdr *th = NULL;
5067     int e_hlen;
5068
5069     /* get the Ethernet header */
5070     eh = mtod(m, struct ether_vlan_header *);
5071
5072     /* handle VLAN encapsulation if present */
5073     e_hlen = (eh->evl_encap_proto == htons(ETHERTYPE_VLAN)) ?
5074                  (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) : ETHER_HDR_LEN;
5075
5076     /* get the IP and TCP header, with LSO entire header in first mbuf */
5077     /* XXX assuming IPv4 */
5078     ip = (struct ip *)(m->m_data + e_hlen);
5079     th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
5080
5081     pbd->lso_mss = htole16(m->m_pkthdr.tso_segsz);
5082     pbd->tcp_send_seq = ntohl(th->th_seq);
5083     pbd->tcp_flags = ((ntohl(((uint32_t *)th)[3]) >> 16) & 0xff);
5084
5085 #if 1
5086         /* XXX IPv4 */
5087         pbd->ip_id = ntohs(ip->ip_id);
5088         pbd->tcp_pseudo_csum =
5089             ntohs(in_pseudo(ip->ip_src.s_addr,
5090                             ip->ip_dst.s_addr,
5091                             htons(IPPROTO_TCP)));
5092 #else
5093         /* XXX IPv6 */
5094         pbd->tcp_pseudo_csum =
5095             ntohs(in_pseudo(&ip6->ip6_src,
5096                             &ip6->ip6_dst,
5097                             htons(IPPROTO_TCP)));
5098 #endif
5099
5100     pbd->global_data |=
5101         htole16(ETH_TX_PARSE_BD_E1X_PSEUDO_CS_WITHOUT_LEN);
5102 }
5103
5104 /*
5105  * Encapsulte an mbuf cluster into the tx bd chain and makes the memory
5106  * visible to the controller.
5107  *
5108  * If an mbuf is submitted to this routine and cannot be given to the
5109  * controller (e.g. it has too many fragments) then the function may free
5110  * the mbuf and return to the caller.
5111  *
5112  * Returns:
5113  *   0 = Success, !0 = Failure
5114  *   Note the side effect that an mbuf may be freed if it causes a problem.
5115  */
5116 static int
5117 bxe_tx_encap(struct bxe_fastpath *fp, struct mbuf **m_head)
5118 {
5119     bus_dma_segment_t segs[32];
5120     struct mbuf *m0;
5121     struct bxe_sw_tx_bd *tx_buf;
5122     struct eth_tx_parse_bd_e1x *pbd_e1x = NULL;
5123     struct eth_tx_parse_bd_e2 *pbd_e2 = NULL;
5124     /* struct eth_tx_parse_2nd_bd *pbd2 = NULL; */
5125     struct eth_tx_bd *tx_data_bd;
5126     struct eth_tx_bd *tx_total_pkt_size_bd;
5127     struct eth_tx_start_bd *tx_start_bd;
5128     uint16_t bd_prod, pkt_prod, total_pkt_size;
5129     uint8_t mac_type;
5130     int defragged, error, nsegs, rc, nbds, vlan_off, ovlan;
5131     struct bxe_softc *sc;
5132     uint16_t tx_bd_avail;
5133     struct ether_vlan_header *eh;
5134     uint32_t pbd_e2_parsing_data = 0;
5135     uint8_t hlen = 0;
5136     int tmp_bd;
5137     int i;
5138
5139     sc = fp->sc;
5140
5141 #if __FreeBSD_version >= 800000
5142     M_ASSERTPKTHDR(*m_head);
5143 #endif /* #if __FreeBSD_version >= 800000 */
5144
5145     m0 = *m_head;
5146     rc = defragged = nbds = ovlan = vlan_off = total_pkt_size = 0;
5147     tx_start_bd = NULL;
5148     tx_data_bd = NULL;
5149     tx_total_pkt_size_bd = NULL;
5150
5151     /* get the H/W pointer for packets and BDs */
5152     pkt_prod = fp->tx_pkt_prod;
5153     bd_prod = fp->tx_bd_prod;
5154
5155     mac_type = UNICAST_ADDRESS;
5156
5157     /* map the mbuf into the next open DMAable memory */
5158     tx_buf = &fp->tx_mbuf_chain[TX_BD(pkt_prod)];
5159     error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5160                                     tx_buf->m_map, m0,
5161                                     segs, &nsegs, BUS_DMA_NOWAIT);
5162
5163     /* mapping errors */
5164     if(__predict_false(error != 0)) {
5165         fp->eth_q_stats.tx_dma_mapping_failure++;
5166         if (error == ENOMEM) {
5167             /* resource issue, try again later */
5168             rc = ENOMEM;
5169         } else if (error == EFBIG) {
5170             /* possibly recoverable with defragmentation */
5171             fp->eth_q_stats.mbuf_defrag_attempts++;
5172             m0 = m_defrag(*m_head, M_DONTWAIT);
5173             if (m0 == NULL) {
5174                 fp->eth_q_stats.mbuf_defrag_failures++;
5175                 rc = ENOBUFS;
5176             } else {
5177                 /* defrag successful, try mapping again */
5178                 *m_head = m0;
5179                 error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5180                                                 tx_buf->m_map, m0,
5181                                                 segs, &nsegs, BUS_DMA_NOWAIT);
5182                 if (error) {
5183                     fp->eth_q_stats.tx_dma_mapping_failure++;
5184                     rc = error;
5185                 }
5186             }
5187         } else {
5188             /* unknown, unrecoverable mapping error */
5189             BLOGE(sc, "Unknown TX mapping error rc=%d\n", error);
5190             bxe_dump_mbuf(sc, m0, FALSE);
5191             rc = error;
5192         }
5193
5194         goto bxe_tx_encap_continue;
5195     }
5196
5197     tx_bd_avail = bxe_tx_avail(sc, fp);
5198
5199     /* make sure there is enough room in the send queue */
5200     if (__predict_false(tx_bd_avail < (nsegs + 2))) {
5201         /* Recoverable, try again later. */
5202         fp->eth_q_stats.tx_hw_queue_full++;
5203         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5204         rc = ENOMEM;
5205         goto bxe_tx_encap_continue;
5206     }
5207
5208     /* capture the current H/W TX chain high watermark */
5209     if (__predict_false(fp->eth_q_stats.tx_hw_max_queue_depth <
5210                         (TX_BD_USABLE - tx_bd_avail))) {
5211         fp->eth_q_stats.tx_hw_max_queue_depth = (TX_BD_USABLE - tx_bd_avail);
5212     }
5213
5214     /* make sure it fits in the packet window */
5215     if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5216         /*
5217          * The mbuf may be to big for the controller to handle. If the frame
5218          * is a TSO frame we'll need to do an additional check.
5219          */
5220         if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5221             if (bxe_chktso_window(sc, nsegs, segs, m0) == 0) {
5222                 goto bxe_tx_encap_continue; /* OK to send */
5223             } else {
5224                 fp->eth_q_stats.tx_window_violation_tso++;
5225             }
5226         } else {
5227             fp->eth_q_stats.tx_window_violation_std++;
5228         }
5229
5230         /* lets try to defragment this mbuf and remap it */
5231         fp->eth_q_stats.mbuf_defrag_attempts++;
5232         bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5233
5234         m0 = m_defrag(*m_head, M_DONTWAIT);
5235         if (m0 == NULL) {
5236             fp->eth_q_stats.mbuf_defrag_failures++;
5237             /* Ugh, just drop the frame... :( */
5238             rc = ENOBUFS;
5239         } else {
5240             /* defrag successful, try mapping again */
5241             *m_head = m0;
5242             error = bus_dmamap_load_mbuf_sg(fp->tx_mbuf_tag,
5243                                             tx_buf->m_map, m0,
5244                                             segs, &nsegs, BUS_DMA_NOWAIT);
5245             if (error) {
5246                 fp->eth_q_stats.tx_dma_mapping_failure++;
5247                 /* No sense in trying to defrag/copy chain, drop it. :( */
5248                 rc = error;
5249             }
5250             else {
5251                 /* if the chain is still too long then drop it */
5252                 if (__predict_false(nsegs > BXE_MAX_SEGMENTS)) {
5253                     bus_dmamap_unload(fp->tx_mbuf_tag, tx_buf->m_map);
5254                     rc = ENODEV;
5255                 }
5256             }
5257         }
5258     }
5259
5260 bxe_tx_encap_continue:
5261
5262     /* Check for errors */
5263     if (rc) {
5264         if (rc == ENOMEM) {
5265             /* recoverable try again later  */
5266         } else {
5267             fp->eth_q_stats.tx_soft_errors++;
5268             fp->eth_q_stats.mbuf_alloc_tx--;
5269             m_freem(*m_head);
5270             *m_head = NULL;
5271         }
5272
5273         return (rc);
5274     }
5275
5276     /* set flag according to packet type (UNICAST_ADDRESS is default) */
5277     if (m0->m_flags & M_BCAST) {
5278         mac_type = BROADCAST_ADDRESS;
5279     } else if (m0->m_flags & M_MCAST) {
5280         mac_type = MULTICAST_ADDRESS;
5281     }
5282
5283     /* store the mbuf into the mbuf ring */
5284     tx_buf->m        = m0;
5285     tx_buf->first_bd = fp->tx_bd_prod;
5286     tx_buf->flags    = 0;
5287
5288     /* prepare the first transmit (start) BD for the mbuf */
5289     tx_start_bd = &fp->tx_chain[TX_BD(bd_prod)].start_bd;
5290
5291     BLOGD(sc, DBG_TX,
5292           "sending pkt_prod=%u tx_buf=%p next_idx=%u bd=%u tx_start_bd=%p\n",
5293           pkt_prod, tx_buf, fp->tx_pkt_prod, bd_prod, tx_start_bd);
5294
5295     tx_start_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
5296     tx_start_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
5297     tx_start_bd->nbytes  = htole16(segs[0].ds_len);
5298     total_pkt_size += tx_start_bd->nbytes;
5299     tx_start_bd->bd_flags.as_bitfield = ETH_TX_BD_FLAGS_START_BD;
5300
5301     tx_start_bd->general_data = (1 << ETH_TX_START_BD_HDR_NBDS_SHIFT);
5302
5303     /* all frames have at least Start BD + Parsing BD */
5304     nbds = nsegs + 1;
5305     tx_start_bd->nbd = htole16(nbds);
5306
5307     if (m0->m_flags & M_VLANTAG) {
5308         tx_start_bd->vlan_or_ethertype = htole16(m0->m_pkthdr.ether_vtag);
5309         tx_start_bd->bd_flags.as_bitfield |=
5310             (X_ETH_OUTBAND_VLAN << ETH_TX_BD_FLAGS_VLAN_MODE_SHIFT);
5311     } else {
5312         /* vf tx, start bd must hold the ethertype for fw to enforce it */
5313         if (IS_VF(sc)) {
5314             /* map ethernet header to find type and header length */
5315             eh = mtod(m0, struct ether_vlan_header *);
5316             tx_start_bd->vlan_or_ethertype = eh->evl_encap_proto;
5317         } else {
5318             /* used by FW for packet accounting */
5319             tx_start_bd->vlan_or_ethertype = htole16(fp->tx_pkt_prod);
5320         }
5321     }
5322
5323     /*
5324      * add a parsing BD from the chain. The parsing BD is always added
5325      * though it is only used for TSO and chksum
5326      */
5327     bd_prod = TX_BD_NEXT(bd_prod);
5328
5329     if (m0->m_pkthdr.csum_flags) {
5330         if (m0->m_pkthdr.csum_flags & CSUM_IP) {
5331             fp->eth_q_stats.tx_ofld_frames_csum_ip++;
5332             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_IP_CSUM;
5333         }
5334
5335         if (m0->m_pkthdr.csum_flags & CSUM_TCP_IPV6) {
5336             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6 |
5337                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5338         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP_IPV6) {
5339             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_IPV6   |
5340                                                   ETH_TX_BD_FLAGS_IS_UDP |
5341                                                   ETH_TX_BD_FLAGS_L4_CSUM);
5342         } else if ((m0->m_pkthdr.csum_flags & CSUM_TCP) ||
5343                    (m0->m_pkthdr.csum_flags & CSUM_TSO)) {
5344             tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_L4_CSUM;
5345         } else if (m0->m_pkthdr.csum_flags & CSUM_UDP) {
5346             tx_start_bd->bd_flags.as_bitfield |= (ETH_TX_BD_FLAGS_L4_CSUM |
5347                                                   ETH_TX_BD_FLAGS_IS_UDP);
5348         }
5349     }
5350
5351     if (!CHIP_IS_E1x(sc)) {
5352         pbd_e2 = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e2;
5353         memset(pbd_e2, 0, sizeof(struct eth_tx_parse_bd_e2));
5354
5355         if (m0->m_pkthdr.csum_flags) {
5356             hlen = bxe_set_pbd_csum_e2(fp, m0, &pbd_e2_parsing_data);
5357         }
5358
5359         SET_FLAG(pbd_e2_parsing_data, ETH_TX_PARSE_BD_E2_ETH_ADDR_TYPE,
5360                  mac_type);
5361     } else {
5362         uint16_t global_data = 0;
5363
5364         pbd_e1x = &fp->tx_chain[TX_BD(bd_prod)].parse_bd_e1x;
5365         memset(pbd_e1x, 0, sizeof(struct eth_tx_parse_bd_e1x));
5366
5367         if (m0->m_pkthdr.csum_flags) {
5368             hlen = bxe_set_pbd_csum(fp, m0, pbd_e1x);
5369         }
5370
5371         SET_FLAG(global_data,
5372                  ETH_TX_PARSE_BD_E1X_ETH_ADDR_TYPE, mac_type);
5373         pbd_e1x->global_data |= htole16(global_data);
5374     }
5375
5376     /* setup the parsing BD with TSO specific info */
5377     if (m0->m_pkthdr.csum_flags & CSUM_TSO) {
5378         fp->eth_q_stats.tx_ofld_frames_lso++;
5379         tx_start_bd->bd_flags.as_bitfield |= ETH_TX_BD_FLAGS_SW_LSO;
5380
5381         if (__predict_false(tx_start_bd->nbytes > hlen)) {
5382             fp->eth_q_stats.tx_ofld_frames_lso_hdr_splits++;
5383
5384             /* split the first BD into header/data making the fw job easy */
5385             nbds++;
5386             tx_start_bd->nbd = htole16(nbds);
5387             tx_start_bd->nbytes = htole16(hlen);
5388
5389             bd_prod = TX_BD_NEXT(bd_prod);
5390
5391             /* new transmit BD after the tx_parse_bd */
5392             tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5393             tx_data_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr + hlen));
5394             tx_data_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr + hlen));
5395             tx_data_bd->nbytes  = htole16(segs[0].ds_len - hlen);
5396             if (tx_total_pkt_size_bd == NULL) {
5397                 tx_total_pkt_size_bd = tx_data_bd;
5398             }
5399
5400             BLOGD(sc, DBG_TX,
5401                   "TSO split header size is %d (%x:%x) nbds %d\n",
5402                   le16toh(tx_start_bd->nbytes),
5403                   le32toh(tx_start_bd->addr_hi),
5404                   le32toh(tx_start_bd->addr_lo),
5405                   nbds);
5406         }
5407
5408         if (!CHIP_IS_E1x(sc)) {
5409             bxe_set_pbd_lso_e2(m0, &pbd_e2_parsing_data);
5410         } else {
5411             bxe_set_pbd_lso(m0, pbd_e1x);
5412         }
5413     }
5414
5415     if (pbd_e2_parsing_data) {
5416         pbd_e2->parsing_data = htole32(pbd_e2_parsing_data);
5417     }
5418
5419     /* prepare remaining BDs, start tx bd contains first seg/frag */
5420     for (i = 1; i < nsegs ; i++) {
5421         bd_prod = TX_BD_NEXT(bd_prod);
5422         tx_data_bd = &fp->tx_chain[TX_BD(bd_prod)].reg_bd;
5423         tx_data_bd->addr_lo = htole32(U64_LO(segs[i].ds_addr));
5424         tx_data_bd->addr_hi = htole32(U64_HI(segs[i].ds_addr));
5425         tx_data_bd->nbytes  = htole16(segs[i].ds_len);
5426         if (tx_total_pkt_size_bd == NULL) {
5427             tx_total_pkt_size_bd = tx_data_bd;
5428         }
5429         total_pkt_size += tx_data_bd->nbytes;
5430     }
5431
5432     BLOGD(sc, DBG_TX, "last bd %p\n", tx_data_bd);
5433
5434     if (tx_total_pkt_size_bd != NULL) {
5435         tx_total_pkt_size_bd->total_pkt_bytes = total_pkt_size;
5436     }
5437
5438     if (__predict_false(sc->debug & DBG_TX)) {
5439         tmp_bd = tx_buf->first_bd;
5440         for (i = 0; i < nbds; i++)
5441         {
5442             if (i == 0) {
5443                 BLOGD(sc, DBG_TX,
5444                       "TX Strt: %p bd=%d nbd=%d vlan=0x%x "
5445                       "bd_flags=0x%x hdr_nbds=%d\n",
5446                       tx_start_bd,
5447                       tmp_bd,
5448                       le16toh(tx_start_bd->nbd),
5449                       le16toh(tx_start_bd->vlan_or_ethertype),
5450                       tx_start_bd->bd_flags.as_bitfield,
5451                       (tx_start_bd->general_data & ETH_TX_START_BD_HDR_NBDS));
5452             } else if (i == 1) {
5453                 if (pbd_e1x) {
5454                     BLOGD(sc, DBG_TX,
5455                           "-> Prse: %p bd=%d global=0x%x ip_hlen_w=%u "
5456                           "ip_id=%u lso_mss=%u tcp_flags=0x%x csum=0x%x "
5457                           "tcp_seq=%u total_hlen_w=%u\n",
5458                           pbd_e1x,
5459                           tmp_bd,
5460                           pbd_e1x->global_data,
5461                           pbd_e1x->ip_hlen_w,
5462                           pbd_e1x->ip_id,
5463                           pbd_e1x->lso_mss,
5464                           pbd_e1x->tcp_flags,
5465                           pbd_e1x->tcp_pseudo_csum,
5466                           pbd_e1x->tcp_send_seq,
5467                           le16toh(pbd_e1x->total_hlen_w));
5468                 } else { /* if (pbd_e2) */
5469                     BLOGD(sc, DBG_TX,
5470                           "-> Parse: %p bd=%d dst=%02x:%02x:%02x "
5471                           "src=%02x:%02x:%02x parsing_data=0x%x\n",
5472                           pbd_e2,
5473                           tmp_bd,
5474                           pbd_e2->data.mac_addr.dst_hi,
5475                           pbd_e2->data.mac_addr.dst_mid,
5476                           pbd_e2->data.mac_addr.dst_lo,
5477                           pbd_e2->data.mac_addr.src_hi,
5478                           pbd_e2->data.mac_addr.src_mid,
5479                           pbd_e2->data.mac_addr.src_lo,
5480                           pbd_e2->parsing_data);
5481                 }
5482             }
5483
5484             if (i != 1) { /* skip parse db as it doesn't hold data */
5485                 tx_data_bd = &fp->tx_chain[TX_BD(tmp_bd)].reg_bd;
5486                 BLOGD(sc, DBG_TX,
5487                       "-> Frag: %p bd=%d nbytes=%d hi=0x%x lo: 0x%x\n",
5488                       tx_data_bd,
5489                       tmp_bd,
5490                       le16toh(tx_data_bd->nbytes),
5491                       le32toh(tx_data_bd->addr_hi),
5492                       le32toh(tx_data_bd->addr_lo));
5493             }
5494
5495             tmp_bd = TX_BD_NEXT(tmp_bd);
5496         }
5497     }
5498
5499     BLOGD(sc, DBG_TX, "doorbell: nbds=%d bd=%u\n", nbds, bd_prod);
5500
5501     /* update TX BD producer index value for next TX */
5502     bd_prod = TX_BD_NEXT(bd_prod);
5503
5504     /*
5505      * If the chain of tx_bd's describing this frame is adjacent to or spans
5506      * an eth_tx_next_bd element then we need to increment the nbds value.
5507      */
5508     if (TX_BD_IDX(bd_prod) < nbds) {
5509         nbds++;
5510     }
5511
5512     /* don't allow reordering of writes for nbd and packets */
5513     mb();
5514
5515     fp->tx_db.data.prod += nbds;
5516
5517     /* producer points to the next free tx_bd at this point */
5518     fp->tx_pkt_prod++;
5519     fp->tx_bd_prod = bd_prod;
5520
5521     DOORBELL(sc, fp->index, fp->tx_db.raw);
5522
5523     fp->eth_q_stats.tx_pkts++;
5524
5525     /* Prevent speculative reads from getting ahead of the status block. */
5526     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle,
5527                       0, 0, BUS_SPACE_BARRIER_READ);
5528
5529     /* Prevent speculative reads from getting ahead of the doorbell. */
5530     bus_space_barrier(sc->bar[BAR2].tag, sc->bar[BAR2].handle,
5531                       0, 0, BUS_SPACE_BARRIER_READ);
5532
5533     return (0);
5534 }
5535
5536 static void
5537 bxe_tx_start_locked(struct bxe_softc    *sc,
5538                     struct ifnet        *ifp,
5539                     struct bxe_fastpath *fp)
5540 {
5541     struct mbuf *m = NULL;
5542     int tx_count = 0;
5543     uint16_t tx_bd_avail;
5544
5545     BXE_FP_TX_LOCK_ASSERT(fp);
5546
5547     /* keep adding entries while there are frames to send */
5548     while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
5549
5550         /*
5551          * check for any frames to send
5552          * dequeue can still be NULL even if queue is not empty
5553          */
5554         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
5555         if (__predict_false(m == NULL)) {
5556             break;
5557         }
5558
5559         /* the mbuf now belongs to us */
5560         fp->eth_q_stats.mbuf_alloc_tx++;
5561
5562         /*
5563          * Put the frame into the transmit ring. If we don't have room,
5564          * place the mbuf back at the head of the TX queue, set the
5565          * OACTIVE flag, and wait for the NIC to drain the chain.
5566          */
5567         if (__predict_false(bxe_tx_encap(fp, &m))) {
5568             fp->eth_q_stats.tx_encap_failures++;
5569             if (m != NULL) {
5570                 /* mark the TX queue as full and return the frame */
5571                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5572                 IFQ_DRV_PREPEND(&ifp->if_snd, m);
5573                 fp->eth_q_stats.mbuf_alloc_tx--;
5574                 fp->eth_q_stats.tx_queue_xoff++;
5575             }
5576
5577             /* stop looking for more work */
5578             break;
5579         }
5580
5581         /* the frame was enqueued successfully */
5582         tx_count++;
5583
5584         /* send a copy of the frame to any BPF listeners. */
5585         BPF_MTAP(ifp, m);
5586
5587         tx_bd_avail = bxe_tx_avail(sc, fp);
5588
5589         /* handle any completions if we're running low */
5590         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5591             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5592             bxe_txeof(sc, fp);
5593             if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5594                 break;
5595             }
5596         }
5597     }
5598
5599     /* all TX packets were dequeued and/or the tx ring is full */
5600     if (tx_count > 0) {
5601         /* reset the TX watchdog timeout timer */
5602         fp->watchdog_timer = BXE_TX_TIMEOUT;
5603     }
5604 }
5605
5606 /* Legacy (non-RSS) dispatch routine */
5607 static void
5608 bxe_tx_start(struct ifnet *ifp)
5609 {
5610     struct bxe_softc *sc;
5611     struct bxe_fastpath *fp;
5612
5613     sc = ifp->if_softc;
5614
5615     if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5616         BLOGW(sc, "Interface not running, ignoring transmit request\n");
5617         return;
5618     }
5619
5620     if (!sc->link_vars.link_up) {
5621         BLOGW(sc, "Interface link is down, ignoring transmit request\n");
5622         return;
5623     }
5624
5625     fp = &sc->fp[0];
5626
5627     if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
5628         fp->eth_q_stats.tx_queue_full_return++;
5629         return;
5630     }
5631
5632     BXE_FP_TX_LOCK(fp);
5633     bxe_tx_start_locked(sc, ifp, fp);
5634     BXE_FP_TX_UNLOCK(fp);
5635 }
5636
5637 #if __FreeBSD_version >= 901504
5638
5639 static int
5640 bxe_tx_mq_start_locked(struct bxe_softc    *sc,
5641                        struct ifnet        *ifp,
5642                        struct bxe_fastpath *fp,
5643                        struct mbuf         *m)
5644 {
5645     struct buf_ring *tx_br = fp->tx_br;
5646     struct mbuf *next;
5647     int depth, rc, tx_count;
5648     uint16_t tx_bd_avail;
5649
5650     rc = tx_count = 0;
5651
5652     BXE_FP_TX_LOCK_ASSERT(fp);
5653
5654     if (!tx_br) {
5655         BLOGE(sc, "Multiqueue TX and no buf_ring!\n");
5656         return (EINVAL);
5657     }
5658
5659     if (m != NULL) {
5660         rc = drbr_enqueue(ifp, tx_br, m);
5661         if (rc != 0) {
5662             fp->eth_q_stats.tx_soft_errors++;
5663             goto bxe_tx_mq_start_locked_exit;
5664         }
5665     }
5666
5667     if (!sc->link_vars.link_up || !(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
5668         fp->eth_q_stats.tx_request_link_down_failures++;
5669         goto bxe_tx_mq_start_locked_exit;
5670     }
5671
5672     /* fetch the depth of the driver queue */
5673     depth = drbr_inuse(ifp, tx_br);
5674     if (depth > fp->eth_q_stats.tx_max_drbr_queue_depth) {
5675         fp->eth_q_stats.tx_max_drbr_queue_depth = depth;
5676     }
5677
5678     /* keep adding entries while there are frames to send */
5679     while ((next = drbr_peek(ifp, tx_br)) != NULL) {
5680         /* handle any completions if we're running low */
5681         tx_bd_avail = bxe_tx_avail(sc, fp);
5682         if (tx_bd_avail < BXE_TX_CLEANUP_THRESHOLD) {
5683             /* bxe_txeof will set IFF_DRV_OACTIVE appropriately */
5684             bxe_txeof(sc, fp);
5685             tx_bd_avail = bxe_tx_avail(sc, fp);
5686             if (tx_bd_avail < (BXE_TSO_MAX_SEGMENTS + 1)) {
5687                 fp->eth_q_stats.bd_avail_too_less_failures++;
5688                 m_freem(next);
5689                 drbr_advance(ifp, tx_br);
5690                 rc = ENOBUFS;
5691                 break;
5692             }
5693         }
5694
5695         /* the mbuf now belongs to us */
5696         fp->eth_q_stats.mbuf_alloc_tx++;
5697
5698         /*
5699          * Put the frame into the transmit ring. If we don't have room,
5700          * place the mbuf back at the head of the TX queue, set the
5701          * OACTIVE flag, and wait for the NIC to drain the chain.
5702          */
5703         rc = bxe_tx_encap(fp, &next);
5704         if (__predict_false(rc != 0)) {
5705             fp->eth_q_stats.tx_encap_failures++;
5706             if (next != NULL) {
5707                 /* mark the TX queue as full and save the frame */
5708                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5709                 drbr_putback(ifp, tx_br, next);
5710                 fp->eth_q_stats.mbuf_alloc_tx--;
5711                 fp->eth_q_stats.tx_frames_deferred++;
5712             } else
5713                 drbr_advance(ifp, tx_br);
5714
5715             /* stop looking for more work */
5716             break;
5717         }
5718
5719         /* the transmit frame was enqueued successfully */
5720         tx_count++;
5721
5722         /* send a copy of the frame to any BPF listeners */
5723         BPF_MTAP(ifp, next);
5724
5725         drbr_advance(ifp, tx_br);
5726     }
5727
5728     /* all TX packets were dequeued and/or the tx ring is full */
5729     if (tx_count > 0) {
5730         /* reset the TX watchdog timeout timer */
5731         fp->watchdog_timer = BXE_TX_TIMEOUT;
5732     }
5733
5734 bxe_tx_mq_start_locked_exit:
5735     /* If we didn't drain the drbr, enqueue a task in the future to do it. */
5736     if (!drbr_empty(ifp, tx_br)) {
5737         fp->eth_q_stats.tx_mq_not_empty++;
5738         taskqueue_enqueue_timeout(fp->tq, &fp->tx_timeout_task, 1);
5739     }
5740
5741     return (rc);
5742 }
5743
5744 static void
5745 bxe_tx_mq_start_deferred(void *arg,
5746                          int pending)
5747 {
5748     struct bxe_fastpath *fp = (struct bxe_fastpath *)arg;
5749     struct bxe_softc *sc = fp->sc;
5750     struct ifnet *ifp = sc->ifnet;
5751
5752     BXE_FP_TX_LOCK(fp);
5753     bxe_tx_mq_start_locked(sc, ifp, fp, NULL);
5754     BXE_FP_TX_UNLOCK(fp);
5755 }
5756
5757 /* Multiqueue (TSS) dispatch routine. */
5758 static int
5759 bxe_tx_mq_start(struct ifnet *ifp,
5760                 struct mbuf  *m)
5761 {
5762     struct bxe_softc *sc = ifp->if_softc;
5763     struct bxe_fastpath *fp;
5764     int fp_index, rc;
5765
5766     fp_index = 0; /* default is the first queue */
5767
5768     /* check if flowid is set */
5769
5770     if (BXE_VALID_FLOWID(m))
5771         fp_index = (m->m_pkthdr.flowid % sc->num_queues);
5772
5773     fp = &sc->fp[fp_index];
5774
5775     if (BXE_FP_TX_TRYLOCK(fp)) {
5776         rc = bxe_tx_mq_start_locked(sc, ifp, fp, m);
5777         BXE_FP_TX_UNLOCK(fp);
5778     } else {
5779         rc = drbr_enqueue(ifp, fp->tx_br, m);
5780         taskqueue_enqueue(fp->tq, &fp->tx_task);
5781     }
5782
5783     return (rc);
5784 }
5785
5786 static void
5787 bxe_mq_flush(struct ifnet *ifp)
5788 {
5789     struct bxe_softc *sc = ifp->if_softc;
5790     struct bxe_fastpath *fp;
5791     struct mbuf *m;
5792     int i;
5793
5794     for (i = 0; i < sc->num_queues; i++) {
5795         fp = &sc->fp[i];
5796
5797         if (fp->state != BXE_FP_STATE_OPEN) {
5798             BLOGD(sc, DBG_LOAD, "Not clearing fp[%02d] buf_ring (state=%d)\n",
5799                   fp->index, fp->state);
5800             continue;
5801         }
5802
5803         if (fp->tx_br != NULL) {
5804             BLOGD(sc, DBG_LOAD, "Clearing fp[%02d] buf_ring\n", fp->index);
5805             BXE_FP_TX_LOCK(fp);
5806             while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL) {
5807                 m_freem(m);
5808             }
5809             BXE_FP_TX_UNLOCK(fp);
5810         }
5811     }
5812
5813     if_qflush(ifp);
5814 }
5815
5816 #endif /* FreeBSD_version >= 901504 */
5817
5818 static uint16_t
5819 bxe_cid_ilt_lines(struct bxe_softc *sc)
5820 {
5821     if (IS_SRIOV(sc)) {
5822         return ((BXE_FIRST_VF_CID + BXE_VF_CIDS) / ILT_PAGE_CIDS);
5823     }
5824     return (L2_ILT_LINES(sc));
5825 }
5826
5827 static void
5828 bxe_ilt_set_info(struct bxe_softc *sc)
5829 {
5830     struct ilt_client_info *ilt_client;
5831     struct ecore_ilt *ilt = sc->ilt;
5832     uint16_t line = 0;
5833
5834     ilt->start_line = FUNC_ILT_BASE(SC_FUNC(sc));
5835     BLOGD(sc, DBG_LOAD, "ilt starts at line %d\n", ilt->start_line);
5836
5837     /* CDU */
5838     ilt_client = &ilt->clients[ILT_CLIENT_CDU];
5839     ilt_client->client_num = ILT_CLIENT_CDU;
5840     ilt_client->page_size = CDU_ILT_PAGE_SZ;
5841     ilt_client->flags = ILT_CLIENT_SKIP_MEM;
5842     ilt_client->start = line;
5843     line += bxe_cid_ilt_lines(sc);
5844
5845     if (CNIC_SUPPORT(sc)) {
5846         line += CNIC_ILT_LINES;
5847     }
5848
5849     ilt_client->end = (line - 1);
5850
5851     BLOGD(sc, DBG_LOAD,
5852           "ilt client[CDU]: start %d, end %d, "
5853           "psz 0x%x, flags 0x%x, hw psz %d\n",
5854           ilt_client->start, ilt_client->end,
5855           ilt_client->page_size,
5856           ilt_client->flags,
5857           ilog2(ilt_client->page_size >> 12));
5858
5859     /* QM */
5860     if (QM_INIT(sc->qm_cid_count)) {
5861         ilt_client = &ilt->clients[ILT_CLIENT_QM];
5862         ilt_client->client_num = ILT_CLIENT_QM;
5863         ilt_client->page_size = QM_ILT_PAGE_SZ;
5864         ilt_client->flags = 0;
5865         ilt_client->start = line;
5866
5867         /* 4 bytes for each cid */
5868         line += DIV_ROUND_UP(sc->qm_cid_count * QM_QUEUES_PER_FUNC * 4,
5869                              QM_ILT_PAGE_SZ);
5870
5871         ilt_client->end = (line - 1);
5872
5873         BLOGD(sc, DBG_LOAD,
5874               "ilt client[QM]: start %d, end %d, "
5875               "psz 0x%x, flags 0x%x, hw psz %d\n",
5876               ilt_client->start, ilt_client->end,
5877               ilt_client->page_size, ilt_client->flags,
5878               ilog2(ilt_client->page_size >> 12));
5879     }
5880
5881     if (CNIC_SUPPORT(sc)) {
5882         /* SRC */
5883         ilt_client = &ilt->clients[ILT_CLIENT_SRC];
5884         ilt_client->client_num = ILT_CLIENT_SRC;
5885         ilt_client->page_size = SRC_ILT_PAGE_SZ;
5886         ilt_client->flags = 0;
5887         ilt_client->start = line;
5888         line += SRC_ILT_LINES;
5889         ilt_client->end = (line - 1);
5890
5891         BLOGD(sc, DBG_LOAD,
5892               "ilt client[SRC]: start %d, end %d, "
5893               "psz 0x%x, flags 0x%x, hw psz %d\n",
5894               ilt_client->start, ilt_client->end,
5895               ilt_client->page_size, ilt_client->flags,
5896               ilog2(ilt_client->page_size >> 12));
5897
5898         /* TM */
5899         ilt_client = &ilt->clients[ILT_CLIENT_TM];
5900         ilt_client->client_num = ILT_CLIENT_TM;
5901         ilt_client->page_size = TM_ILT_PAGE_SZ;
5902         ilt_client->flags = 0;
5903         ilt_client->start = line;
5904         line += TM_ILT_LINES;
5905         ilt_client->end = (line - 1);
5906
5907         BLOGD(sc, DBG_LOAD,
5908               "ilt client[TM]: start %d, end %d, "
5909               "psz 0x%x, flags 0x%x, hw psz %d\n",
5910               ilt_client->start, ilt_client->end,
5911               ilt_client->page_size, ilt_client->flags,
5912               ilog2(ilt_client->page_size >> 12));
5913     }
5914
5915     KASSERT((line <= ILT_MAX_LINES), ("Invalid number of ILT lines!"));
5916 }
5917
5918 static void
5919 bxe_set_fp_rx_buf_size(struct bxe_softc *sc)
5920 {
5921     int i;
5922     uint32_t rx_buf_size;
5923
5924     rx_buf_size = (IP_HEADER_ALIGNMENT_PADDING + ETH_OVERHEAD + sc->mtu);
5925
5926     for (i = 0; i < sc->num_queues; i++) {
5927         if(rx_buf_size <= MCLBYTES){
5928             sc->fp[i].rx_buf_size = rx_buf_size;
5929             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5930         }else if (rx_buf_size <= MJUMPAGESIZE){
5931             sc->fp[i].rx_buf_size = rx_buf_size;
5932             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5933         }else if (rx_buf_size <= (MJUMPAGESIZE + MCLBYTES)){
5934             sc->fp[i].rx_buf_size = MCLBYTES;
5935             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5936         }else if (rx_buf_size <= (2 * MJUMPAGESIZE)){
5937             sc->fp[i].rx_buf_size = MJUMPAGESIZE;
5938             sc->fp[i].mbuf_alloc_size = MJUMPAGESIZE;
5939         }else {
5940             sc->fp[i].rx_buf_size = MCLBYTES;
5941             sc->fp[i].mbuf_alloc_size = MCLBYTES;
5942         }
5943     }
5944 }
5945
5946 static int
5947 bxe_alloc_ilt_mem(struct bxe_softc *sc)
5948 {
5949     int rc = 0;
5950
5951     if ((sc->ilt =
5952          (struct ecore_ilt *)malloc(sizeof(struct ecore_ilt),
5953                                     M_BXE_ILT,
5954                                     (M_NOWAIT | M_ZERO))) == NULL) {
5955         rc = 1;
5956     }
5957
5958     return (rc);
5959 }
5960
5961 static int
5962 bxe_alloc_ilt_lines_mem(struct bxe_softc *sc)
5963 {
5964     int rc = 0;
5965
5966     if ((sc->ilt->lines =
5967          (struct ilt_line *)malloc((sizeof(struct ilt_line) * ILT_MAX_LINES),
5968                                     M_BXE_ILT,
5969                                     (M_NOWAIT | M_ZERO))) == NULL) {
5970         rc = 1;
5971     }
5972
5973     return (rc);
5974 }
5975
5976 static void
5977 bxe_free_ilt_mem(struct bxe_softc *sc)
5978 {
5979     if (sc->ilt != NULL) {
5980         free(sc->ilt, M_BXE_ILT);
5981         sc->ilt = NULL;
5982     }
5983 }
5984
5985 static void
5986 bxe_free_ilt_lines_mem(struct bxe_softc *sc)
5987 {
5988     if (sc->ilt->lines != NULL) {
5989         free(sc->ilt->lines, M_BXE_ILT);
5990         sc->ilt->lines = NULL;
5991     }
5992 }
5993
5994 static void
5995 bxe_free_mem(struct bxe_softc *sc)
5996 {
5997     int i;
5998
5999     for (i = 0; i < L2_ILT_LINES(sc); i++) {
6000         bxe_dma_free(sc, &sc->context[i].vcxt_dma);
6001         sc->context[i].vcxt = NULL;
6002         sc->context[i].size = 0;
6003     }
6004
6005     ecore_ilt_mem_op(sc, ILT_MEMOP_FREE);
6006
6007     bxe_free_ilt_lines_mem(sc);
6008
6009 }
6010
6011 static int
6012 bxe_alloc_mem(struct bxe_softc *sc)
6013 {
6014     int context_size;
6015     int allocated;
6016     int i;
6017
6018     /*
6019      * Allocate memory for CDU context:
6020      * This memory is allocated separately and not in the generic ILT
6021      * functions because CDU differs in few aspects:
6022      * 1. There can be multiple entities allocating memory for context -
6023      * regular L2, CNIC, and SRIOV drivers. Each separately controls
6024      * its own ILT lines.
6025      * 2. Since CDU page-size is not a single 4KB page (which is the case
6026      * for the other ILT clients), to be efficient we want to support
6027      * allocation of sub-page-size in the last entry.
6028      * 3. Context pointers are used by the driver to pass to FW / update
6029      * the context (for the other ILT clients the pointers are used just to
6030      * free the memory during unload).
6031      */
6032     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
6033     for (i = 0, allocated = 0; allocated < context_size; i++) {
6034         sc->context[i].size = min(CDU_ILT_PAGE_SZ,
6035                                   (context_size - allocated));
6036
6037         if (bxe_dma_alloc(sc, sc->context[i].size,
6038                           &sc->context[i].vcxt_dma,
6039                           "cdu context") != 0) {
6040             bxe_free_mem(sc);
6041             return (-1);
6042         }
6043
6044         sc->context[i].vcxt =
6045             (union cdu_context *)sc->context[i].vcxt_dma.vaddr;
6046
6047         allocated += sc->context[i].size;
6048     }
6049
6050     bxe_alloc_ilt_lines_mem(sc);
6051
6052     BLOGD(sc, DBG_LOAD, "ilt=%p start_line=%u lines=%p\n",
6053           sc->ilt, sc->ilt->start_line, sc->ilt->lines);
6054     {
6055         for (i = 0; i < 4; i++) {
6056             BLOGD(sc, DBG_LOAD,
6057                   "c%d page_size=%u start=%u end=%u num=%u flags=0x%x\n",
6058                   i,
6059                   sc->ilt->clients[i].page_size,
6060                   sc->ilt->clients[i].start,
6061                   sc->ilt->clients[i].end,
6062                   sc->ilt->clients[i].client_num,
6063                   sc->ilt->clients[i].flags);
6064         }
6065     }
6066     if (ecore_ilt_mem_op(sc, ILT_MEMOP_ALLOC)) {
6067         BLOGE(sc, "ecore_ilt_mem_op ILT_MEMOP_ALLOC failed\n");
6068         bxe_free_mem(sc);
6069         return (-1);
6070     }
6071
6072     return (0);
6073 }
6074
6075 static void
6076 bxe_free_rx_bd_chain(struct bxe_fastpath *fp)
6077 {
6078     struct bxe_softc *sc;
6079     int i;
6080
6081     sc = fp->sc;
6082
6083     if (fp->rx_mbuf_tag == NULL) {
6084         return;
6085     }
6086
6087     /* free all mbufs and unload all maps */
6088     for (i = 0; i < RX_BD_TOTAL; i++) {
6089         if (fp->rx_mbuf_chain[i].m_map != NULL) {
6090             bus_dmamap_sync(fp->rx_mbuf_tag,
6091                             fp->rx_mbuf_chain[i].m_map,
6092                             BUS_DMASYNC_POSTREAD);
6093             bus_dmamap_unload(fp->rx_mbuf_tag,
6094                               fp->rx_mbuf_chain[i].m_map);
6095         }
6096
6097         if (fp->rx_mbuf_chain[i].m != NULL) {
6098             m_freem(fp->rx_mbuf_chain[i].m);
6099             fp->rx_mbuf_chain[i].m = NULL;
6100             fp->eth_q_stats.mbuf_alloc_rx--;
6101         }
6102     }
6103 }
6104
6105 static void
6106 bxe_free_tpa_pool(struct bxe_fastpath *fp)
6107 {
6108     struct bxe_softc *sc;
6109     int i, max_agg_queues;
6110
6111     sc = fp->sc;
6112
6113     if (fp->rx_mbuf_tag == NULL) {
6114         return;
6115     }
6116
6117     max_agg_queues = MAX_AGG_QS(sc);
6118
6119     /* release all mbufs and unload all DMA maps in the TPA pool */
6120     for (i = 0; i < max_agg_queues; i++) {
6121         if (fp->rx_tpa_info[i].bd.m_map != NULL) {
6122             bus_dmamap_sync(fp->rx_mbuf_tag,
6123                             fp->rx_tpa_info[i].bd.m_map,
6124                             BUS_DMASYNC_POSTREAD);
6125             bus_dmamap_unload(fp->rx_mbuf_tag,
6126                               fp->rx_tpa_info[i].bd.m_map);
6127         }
6128
6129         if (fp->rx_tpa_info[i].bd.m != NULL) {
6130             m_freem(fp->rx_tpa_info[i].bd.m);
6131             fp->rx_tpa_info[i].bd.m = NULL;
6132             fp->eth_q_stats.mbuf_alloc_tpa--;
6133         }
6134     }
6135 }
6136
6137 static void
6138 bxe_free_sge_chain(struct bxe_fastpath *fp)
6139 {
6140     struct bxe_softc *sc;
6141     int i;
6142
6143     sc = fp->sc;
6144
6145     if (fp->rx_sge_mbuf_tag == NULL) {
6146         return;
6147     }
6148
6149     /* rree all mbufs and unload all maps */
6150     for (i = 0; i < RX_SGE_TOTAL; i++) {
6151         if (fp->rx_sge_mbuf_chain[i].m_map != NULL) {
6152             bus_dmamap_sync(fp->rx_sge_mbuf_tag,
6153                             fp->rx_sge_mbuf_chain[i].m_map,
6154                             BUS_DMASYNC_POSTREAD);
6155             bus_dmamap_unload(fp->rx_sge_mbuf_tag,
6156                               fp->rx_sge_mbuf_chain[i].m_map);
6157         }
6158
6159         if (fp->rx_sge_mbuf_chain[i].m != NULL) {
6160             m_freem(fp->rx_sge_mbuf_chain[i].m);
6161             fp->rx_sge_mbuf_chain[i].m = NULL;
6162             fp->eth_q_stats.mbuf_alloc_sge--;
6163         }
6164     }
6165 }
6166
6167 static void
6168 bxe_free_fp_buffers(struct bxe_softc *sc)
6169 {
6170     struct bxe_fastpath *fp;
6171     int i;
6172
6173     for (i = 0; i < sc->num_queues; i++) {
6174         fp = &sc->fp[i];
6175
6176 #if __FreeBSD_version >= 901504
6177         if (fp->tx_br != NULL) {
6178             /* just in case bxe_mq_flush() wasn't called */
6179             if (mtx_initialized(&fp->tx_mtx)) {
6180                 struct mbuf *m;
6181
6182                 BXE_FP_TX_LOCK(fp);
6183                 while ((m = buf_ring_dequeue_sc(fp->tx_br)) != NULL)
6184                     m_freem(m);
6185                 BXE_FP_TX_UNLOCK(fp);
6186             }
6187         }
6188 #endif
6189
6190         /* free all RX buffers */
6191         bxe_free_rx_bd_chain(fp);
6192         bxe_free_tpa_pool(fp);
6193         bxe_free_sge_chain(fp);
6194
6195         if (fp->eth_q_stats.mbuf_alloc_rx != 0) {
6196             BLOGE(sc, "failed to claim all rx mbufs (%d left)\n",
6197                   fp->eth_q_stats.mbuf_alloc_rx);
6198         }
6199
6200         if (fp->eth_q_stats.mbuf_alloc_sge != 0) {
6201             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6202                   fp->eth_q_stats.mbuf_alloc_sge);
6203         }
6204
6205         if (fp->eth_q_stats.mbuf_alloc_tpa != 0) {
6206             BLOGE(sc, "failed to claim all sge mbufs (%d left)\n",
6207                   fp->eth_q_stats.mbuf_alloc_tpa);
6208         }
6209
6210         if (fp->eth_q_stats.mbuf_alloc_tx != 0) {
6211             BLOGE(sc, "failed to release tx mbufs (%d left)\n",
6212                   fp->eth_q_stats.mbuf_alloc_tx);
6213         }
6214
6215         /* XXX verify all mbufs were reclaimed */
6216     }
6217 }
6218
6219 static int
6220 bxe_alloc_rx_bd_mbuf(struct bxe_fastpath *fp,
6221                      uint16_t            prev_index,
6222                      uint16_t            index)
6223 {
6224     struct bxe_sw_rx_bd *rx_buf;
6225     struct eth_rx_bd *rx_bd;
6226     bus_dma_segment_t segs[1];
6227     bus_dmamap_t map;
6228     struct mbuf *m;
6229     int nsegs, rc;
6230
6231     rc = 0;
6232
6233     /* allocate the new RX BD mbuf */
6234     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6235     if (__predict_false(m == NULL)) {
6236         fp->eth_q_stats.mbuf_rx_bd_alloc_failed++;
6237         return (ENOBUFS);
6238     }
6239
6240     fp->eth_q_stats.mbuf_alloc_rx++;
6241
6242     /* initialize the mbuf buffer length */
6243     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6244
6245     /* map the mbuf into non-paged pool */
6246     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6247                                  fp->rx_mbuf_spare_map,
6248                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6249     if (__predict_false(rc != 0)) {
6250         fp->eth_q_stats.mbuf_rx_bd_mapping_failed++;
6251         m_freem(m);
6252         fp->eth_q_stats.mbuf_alloc_rx--;
6253         return (rc);
6254     }
6255
6256     /* all mbufs must map to a single segment */
6257     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6258
6259     /* release any existing RX BD mbuf mappings */
6260
6261     if (prev_index != index) {
6262         rx_buf = &fp->rx_mbuf_chain[prev_index];
6263
6264         if (rx_buf->m_map != NULL) {
6265             bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6266                             BUS_DMASYNC_POSTREAD);
6267             bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6268         }
6269
6270         /*
6271          * We only get here from bxe_rxeof() when the maximum number
6272          * of rx buffers is less than RX_BD_USABLE. bxe_rxeof() already
6273          * holds the mbuf in the prev_index so it's OK to NULL it out
6274          * here without concern of a memory leak.
6275          */
6276         fp->rx_mbuf_chain[prev_index].m = NULL;
6277     }
6278
6279     rx_buf = &fp->rx_mbuf_chain[index];
6280
6281     if (rx_buf->m_map != NULL) {
6282         bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6283                         BUS_DMASYNC_POSTREAD);
6284         bus_dmamap_unload(fp->rx_mbuf_tag, rx_buf->m_map);
6285     }
6286
6287     /* save the mbuf and mapping info for a future packet */
6288     map = (prev_index != index) ?
6289               fp->rx_mbuf_chain[prev_index].m_map : rx_buf->m_map;
6290     rx_buf->m_map = fp->rx_mbuf_spare_map;
6291     fp->rx_mbuf_spare_map = map;
6292     bus_dmamap_sync(fp->rx_mbuf_tag, rx_buf->m_map,
6293                     BUS_DMASYNC_PREREAD);
6294     rx_buf->m = m;
6295
6296     rx_bd = &fp->rx_chain[index];
6297     rx_bd->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6298     rx_bd->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6299
6300     return (rc);
6301 }
6302
6303 static int
6304 bxe_alloc_rx_tpa_mbuf(struct bxe_fastpath *fp,
6305                       int                 queue)
6306 {
6307     struct bxe_sw_tpa_info *tpa_info = &fp->rx_tpa_info[queue];
6308     bus_dma_segment_t segs[1];
6309     bus_dmamap_t map;
6310     struct mbuf *m;
6311     int nsegs;
6312     int rc = 0;
6313
6314     /* allocate the new TPA mbuf */
6315     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, fp->mbuf_alloc_size);
6316     if (__predict_false(m == NULL)) {
6317         fp->eth_q_stats.mbuf_rx_tpa_alloc_failed++;
6318         return (ENOBUFS);
6319     }
6320
6321     fp->eth_q_stats.mbuf_alloc_tpa++;
6322
6323     /* initialize the mbuf buffer length */
6324     m->m_pkthdr.len = m->m_len = fp->rx_buf_size;
6325
6326     /* map the mbuf into non-paged pool */
6327     rc = bus_dmamap_load_mbuf_sg(fp->rx_mbuf_tag,
6328                                  fp->rx_tpa_info_mbuf_spare_map,
6329                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6330     if (__predict_false(rc != 0)) {
6331         fp->eth_q_stats.mbuf_rx_tpa_mapping_failed++;
6332         m_free(m);
6333         fp->eth_q_stats.mbuf_alloc_tpa--;
6334         return (rc);
6335     }
6336
6337     /* all mbufs must map to a single segment */
6338     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6339
6340     /* release any existing TPA mbuf mapping */
6341     if (tpa_info->bd.m_map != NULL) {
6342         bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6343                         BUS_DMASYNC_POSTREAD);
6344         bus_dmamap_unload(fp->rx_mbuf_tag, tpa_info->bd.m_map);
6345     }
6346
6347     /* save the mbuf and mapping info for the TPA mbuf */
6348     map = tpa_info->bd.m_map;
6349     tpa_info->bd.m_map = fp->rx_tpa_info_mbuf_spare_map;
6350     fp->rx_tpa_info_mbuf_spare_map = map;
6351     bus_dmamap_sync(fp->rx_mbuf_tag, tpa_info->bd.m_map,
6352                     BUS_DMASYNC_PREREAD);
6353     tpa_info->bd.m = m;
6354     tpa_info->seg = segs[0];
6355
6356     return (rc);
6357 }
6358
6359 /*
6360  * Allocate an mbuf and assign it to the receive scatter gather chain. The
6361  * caller must take care to save a copy of the existing mbuf in the SG mbuf
6362  * chain.
6363  */
6364 static int
6365 bxe_alloc_rx_sge_mbuf(struct bxe_fastpath *fp,
6366                       uint16_t            index)
6367 {
6368     struct bxe_sw_rx_bd *sge_buf;
6369     struct eth_rx_sge *sge;
6370     bus_dma_segment_t segs[1];
6371     bus_dmamap_t map;
6372     struct mbuf *m;
6373     int nsegs;
6374     int rc = 0;
6375
6376     /* allocate a new SGE mbuf */
6377     m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, SGE_PAGE_SIZE);
6378     if (__predict_false(m == NULL)) {
6379         fp->eth_q_stats.mbuf_rx_sge_alloc_failed++;
6380         return (ENOMEM);
6381     }
6382
6383     fp->eth_q_stats.mbuf_alloc_sge++;
6384
6385     /* initialize the mbuf buffer length */
6386     m->m_pkthdr.len = m->m_len = SGE_PAGE_SIZE;
6387
6388     /* map the SGE mbuf into non-paged pool */
6389     rc = bus_dmamap_load_mbuf_sg(fp->rx_sge_mbuf_tag,
6390                                  fp->rx_sge_mbuf_spare_map,
6391                                  m, segs, &nsegs, BUS_DMA_NOWAIT);
6392     if (__predict_false(rc != 0)) {
6393         fp->eth_q_stats.mbuf_rx_sge_mapping_failed++;
6394         m_freem(m);
6395         fp->eth_q_stats.mbuf_alloc_sge--;
6396         return (rc);
6397     }
6398
6399     /* all mbufs must map to a single segment */
6400     KASSERT((nsegs == 1), ("Too many segments, %d returned!", nsegs));
6401
6402     sge_buf = &fp->rx_sge_mbuf_chain[index];
6403
6404     /* release any existing SGE mbuf mapping */
6405     if (sge_buf->m_map != NULL) {
6406         bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6407                         BUS_DMASYNC_POSTREAD);
6408         bus_dmamap_unload(fp->rx_sge_mbuf_tag, sge_buf->m_map);
6409     }
6410
6411     /* save the mbuf and mapping info for a future packet */
6412     map = sge_buf->m_map;
6413     sge_buf->m_map = fp->rx_sge_mbuf_spare_map;
6414     fp->rx_sge_mbuf_spare_map = map;
6415     bus_dmamap_sync(fp->rx_sge_mbuf_tag, sge_buf->m_map,
6416                     BUS_DMASYNC_PREREAD);
6417     sge_buf->m = m;
6418
6419     sge = &fp->rx_sge_chain[index];
6420     sge->addr_hi = htole32(U64_HI(segs[0].ds_addr));
6421     sge->addr_lo = htole32(U64_LO(segs[0].ds_addr));
6422
6423     return (rc);
6424 }
6425
6426 static __noinline int
6427 bxe_alloc_fp_buffers(struct bxe_softc *sc)
6428 {
6429     struct bxe_fastpath *fp;
6430     int i, j, rc = 0;
6431     int ring_prod, cqe_ring_prod;
6432     int max_agg_queues;
6433
6434     for (i = 0; i < sc->num_queues; i++) {
6435         fp = &sc->fp[i];
6436
6437         ring_prod = cqe_ring_prod = 0;
6438         fp->rx_bd_cons = 0;
6439         fp->rx_cq_cons = 0;
6440
6441         /* allocate buffers for the RX BDs in RX BD chain */
6442         for (j = 0; j < sc->max_rx_bufs; j++) {
6443             rc = bxe_alloc_rx_bd_mbuf(fp, ring_prod, ring_prod);
6444             if (rc != 0) {
6445                 BLOGE(sc, "mbuf alloc fail for fp[%02d] rx chain (%d)\n",
6446                       i, rc);
6447                 goto bxe_alloc_fp_buffers_error;
6448             }
6449
6450             ring_prod     = RX_BD_NEXT(ring_prod);
6451             cqe_ring_prod = RCQ_NEXT(cqe_ring_prod);
6452         }
6453
6454         fp->rx_bd_prod = ring_prod;
6455         fp->rx_cq_prod = cqe_ring_prod;
6456         fp->eth_q_stats.rx_calls = fp->eth_q_stats.rx_pkts = 0;
6457
6458         max_agg_queues = MAX_AGG_QS(sc);
6459
6460         fp->tpa_enable = TRUE;
6461
6462         /* fill the TPA pool */
6463         for (j = 0; j < max_agg_queues; j++) {
6464             rc = bxe_alloc_rx_tpa_mbuf(fp, j);
6465             if (rc != 0) {
6466                 BLOGE(sc, "mbuf alloc fail for fp[%02d] TPA queue %d\n",
6467                           i, j);
6468                 fp->tpa_enable = FALSE;
6469                 goto bxe_alloc_fp_buffers_error;
6470             }
6471
6472             fp->rx_tpa_info[j].state = BXE_TPA_STATE_STOP;
6473         }
6474
6475         if (fp->tpa_enable) {
6476             /* fill the RX SGE chain */
6477             ring_prod = 0;
6478             for (j = 0; j < RX_SGE_USABLE; j++) {
6479                 rc = bxe_alloc_rx_sge_mbuf(fp, ring_prod);
6480                 if (rc != 0) {
6481                     BLOGE(sc, "mbuf alloc fail for fp[%02d] SGE %d\n",
6482                               i, ring_prod);
6483                     fp->tpa_enable = FALSE;
6484                     ring_prod = 0;
6485                     goto bxe_alloc_fp_buffers_error;
6486                 }
6487
6488                 ring_prod = RX_SGE_NEXT(ring_prod);
6489             }
6490
6491             fp->rx_sge_prod = ring_prod;
6492         }
6493     }
6494
6495     return (0);
6496
6497 bxe_alloc_fp_buffers_error:
6498
6499     /* unwind what was already allocated */
6500     bxe_free_rx_bd_chain(fp);
6501     bxe_free_tpa_pool(fp);
6502     bxe_free_sge_chain(fp);
6503
6504     return (ENOBUFS);
6505 }
6506
6507 static void
6508 bxe_free_fw_stats_mem(struct bxe_softc *sc)
6509 {
6510     bxe_dma_free(sc, &sc->fw_stats_dma);
6511
6512     sc->fw_stats_num = 0;
6513
6514     sc->fw_stats_req_size = 0;
6515     sc->fw_stats_req = NULL;
6516     sc->fw_stats_req_mapping = 0;
6517
6518     sc->fw_stats_data_size = 0;
6519     sc->fw_stats_data = NULL;
6520     sc->fw_stats_data_mapping = 0;
6521 }
6522
6523 static int
6524 bxe_alloc_fw_stats_mem(struct bxe_softc *sc)
6525 {
6526     uint8_t num_queue_stats;
6527     int num_groups;
6528
6529     /* number of queues for statistics is number of eth queues */
6530     num_queue_stats = BXE_NUM_ETH_QUEUES(sc);
6531
6532     /*
6533      * Total number of FW statistics requests =
6534      *   1 for port stats + 1 for PF stats + num of queues
6535      */
6536     sc->fw_stats_num = (2 + num_queue_stats);
6537
6538     /*
6539      * Request is built from stats_query_header and an array of
6540      * stats_query_cmd_group each of which contains STATS_QUERY_CMD_COUNT
6541      * rules. The real number or requests is configured in the
6542      * stats_query_header.
6543      */
6544     num_groups =
6545         ((sc->fw_stats_num / STATS_QUERY_CMD_COUNT) +
6546          ((sc->fw_stats_num % STATS_QUERY_CMD_COUNT) ? 1 : 0));
6547
6548     BLOGD(sc, DBG_LOAD, "stats fw_stats_num %d num_groups %d\n",
6549           sc->fw_stats_num, num_groups);
6550
6551     sc->fw_stats_req_size =
6552         (sizeof(struct stats_query_header) +
6553          (num_groups * sizeof(struct stats_query_cmd_group)));
6554
6555     /*
6556      * Data for statistics requests + stats_counter.
6557      * stats_counter holds per-STORM counters that are incremented when
6558      * STORM has finished with the current request. Memory for FCoE
6559      * offloaded statistics are counted anyway, even if they will not be sent.
6560      * VF stats are not accounted for here as the data of VF stats is stored
6561      * in memory allocated by the VF, not here.
6562      */
6563     sc->fw_stats_data_size =
6564         (sizeof(struct stats_counter) +
6565          sizeof(struct per_port_stats) +
6566          sizeof(struct per_pf_stats) +
6567          /* sizeof(struct fcoe_statistics_params) + */
6568          (sizeof(struct per_queue_stats) * num_queue_stats));
6569
6570     if (bxe_dma_alloc(sc, (sc->fw_stats_req_size + sc->fw_stats_data_size),
6571                       &sc->fw_stats_dma, "fw stats") != 0) {
6572         bxe_free_fw_stats_mem(sc);
6573         return (-1);
6574     }
6575
6576     /* set up the shortcuts */
6577
6578     sc->fw_stats_req =
6579         (struct bxe_fw_stats_req *)sc->fw_stats_dma.vaddr;
6580     sc->fw_stats_req_mapping = sc->fw_stats_dma.paddr;
6581
6582     sc->fw_stats_data =
6583         (struct bxe_fw_stats_data *)((uint8_t *)sc->fw_stats_dma.vaddr +
6584                                      sc->fw_stats_req_size);
6585     sc->fw_stats_data_mapping = (sc->fw_stats_dma.paddr +
6586                                  sc->fw_stats_req_size);
6587
6588     BLOGD(sc, DBG_LOAD, "statistics request base address set to %#jx\n",
6589           (uintmax_t)sc->fw_stats_req_mapping);
6590
6591     BLOGD(sc, DBG_LOAD, "statistics data base address set to %#jx\n",
6592           (uintmax_t)sc->fw_stats_data_mapping);
6593
6594     return (0);
6595 }
6596
6597 /*
6598  * Bits map:
6599  * 0-7  - Engine0 load counter.
6600  * 8-15 - Engine1 load counter.
6601  * 16   - Engine0 RESET_IN_PROGRESS bit.
6602  * 17   - Engine1 RESET_IN_PROGRESS bit.
6603  * 18   - Engine0 ONE_IS_LOADED. Set when there is at least one active
6604  *        function on the engine
6605  * 19   - Engine1 ONE_IS_LOADED.
6606  * 20   - Chip reset flow bit. When set none-leader must wait for both engines
6607  *        leader to complete (check for both RESET_IN_PROGRESS bits and not
6608  *        for just the one belonging to its engine).
6609  */
6610 #define BXE_RECOVERY_GLOB_REG     MISC_REG_GENERIC_POR_1
6611 #define BXE_PATH0_LOAD_CNT_MASK   0x000000ff
6612 #define BXE_PATH0_LOAD_CNT_SHIFT  0
6613 #define BXE_PATH1_LOAD_CNT_MASK   0x0000ff00
6614 #define BXE_PATH1_LOAD_CNT_SHIFT  8
6615 #define BXE_PATH0_RST_IN_PROG_BIT 0x00010000
6616 #define BXE_PATH1_RST_IN_PROG_BIT 0x00020000
6617 #define BXE_GLOBAL_RESET_BIT      0x00040000
6618
6619 /* set the GLOBAL_RESET bit, should be run under rtnl lock */
6620 static void
6621 bxe_set_reset_global(struct bxe_softc *sc)
6622 {
6623     uint32_t val;
6624     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6625     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6626     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val | BXE_GLOBAL_RESET_BIT);
6627     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6628 }
6629
6630 /* clear the GLOBAL_RESET bit, should be run under rtnl lock */
6631 static void
6632 bxe_clear_reset_global(struct bxe_softc *sc)
6633 {
6634     uint32_t val;
6635     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6636     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6637     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val & (~BXE_GLOBAL_RESET_BIT));
6638     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6639 }
6640
6641 /* checks the GLOBAL_RESET bit, should be run under rtnl lock */
6642 static uint8_t
6643 bxe_reset_is_global(struct bxe_softc *sc)
6644 {
6645     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6646     BLOGD(sc, DBG_LOAD, "GLOB_REG=0x%08x\n", val);
6647     return (val & BXE_GLOBAL_RESET_BIT) ? TRUE : FALSE;
6648 }
6649
6650 /* clear RESET_IN_PROGRESS bit for the engine, should be run under rtnl lock */
6651 static void
6652 bxe_set_reset_done(struct bxe_softc *sc)
6653 {
6654     uint32_t val;
6655     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6656                                  BXE_PATH0_RST_IN_PROG_BIT;
6657
6658     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6659
6660     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6661     /* Clear the bit */
6662     val &= ~bit;
6663     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6664
6665     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6666 }
6667
6668 /* set RESET_IN_PROGRESS for the engine, should be run under rtnl lock */
6669 static void
6670 bxe_set_reset_in_progress(struct bxe_softc *sc)
6671 {
6672     uint32_t val;
6673     uint32_t bit = SC_PATH(sc) ? BXE_PATH1_RST_IN_PROG_BIT :
6674                                  BXE_PATH0_RST_IN_PROG_BIT;
6675
6676     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6677
6678     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6679     /* Set the bit */
6680     val |= bit;
6681     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6682
6683     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6684 }
6685
6686 /* check RESET_IN_PROGRESS bit for an engine, should be run under rtnl lock */
6687 static uint8_t
6688 bxe_reset_is_done(struct bxe_softc *sc,
6689                   int              engine)
6690 {
6691     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6692     uint32_t bit = engine ? BXE_PATH1_RST_IN_PROG_BIT :
6693                             BXE_PATH0_RST_IN_PROG_BIT;
6694
6695     /* return false if bit is set */
6696     return (val & bit) ? FALSE : TRUE;
6697 }
6698
6699 /* get the load status for an engine, should be run under rtnl lock */
6700 static uint8_t
6701 bxe_get_load_status(struct bxe_softc *sc,
6702                     int              engine)
6703 {
6704     uint32_t mask = engine ? BXE_PATH1_LOAD_CNT_MASK :
6705                              BXE_PATH0_LOAD_CNT_MASK;
6706     uint32_t shift = engine ? BXE_PATH1_LOAD_CNT_SHIFT :
6707                               BXE_PATH0_LOAD_CNT_SHIFT;
6708     uint32_t val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6709
6710     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6711
6712     val = ((val & mask) >> shift);
6713
6714     BLOGD(sc, DBG_LOAD, "Load mask engine %d = 0x%08x\n", engine, val);
6715
6716     return (val != 0);
6717 }
6718
6719 /* set pf load mark */
6720 /* XXX needs to be under rtnl lock */
6721 static void
6722 bxe_set_pf_load(struct bxe_softc *sc)
6723 {
6724     uint32_t val;
6725     uint32_t val1;
6726     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6727                                   BXE_PATH0_LOAD_CNT_MASK;
6728     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6729                                    BXE_PATH0_LOAD_CNT_SHIFT;
6730
6731     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6732
6733     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6734     BLOGD(sc, DBG_LOAD, "Old value for GLOB_REG=0x%08x\n", val);
6735
6736     /* get the current counter value */
6737     val1 = ((val & mask) >> shift);
6738
6739     /* set bit of this PF */
6740     val1 |= (1 << SC_ABS_FUNC(sc));
6741
6742     /* clear the old value */
6743     val &= ~mask;
6744
6745     /* set the new one */
6746     val |= ((val1 << shift) & mask);
6747
6748     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6749
6750     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6751 }
6752
6753 /* clear pf load mark */
6754 /* XXX needs to be under rtnl lock */
6755 static uint8_t
6756 bxe_clear_pf_load(struct bxe_softc *sc)
6757 {
6758     uint32_t val1, val;
6759     uint32_t mask = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_MASK :
6760                                   BXE_PATH0_LOAD_CNT_MASK;
6761     uint32_t shift = SC_PATH(sc) ? BXE_PATH1_LOAD_CNT_SHIFT :
6762                                    BXE_PATH0_LOAD_CNT_SHIFT;
6763
6764     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6765     val = REG_RD(sc, BXE_RECOVERY_GLOB_REG);
6766     BLOGD(sc, DBG_LOAD, "Old GEN_REG_VAL=0x%08x\n", val);
6767
6768     /* get the current counter value */
6769     val1 = (val & mask) >> shift;
6770
6771     /* clear bit of that PF */
6772     val1 &= ~(1 << SC_ABS_FUNC(sc));
6773
6774     /* clear the old value */
6775     val &= ~mask;
6776
6777     /* set the new one */
6778     val |= ((val1 << shift) & mask);
6779
6780     REG_WR(sc, BXE_RECOVERY_GLOB_REG, val);
6781     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RECOVERY_REG);
6782     return (val1 != 0);
6783 }
6784
6785 /* send load requrest to mcp and analyze response */
6786 static int
6787 bxe_nic_load_request(struct bxe_softc *sc,
6788                      uint32_t         *load_code)
6789 {
6790     /* init fw_seq */
6791     sc->fw_seq =
6792         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
6793          DRV_MSG_SEQ_NUMBER_MASK);
6794
6795     BLOGD(sc, DBG_LOAD, "initial fw_seq 0x%04x\n", sc->fw_seq);
6796
6797     /* get the current FW pulse sequence */
6798     sc->fw_drv_pulse_wr_seq =
6799         (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_pulse_mb) &
6800          DRV_PULSE_SEQ_MASK);
6801
6802     BLOGD(sc, DBG_LOAD, "initial drv_pulse 0x%04x\n",
6803           sc->fw_drv_pulse_wr_seq);
6804
6805     /* load request */
6806     (*load_code) = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
6807                                   DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
6808
6809     /* if the MCP fails to respond we must abort */
6810     if (!(*load_code)) {
6811         BLOGE(sc, "MCP response failure!\n");
6812         return (-1);
6813     }
6814
6815     /* if MCP refused then must abort */
6816     if ((*load_code) == FW_MSG_CODE_DRV_LOAD_REFUSED) {
6817         BLOGE(sc, "MCP refused load request\n");
6818         return (-1);
6819     }
6820
6821     return (0);
6822 }
6823
6824 /*
6825  * Check whether another PF has already loaded FW to chip. In virtualized
6826  * environments a pf from anoth VM may have already initialized the device
6827  * including loading FW.
6828  */
6829 static int
6830 bxe_nic_load_analyze_req(struct bxe_softc *sc,
6831                          uint32_t         load_code)
6832 {
6833     uint32_t my_fw, loaded_fw;
6834
6835     /* is another pf loaded on this engine? */
6836     if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
6837         (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
6838         /* build my FW version dword */
6839         my_fw = (BCM_5710_FW_MAJOR_VERSION +
6840                  (BCM_5710_FW_MINOR_VERSION << 8 ) +
6841                  (BCM_5710_FW_REVISION_VERSION << 16) +
6842                  (BCM_5710_FW_ENGINEERING_VERSION << 24));
6843
6844         /* read loaded FW from chip */
6845         loaded_fw = REG_RD(sc, XSEM_REG_PRAM);
6846         BLOGD(sc, DBG_LOAD, "loaded FW 0x%08x / my FW 0x%08x\n",
6847               loaded_fw, my_fw);
6848
6849         /* abort nic load if version mismatch */
6850         if (my_fw != loaded_fw) {
6851             BLOGE(sc, "FW 0x%08x already loaded (mine is 0x%08x)",
6852                   loaded_fw, my_fw);
6853             return (-1);
6854         }
6855     }
6856
6857     return (0);
6858 }
6859
6860 /* mark PMF if applicable */
6861 static void
6862 bxe_nic_load_pmf(struct bxe_softc *sc,
6863                  uint32_t         load_code)
6864 {
6865     uint32_t ncsi_oem_data_addr;
6866
6867     if ((load_code == FW_MSG_CODE_DRV_LOAD_COMMON) ||
6868         (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) ||
6869         (load_code == FW_MSG_CODE_DRV_LOAD_PORT)) {
6870         /*
6871          * Barrier here for ordering between the writing to sc->port.pmf here
6872          * and reading it from the periodic task.
6873          */
6874         sc->port.pmf = 1;
6875         mb();
6876     } else {
6877         sc->port.pmf = 0;
6878     }
6879
6880     BLOGD(sc, DBG_LOAD, "pmf %d\n", sc->port.pmf);
6881
6882     /* XXX needed? */
6883     if (load_code == FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) {
6884         if (SHMEM2_HAS(sc, ncsi_oem_data_addr)) {
6885             ncsi_oem_data_addr = SHMEM2_RD(sc, ncsi_oem_data_addr);
6886             if (ncsi_oem_data_addr) {
6887                 REG_WR(sc,
6888                        (ncsi_oem_data_addr +
6889                         offsetof(struct glob_ncsi_oem_data, driver_version)),
6890                        0);
6891             }
6892         }
6893     }
6894 }
6895
6896 static void
6897 bxe_read_mf_cfg(struct bxe_softc *sc)
6898 {
6899     int n = (CHIP_IS_MODE_4_PORT(sc) ? 2 : 1);
6900     int abs_func;
6901     int vn;
6902
6903     if (BXE_NOMCP(sc)) {
6904         return; /* what should be the default bvalue in this case */
6905     }
6906
6907     /*
6908      * The formula for computing the absolute function number is...
6909      * For 2 port configuration (4 functions per port):
6910      *   abs_func = 2 * vn + SC_PORT + SC_PATH
6911      * For 4 port configuration (2 functions per port):
6912      *   abs_func = 4 * vn + 2 * SC_PORT + SC_PATH
6913      */
6914     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
6915         abs_func = (n * (2 * vn + SC_PORT(sc)) + SC_PATH(sc));
6916         if (abs_func >= E1H_FUNC_MAX) {
6917             break;
6918         }
6919         sc->devinfo.mf_info.mf_config[vn] =
6920             MFCFG_RD(sc, func_mf_config[abs_func].config);
6921     }
6922
6923     if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] &
6924         FUNC_MF_CFG_FUNC_DISABLED) {
6925         BLOGD(sc, DBG_LOAD, "mf_cfg function disabled\n");
6926         sc->flags |= BXE_MF_FUNC_DIS;
6927     } else {
6928         BLOGD(sc, DBG_LOAD, "mf_cfg function enabled\n");
6929         sc->flags &= ~BXE_MF_FUNC_DIS;
6930     }
6931 }
6932
6933 /* acquire split MCP access lock register */
6934 static int bxe_acquire_alr(struct bxe_softc *sc)
6935 {
6936     uint32_t j, val;
6937
6938     for (j = 0; j < 1000; j++) {
6939         val = (1UL << 31);
6940         REG_WR(sc, GRCBASE_MCP + 0x9c, val);
6941         val = REG_RD(sc, GRCBASE_MCP + 0x9c);
6942         if (val & (1L << 31))
6943             break;
6944
6945         DELAY(5000);
6946     }
6947
6948     if (!(val & (1L << 31))) {
6949         BLOGE(sc, "Cannot acquire MCP access lock register\n");
6950         return (-1);
6951     }
6952
6953     return (0);
6954 }
6955
6956 /* release split MCP access lock register */
6957 static void bxe_release_alr(struct bxe_softc *sc)
6958 {
6959     REG_WR(sc, GRCBASE_MCP + 0x9c, 0);
6960 }
6961
6962 static void
6963 bxe_fan_failure(struct bxe_softc *sc)
6964 {
6965     int port = SC_PORT(sc);
6966     uint32_t ext_phy_config;
6967
6968     /* mark the failure */
6969     ext_phy_config =
6970         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
6971
6972     ext_phy_config &= ~PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK;
6973     ext_phy_config |= PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE;
6974     SHMEM_WR(sc, dev_info.port_hw_config[port].external_phy_config,
6975              ext_phy_config);
6976
6977     /* log the failure */
6978     BLOGW(sc, "Fan Failure has caused the driver to shutdown "
6979               "the card to prevent permanent damage. "
6980               "Please contact OEM Support for assistance\n");
6981
6982     /* XXX */
6983 #if 1
6984     bxe_panic(sc, ("Schedule task to handle fan failure\n"));
6985 #else
6986     /*
6987      * Schedule device reset (unload)
6988      * This is due to some boards consuming sufficient power when driver is
6989      * up to overheat if fan fails.
6990      */
6991     bxe_set_bit(BXE_SP_RTNL_FAN_FAILURE, &sc->sp_rtnl_state);
6992     schedule_delayed_work(&sc->sp_rtnl_task, 0);
6993 #endif
6994 }
6995
6996 /* this function is called upon a link interrupt */
6997 static void
6998 bxe_link_attn(struct bxe_softc *sc)
6999 {
7000     uint32_t pause_enabled = 0;
7001     struct host_port_stats *pstats;
7002     int cmng_fns;
7003     struct bxe_fastpath *fp;
7004     int i;
7005
7006     /* Make sure that we are synced with the current statistics */
7007     bxe_stats_handle(sc, STATS_EVENT_STOP);
7008
7009     elink_link_update(&sc->link_params, &sc->link_vars);
7010
7011     if (sc->link_vars.link_up) {
7012
7013         /* dropless flow control */
7014         if (!CHIP_IS_E1(sc) && sc->dropless_fc) {
7015             pause_enabled = 0;
7016
7017             if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
7018                 pause_enabled = 1;
7019             }
7020
7021             REG_WR(sc,
7022                    (BAR_USTRORM_INTMEM +
7023                     USTORM_ETH_PAUSE_ENABLED_OFFSET(SC_PORT(sc))),
7024                    pause_enabled);
7025         }
7026
7027         if (sc->link_vars.mac_type != ELINK_MAC_TYPE_EMAC) {
7028             pstats = BXE_SP(sc, port_stats);
7029             /* reset old mac stats */
7030             memset(&(pstats->mac_stx[0]), 0, sizeof(struct mac_stx));
7031         }
7032
7033         if (sc->state == BXE_STATE_OPEN) {
7034             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
7035         }
7036
7037         /* Restart tx when the link comes back. */
7038         FOR_EACH_ETH_QUEUE(sc, i) {
7039             fp = &sc->fp[i];
7040             taskqueue_enqueue(fp->tq, &fp->tx_task);
7041         }
7042     }
7043
7044     if (sc->link_vars.link_up && sc->link_vars.line_speed) {
7045         cmng_fns = bxe_get_cmng_fns_mode(sc);
7046
7047         if (cmng_fns != CMNG_FNS_NONE) {
7048             bxe_cmng_fns_init(sc, FALSE, cmng_fns);
7049             storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7050         } else {
7051             /* rate shaping and fairness are disabled */
7052             BLOGD(sc, DBG_LOAD, "single function mode without fairness\n");
7053         }
7054     }
7055
7056     bxe_link_report_locked(sc);
7057
7058     if (IS_MF(sc)) {
7059         ; // XXX bxe_link_sync_notify(sc);
7060     }
7061 }
7062
7063 static void
7064 bxe_attn_int_asserted(struct bxe_softc *sc,
7065                       uint32_t         asserted)
7066 {
7067     int port = SC_PORT(sc);
7068     uint32_t aeu_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
7069                                MISC_REG_AEU_MASK_ATTN_FUNC_0;
7070     uint32_t nig_int_mask_addr = port ? NIG_REG_MASK_INTERRUPT_PORT1 :
7071                                         NIG_REG_MASK_INTERRUPT_PORT0;
7072     uint32_t aeu_mask;
7073     uint32_t nig_mask = 0;
7074     uint32_t reg_addr;
7075     uint32_t igu_acked;
7076     uint32_t cnt;
7077
7078     if (sc->attn_state & asserted) {
7079         BLOGE(sc, "IGU ERROR attn=0x%08x\n", asserted);
7080     }
7081
7082     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7083
7084     aeu_mask = REG_RD(sc, aeu_addr);
7085
7086     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly asserted 0x%08x\n",
7087           aeu_mask, asserted);
7088
7089     aeu_mask &= ~(asserted & 0x3ff);
7090
7091     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
7092
7093     REG_WR(sc, aeu_addr, aeu_mask);
7094
7095     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
7096
7097     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
7098     sc->attn_state |= asserted;
7099     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
7100
7101     if (asserted & ATTN_HARD_WIRED_MASK) {
7102         if (asserted & ATTN_NIG_FOR_FUNC) {
7103
7104             bxe_acquire_phy_lock(sc);
7105             /* save nig interrupt mask */
7106             nig_mask = REG_RD(sc, nig_int_mask_addr);
7107
7108             /* If nig_mask is not set, no need to call the update function */
7109             if (nig_mask) {
7110                 REG_WR(sc, nig_int_mask_addr, 0);
7111
7112                 bxe_link_attn(sc);
7113             }
7114
7115             /* handle unicore attn? */
7116         }
7117
7118         if (asserted & ATTN_SW_TIMER_4_FUNC) {
7119             BLOGD(sc, DBG_INTR, "ATTN_SW_TIMER_4_FUNC!\n");
7120         }
7121
7122         if (asserted & GPIO_2_FUNC) {
7123             BLOGD(sc, DBG_INTR, "GPIO_2_FUNC!\n");
7124         }
7125
7126         if (asserted & GPIO_3_FUNC) {
7127             BLOGD(sc, DBG_INTR, "GPIO_3_FUNC!\n");
7128         }
7129
7130         if (asserted & GPIO_4_FUNC) {
7131             BLOGD(sc, DBG_INTR, "GPIO_4_FUNC!\n");
7132         }
7133
7134         if (port == 0) {
7135             if (asserted & ATTN_GENERAL_ATTN_1) {
7136                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_1!\n");
7137                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_1, 0x0);
7138             }
7139             if (asserted & ATTN_GENERAL_ATTN_2) {
7140                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_2!\n");
7141                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_2, 0x0);
7142             }
7143             if (asserted & ATTN_GENERAL_ATTN_3) {
7144                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_3!\n");
7145                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_3, 0x0);
7146             }
7147         } else {
7148             if (asserted & ATTN_GENERAL_ATTN_4) {
7149                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_4!\n");
7150                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_4, 0x0);
7151             }
7152             if (asserted & ATTN_GENERAL_ATTN_5) {
7153                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_5!\n");
7154                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_5, 0x0);
7155             }
7156             if (asserted & ATTN_GENERAL_ATTN_6) {
7157                 BLOGD(sc, DBG_INTR, "ATTN_GENERAL_ATTN_6!\n");
7158                 REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_6, 0x0);
7159             }
7160         }
7161     } /* hardwired */
7162
7163     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7164         reg_addr = (HC_REG_COMMAND_REG + port*32 + COMMAND_REG_ATTN_BITS_SET);
7165     } else {
7166         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_SET_UPPER*8);
7167     }
7168
7169     BLOGD(sc, DBG_INTR, "about to mask 0x%08x at %s addr 0x%08x\n",
7170           asserted,
7171           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
7172     REG_WR(sc, reg_addr, asserted);
7173
7174     /* now set back the mask */
7175     if (asserted & ATTN_NIG_FOR_FUNC) {
7176         /*
7177          * Verify that IGU ack through BAR was written before restoring
7178          * NIG mask. This loop should exit after 2-3 iterations max.
7179          */
7180         if (sc->devinfo.int_block != INT_BLOCK_HC) {
7181             cnt = 0;
7182
7183             do {
7184                 igu_acked = REG_RD(sc, IGU_REG_ATTENTION_ACK_BITS);
7185             } while (((igu_acked & ATTN_NIG_FOR_FUNC) == 0) &&
7186                      (++cnt < MAX_IGU_ATTN_ACK_TO));
7187
7188             if (!igu_acked) {
7189                 BLOGE(sc, "Failed to verify IGU ack on time\n");
7190             }
7191
7192             mb();
7193         }
7194
7195         REG_WR(sc, nig_int_mask_addr, nig_mask);
7196
7197         bxe_release_phy_lock(sc);
7198     }
7199 }
7200
7201 static void
7202 bxe_print_next_block(struct bxe_softc *sc,
7203                      int              idx,
7204                      const char       *blk)
7205 {
7206     BLOGI(sc, "%s%s", idx ? ", " : "", blk);
7207 }
7208
7209 static int
7210 bxe_check_blocks_with_parity0(struct bxe_softc *sc,
7211                               uint32_t         sig,
7212                               int              par_num,
7213                               uint8_t          print)
7214 {
7215     uint32_t cur_bit = 0;
7216     int i = 0;
7217
7218     for (i = 0; sig; i++) {
7219         cur_bit = ((uint32_t)0x1 << i);
7220         if (sig & cur_bit) {
7221             switch (cur_bit) {
7222             case AEU_INPUTS_ATTN_BITS_BRB_PARITY_ERROR:
7223                 if (print)
7224                     bxe_print_next_block(sc, par_num++, "BRB");
7225                 break;
7226             case AEU_INPUTS_ATTN_BITS_PARSER_PARITY_ERROR:
7227                 if (print)
7228                     bxe_print_next_block(sc, par_num++, "PARSER");
7229                 break;
7230             case AEU_INPUTS_ATTN_BITS_TSDM_PARITY_ERROR:
7231                 if (print)
7232                     bxe_print_next_block(sc, par_num++, "TSDM");
7233                 break;
7234             case AEU_INPUTS_ATTN_BITS_SEARCHER_PARITY_ERROR:
7235                 if (print)
7236                     bxe_print_next_block(sc, par_num++, "SEARCHER");
7237                 break;
7238             case AEU_INPUTS_ATTN_BITS_TCM_PARITY_ERROR:
7239                 if (print)
7240                     bxe_print_next_block(sc, par_num++, "TCM");
7241                 break;
7242             case AEU_INPUTS_ATTN_BITS_TSEMI_PARITY_ERROR:
7243                 if (print)
7244                     bxe_print_next_block(sc, par_num++, "TSEMI");
7245                 break;
7246             case AEU_INPUTS_ATTN_BITS_PBCLIENT_PARITY_ERROR:
7247                 if (print)
7248                     bxe_print_next_block(sc, par_num++, "XPB");
7249                 break;
7250             }
7251
7252             /* Clear the bit */
7253             sig &= ~cur_bit;
7254         }
7255     }
7256
7257     return (par_num);
7258 }
7259
7260 static int
7261 bxe_check_blocks_with_parity1(struct bxe_softc *sc,
7262                               uint32_t         sig,
7263                               int              par_num,
7264                               uint8_t          *global,
7265                               uint8_t          print)
7266 {
7267     int i = 0;
7268     uint32_t cur_bit = 0;
7269     for (i = 0; sig; i++) {
7270         cur_bit = ((uint32_t)0x1 << i);
7271         if (sig & cur_bit) {
7272             switch (cur_bit) {
7273             case AEU_INPUTS_ATTN_BITS_PBF_PARITY_ERROR:
7274                 if (print)
7275                     bxe_print_next_block(sc, par_num++, "PBF");
7276                 break;
7277             case AEU_INPUTS_ATTN_BITS_QM_PARITY_ERROR:
7278                 if (print)
7279                     bxe_print_next_block(sc, par_num++, "QM");
7280                 break;
7281             case AEU_INPUTS_ATTN_BITS_TIMERS_PARITY_ERROR:
7282                 if (print)
7283                     bxe_print_next_block(sc, par_num++, "TM");
7284                 break;
7285             case AEU_INPUTS_ATTN_BITS_XSDM_PARITY_ERROR:
7286                 if (print)
7287                     bxe_print_next_block(sc, par_num++, "XSDM");
7288                 break;
7289             case AEU_INPUTS_ATTN_BITS_XCM_PARITY_ERROR:
7290                 if (print)
7291                     bxe_print_next_block(sc, par_num++, "XCM");
7292                 break;
7293             case AEU_INPUTS_ATTN_BITS_XSEMI_PARITY_ERROR:
7294                 if (print)
7295                     bxe_print_next_block(sc, par_num++, "XSEMI");
7296                 break;
7297             case AEU_INPUTS_ATTN_BITS_DOORBELLQ_PARITY_ERROR:
7298                 if (print)
7299                     bxe_print_next_block(sc, par_num++, "DOORBELLQ");
7300                 break;
7301             case AEU_INPUTS_ATTN_BITS_NIG_PARITY_ERROR:
7302                 if (print)
7303                     bxe_print_next_block(sc, par_num++, "NIG");
7304                 break;
7305             case AEU_INPUTS_ATTN_BITS_VAUX_PCI_CORE_PARITY_ERROR:
7306                 if (print)
7307                     bxe_print_next_block(sc, par_num++, "VAUX PCI CORE");
7308                 *global = TRUE;
7309                 break;
7310             case AEU_INPUTS_ATTN_BITS_DEBUG_PARITY_ERROR:
7311                 if (print)
7312                     bxe_print_next_block(sc, par_num++, "DEBUG");
7313                 break;
7314             case AEU_INPUTS_ATTN_BITS_USDM_PARITY_ERROR:
7315                 if (print)
7316                     bxe_print_next_block(sc, par_num++, "USDM");
7317                 break;
7318             case AEU_INPUTS_ATTN_BITS_UCM_PARITY_ERROR:
7319                 if (print)
7320                     bxe_print_next_block(sc, par_num++, "UCM");
7321                 break;
7322             case AEU_INPUTS_ATTN_BITS_USEMI_PARITY_ERROR:
7323                 if (print)
7324                     bxe_print_next_block(sc, par_num++, "USEMI");
7325                 break;
7326             case AEU_INPUTS_ATTN_BITS_UPB_PARITY_ERROR:
7327                 if (print)
7328                     bxe_print_next_block(sc, par_num++, "UPB");
7329                 break;
7330             case AEU_INPUTS_ATTN_BITS_CSDM_PARITY_ERROR:
7331                 if (print)
7332                     bxe_print_next_block(sc, par_num++, "CSDM");
7333                 break;
7334             case AEU_INPUTS_ATTN_BITS_CCM_PARITY_ERROR:
7335                 if (print)
7336                     bxe_print_next_block(sc, par_num++, "CCM");
7337                 break;
7338             }
7339
7340             /* Clear the bit */
7341             sig &= ~cur_bit;
7342         }
7343     }
7344
7345     return (par_num);
7346 }
7347
7348 static int
7349 bxe_check_blocks_with_parity2(struct bxe_softc *sc,
7350                               uint32_t         sig,
7351                               int              par_num,
7352                               uint8_t          print)
7353 {
7354     uint32_t cur_bit = 0;
7355     int i = 0;
7356
7357     for (i = 0; sig; i++) {
7358         cur_bit = ((uint32_t)0x1 << i);
7359         if (sig & cur_bit) {
7360             switch (cur_bit) {
7361             case AEU_INPUTS_ATTN_BITS_CSEMI_PARITY_ERROR:
7362                 if (print)
7363                     bxe_print_next_block(sc, par_num++, "CSEMI");
7364                 break;
7365             case AEU_INPUTS_ATTN_BITS_PXP_PARITY_ERROR:
7366                 if (print)
7367                     bxe_print_next_block(sc, par_num++, "PXP");
7368                 break;
7369             case AEU_IN_ATTN_BITS_PXPPCICLOCKCLIENT_PARITY_ERROR:
7370                 if (print)
7371                     bxe_print_next_block(sc, par_num++, "PXPPCICLOCKCLIENT");
7372                 break;
7373             case AEU_INPUTS_ATTN_BITS_CFC_PARITY_ERROR:
7374                 if (print)
7375                     bxe_print_next_block(sc, par_num++, "CFC");
7376                 break;
7377             case AEU_INPUTS_ATTN_BITS_CDU_PARITY_ERROR:
7378                 if (print)
7379                     bxe_print_next_block(sc, par_num++, "CDU");
7380                 break;
7381             case AEU_INPUTS_ATTN_BITS_DMAE_PARITY_ERROR:
7382                 if (print)
7383                     bxe_print_next_block(sc, par_num++, "DMAE");
7384                 break;
7385             case AEU_INPUTS_ATTN_BITS_IGU_PARITY_ERROR:
7386                 if (print)
7387                     bxe_print_next_block(sc, par_num++, "IGU");
7388                 break;
7389             case AEU_INPUTS_ATTN_BITS_MISC_PARITY_ERROR:
7390                 if (print)
7391                     bxe_print_next_block(sc, par_num++, "MISC");
7392                 break;
7393             }
7394
7395             /* Clear the bit */
7396             sig &= ~cur_bit;
7397         }
7398     }
7399
7400     return (par_num);
7401 }
7402
7403 static int
7404 bxe_check_blocks_with_parity3(struct bxe_softc *sc,
7405                               uint32_t         sig,
7406                               int              par_num,
7407                               uint8_t          *global,
7408                               uint8_t          print)
7409 {
7410     uint32_t cur_bit = 0;
7411     int i = 0;
7412
7413     for (i = 0; sig; i++) {
7414         cur_bit = ((uint32_t)0x1 << i);
7415         if (sig & cur_bit) {
7416             switch (cur_bit) {
7417             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_ROM_PARITY:
7418                 if (print)
7419                     bxe_print_next_block(sc, par_num++, "MCP ROM");
7420                 *global = TRUE;
7421                 break;
7422             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_RX_PARITY:
7423                 if (print)
7424                     bxe_print_next_block(sc, par_num++,
7425                               "MCP UMP RX");
7426                 *global = TRUE;
7427                 break;
7428             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_UMP_TX_PARITY:
7429                 if (print)
7430                     bxe_print_next_block(sc, par_num++,
7431                               "MCP UMP TX");
7432                 *global = TRUE;
7433                 break;
7434             case AEU_INPUTS_ATTN_BITS_MCP_LATCHED_SCPAD_PARITY:
7435                 if (print)
7436                     bxe_print_next_block(sc, par_num++,
7437                               "MCP SCPAD");
7438                 *global = TRUE;
7439                 break;
7440             }
7441
7442             /* Clear the bit */
7443             sig &= ~cur_bit;
7444         }
7445     }
7446
7447     return (par_num);
7448 }
7449
7450 static int
7451 bxe_check_blocks_with_parity4(struct bxe_softc *sc,
7452                               uint32_t         sig,
7453                               int              par_num,
7454                               uint8_t          print)
7455 {
7456     uint32_t cur_bit = 0;
7457     int i = 0;
7458
7459     for (i = 0; sig; i++) {
7460         cur_bit = ((uint32_t)0x1 << i);
7461         if (sig & cur_bit) {
7462             switch (cur_bit) {
7463             case AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR:
7464                 if (print)
7465                     bxe_print_next_block(sc, par_num++, "PGLUE_B");
7466                 break;
7467             case AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR:
7468                 if (print)
7469                     bxe_print_next_block(sc, par_num++, "ATC");
7470                 break;
7471             }
7472
7473             /* Clear the bit */
7474             sig &= ~cur_bit;
7475         }
7476     }
7477
7478     return (par_num);
7479 }
7480
7481 static uint8_t
7482 bxe_parity_attn(struct bxe_softc *sc,
7483                 uint8_t          *global,
7484                 uint8_t          print,
7485                 uint32_t         *sig)
7486 {
7487     int par_num = 0;
7488
7489     if ((sig[0] & HW_PRTY_ASSERT_SET_0) ||
7490         (sig[1] & HW_PRTY_ASSERT_SET_1) ||
7491         (sig[2] & HW_PRTY_ASSERT_SET_2) ||
7492         (sig[3] & HW_PRTY_ASSERT_SET_3) ||
7493         (sig[4] & HW_PRTY_ASSERT_SET_4)) {
7494         BLOGE(sc, "Parity error: HW block parity attention:\n"
7495                   "[0]:0x%08x [1]:0x%08x [2]:0x%08x [3]:0x%08x [4]:0x%08x\n",
7496               (uint32_t)(sig[0] & HW_PRTY_ASSERT_SET_0),
7497               (uint32_t)(sig[1] & HW_PRTY_ASSERT_SET_1),
7498               (uint32_t)(sig[2] & HW_PRTY_ASSERT_SET_2),
7499               (uint32_t)(sig[3] & HW_PRTY_ASSERT_SET_3),
7500               (uint32_t)(sig[4] & HW_PRTY_ASSERT_SET_4));
7501
7502         if (print)
7503             BLOGI(sc, "Parity errors detected in blocks: ");
7504
7505         par_num =
7506             bxe_check_blocks_with_parity0(sc, sig[0] &
7507                                           HW_PRTY_ASSERT_SET_0,
7508                                           par_num, print);
7509         par_num =
7510             bxe_check_blocks_with_parity1(sc, sig[1] &
7511                                           HW_PRTY_ASSERT_SET_1,
7512                                           par_num, global, print);
7513         par_num =
7514             bxe_check_blocks_with_parity2(sc, sig[2] &
7515                                           HW_PRTY_ASSERT_SET_2,
7516                                           par_num, print);
7517         par_num =
7518             bxe_check_blocks_with_parity3(sc, sig[3] &
7519                                           HW_PRTY_ASSERT_SET_3,
7520                                           par_num, global, print);
7521         par_num =
7522             bxe_check_blocks_with_parity4(sc, sig[4] &
7523                                           HW_PRTY_ASSERT_SET_4,
7524                                           par_num, print);
7525
7526         if (print)
7527             BLOGI(sc, "\n");
7528
7529         return (TRUE);
7530     }
7531
7532     return (FALSE);
7533 }
7534
7535 static uint8_t
7536 bxe_chk_parity_attn(struct bxe_softc *sc,
7537                     uint8_t          *global,
7538                     uint8_t          print)
7539 {
7540     struct attn_route attn = { {0} };
7541     int port = SC_PORT(sc);
7542
7543     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
7544     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
7545     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
7546     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
7547
7548     /*
7549      * Since MCP attentions can't be disabled inside the block, we need to
7550      * read AEU registers to see whether they're currently disabled
7551      */
7552     attn.sig[3] &= ((REG_RD(sc, (!port ? MISC_REG_AEU_ENABLE4_FUNC_0_OUT_0
7553                                       : MISC_REG_AEU_ENABLE4_FUNC_1_OUT_0)) &
7554                          MISC_AEU_ENABLE_MCP_PRTY_BITS) |
7555                         ~MISC_AEU_ENABLE_MCP_PRTY_BITS);
7556
7557
7558     if (!CHIP_IS_E1x(sc))
7559         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
7560
7561     return (bxe_parity_attn(sc, global, print, attn.sig));
7562 }
7563
7564 static void
7565 bxe_attn_int_deasserted4(struct bxe_softc *sc,
7566                          uint32_t         attn)
7567 {
7568     uint32_t val;
7569
7570     if (attn & AEU_INPUTS_ATTN_BITS_PGLUE_HW_INTERRUPT) {
7571         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS_CLR);
7572         BLOGE(sc, "PGLUE hw attention 0x%08x\n", val);
7573         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR)
7574             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_ADDRESS_ERROR\n");
7575         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR)
7576             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_INCORRECT_RCV_BEHAVIOR\n");
7577         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN)
7578             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN\n");
7579         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN)
7580             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_LENGTH_VIOLATION_ATTN\n");
7581         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN)
7582             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_GRC_SPACE_VIOLATION_ATTN\n");
7583         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN)
7584             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_VF_MSIX_BAR_VIOLATION_ATTN\n");
7585         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN)
7586             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_ERROR_ATTN\n");
7587         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN)
7588             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_TCPL_IN_TWO_RCBS_ATTN\n");
7589         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW)
7590             BLOGE(sc, "PGLUE_B_PGLUE_B_INT_STS_REG_CSSNOOP_FIFO_OVERFLOW\n");
7591     }
7592
7593     if (attn & AEU_INPUTS_ATTN_BITS_ATC_HW_INTERRUPT) {
7594         val = REG_RD(sc, ATC_REG_ATC_INT_STS_CLR);
7595         BLOGE(sc, "ATC hw attention 0x%08x\n", val);
7596         if (val & ATC_ATC_INT_STS_REG_ADDRESS_ERROR)
7597             BLOGE(sc, "ATC_ATC_INT_STS_REG_ADDRESS_ERROR\n");
7598         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND)
7599             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_TO_NOT_PEND\n");
7600         if (val & ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS)
7601             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_GPA_MULTIPLE_HITS\n");
7602         if (val & ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT)
7603             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_RCPL_TO_EMPTY_CNT\n");
7604         if (val & ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR)
7605             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_TCPL_ERROR\n");
7606         if (val & ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU)
7607             BLOGE(sc, "ATC_ATC_INT_STS_REG_ATC_IREQ_LESS_THAN_STU\n");
7608     }
7609
7610     if (attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7611                 AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)) {
7612         BLOGE(sc, "FATAL parity attention set4 0x%08x\n",
7613               (uint32_t)(attn & (AEU_INPUTS_ATTN_BITS_PGLUE_PARITY_ERROR |
7614                                  AEU_INPUTS_ATTN_BITS_ATC_PARITY_ERROR)));
7615     }
7616 }
7617
7618 static void
7619 bxe_e1h_disable(struct bxe_softc *sc)
7620 {
7621     int port = SC_PORT(sc);
7622
7623     bxe_tx_disable(sc);
7624
7625     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 0);
7626 }
7627
7628 static void
7629 bxe_e1h_enable(struct bxe_softc *sc)
7630 {
7631     int port = SC_PORT(sc);
7632
7633     REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
7634
7635     // XXX bxe_tx_enable(sc);
7636 }
7637
7638 /*
7639  * called due to MCP event (on pmf):
7640  *   reread new bandwidth configuration
7641  *   configure FW
7642  *   notify others function about the change
7643  */
7644 static void
7645 bxe_config_mf_bw(struct bxe_softc *sc)
7646 {
7647     if (sc->link_vars.link_up) {
7648         bxe_cmng_fns_init(sc, TRUE, CMNG_FNS_MINMAX);
7649         // XXX bxe_link_sync_notify(sc);
7650     }
7651
7652     storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
7653 }
7654
7655 static void
7656 bxe_set_mf_bw(struct bxe_softc *sc)
7657 {
7658     bxe_config_mf_bw(sc);
7659     bxe_fw_command(sc, DRV_MSG_CODE_SET_MF_BW_ACK, 0);
7660 }
7661
7662 static void
7663 bxe_handle_eee_event(struct bxe_softc *sc)
7664 {
7665     BLOGD(sc, DBG_INTR, "EEE - LLDP event\n");
7666     bxe_fw_command(sc, DRV_MSG_CODE_EEE_RESULTS_ACK, 0);
7667 }
7668
7669 #define DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED 3
7670
7671 static void
7672 bxe_drv_info_ether_stat(struct bxe_softc *sc)
7673 {
7674     struct eth_stats_info *ether_stat =
7675         &sc->sp->drv_info_to_mcp.ether_stat;
7676
7677     strlcpy(ether_stat->version, BXE_DRIVER_VERSION,
7678             ETH_STAT_INFO_VERSION_LEN);
7679
7680     /* XXX (+ MAC_PAD) taken from other driver... verify this is right */
7681     sc->sp_objs[0].mac_obj.get_n_elements(sc, &sc->sp_objs[0].mac_obj,
7682                                           DRV_INFO_ETH_STAT_NUM_MACS_REQUIRED,
7683                                           ether_stat->mac_local + MAC_PAD,
7684                                           MAC_PAD, ETH_ALEN);
7685
7686     ether_stat->mtu_size = sc->mtu;
7687
7688     ether_stat->feature_flags |= FEATURE_ETH_CHKSUM_OFFLOAD_MASK;
7689     if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
7690         ether_stat->feature_flags |= FEATURE_ETH_LSO_MASK;
7691     }
7692
7693     // XXX ether_stat->feature_flags |= ???;
7694
7695     ether_stat->promiscuous_mode = 0; // (flags & PROMISC) ? 1 : 0;
7696
7697     ether_stat->txq_size = sc->tx_ring_size;
7698     ether_stat->rxq_size = sc->rx_ring_size;
7699 }
7700
7701 static void
7702 bxe_handle_drv_info_req(struct bxe_softc *sc)
7703 {
7704     enum drv_info_opcode op_code;
7705     uint32_t drv_info_ctl = SHMEM2_RD(sc, drv_info_control);
7706
7707     /* if drv_info version supported by MFW doesn't match - send NACK */
7708     if ((drv_info_ctl & DRV_INFO_CONTROL_VER_MASK) != DRV_INFO_CUR_VER) {
7709         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7710         return;
7711     }
7712
7713     op_code = ((drv_info_ctl & DRV_INFO_CONTROL_OP_CODE_MASK) >>
7714                DRV_INFO_CONTROL_OP_CODE_SHIFT);
7715
7716     memset(&sc->sp->drv_info_to_mcp, 0, sizeof(union drv_info_to_mcp));
7717
7718     switch (op_code) {
7719     case ETH_STATS_OPCODE:
7720         bxe_drv_info_ether_stat(sc);
7721         break;
7722     case FCOE_STATS_OPCODE:
7723     case ISCSI_STATS_OPCODE:
7724     default:
7725         /* if op code isn't supported - send NACK */
7726         bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_NACK, 0);
7727         return;
7728     }
7729
7730     /*
7731      * If we got drv_info attn from MFW then these fields are defined in
7732      * shmem2 for sure
7733      */
7734     SHMEM2_WR(sc, drv_info_host_addr_lo,
7735               U64_LO(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7736     SHMEM2_WR(sc, drv_info_host_addr_hi,
7737               U64_HI(BXE_SP_MAPPING(sc, drv_info_to_mcp)));
7738
7739     bxe_fw_command(sc, DRV_MSG_CODE_DRV_INFO_ACK, 0);
7740 }
7741
7742 static void
7743 bxe_dcc_event(struct bxe_softc *sc,
7744               uint32_t         dcc_event)
7745 {
7746     BLOGD(sc, DBG_INTR, "dcc_event 0x%08x\n", dcc_event);
7747
7748     if (dcc_event & DRV_STATUS_DCC_DISABLE_ENABLE_PF) {
7749         /*
7750          * This is the only place besides the function initialization
7751          * where the sc->flags can change so it is done without any
7752          * locks
7753          */
7754         if (sc->devinfo.mf_info.mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_DISABLED) {
7755             BLOGD(sc, DBG_INTR, "mf_cfg function disabled\n");
7756             sc->flags |= BXE_MF_FUNC_DIS;
7757             bxe_e1h_disable(sc);
7758         } else {
7759             BLOGD(sc, DBG_INTR, "mf_cfg function enabled\n");
7760             sc->flags &= ~BXE_MF_FUNC_DIS;
7761             bxe_e1h_enable(sc);
7762         }
7763         dcc_event &= ~DRV_STATUS_DCC_DISABLE_ENABLE_PF;
7764     }
7765
7766     if (dcc_event & DRV_STATUS_DCC_BANDWIDTH_ALLOCATION) {
7767         bxe_config_mf_bw(sc);
7768         dcc_event &= ~DRV_STATUS_DCC_BANDWIDTH_ALLOCATION;
7769     }
7770
7771     /* Report results to MCP */
7772     if (dcc_event)
7773         bxe_fw_command(sc, DRV_MSG_CODE_DCC_FAILURE, 0);
7774     else
7775         bxe_fw_command(sc, DRV_MSG_CODE_DCC_OK, 0);
7776 }
7777
7778 static void
7779 bxe_pmf_update(struct bxe_softc *sc)
7780 {
7781     int port = SC_PORT(sc);
7782     uint32_t val;
7783
7784     sc->port.pmf = 1;
7785     BLOGD(sc, DBG_INTR, "pmf %d\n", sc->port.pmf);
7786
7787     /*
7788      * We need the mb() to ensure the ordering between the writing to
7789      * sc->port.pmf here and reading it from the bxe_periodic_task().
7790      */
7791     mb();
7792
7793     /* queue a periodic task */
7794     // XXX schedule task...
7795
7796     // XXX bxe_dcbx_pmf_update(sc);
7797
7798     /* enable nig attention */
7799     val = (0xff0f | (1 << (SC_VN(sc) + 4)));
7800     if (sc->devinfo.int_block == INT_BLOCK_HC) {
7801         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, val);
7802         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, val);
7803     } else if (!CHIP_IS_E1x(sc)) {
7804         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
7805         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
7806     }
7807
7808     bxe_stats_handle(sc, STATS_EVENT_PMF);
7809 }
7810
7811 static int
7812 bxe_mc_assert(struct bxe_softc *sc)
7813 {
7814     char last_idx;
7815     int i, rc = 0;
7816     uint32_t row0, row1, row2, row3;
7817
7818     /* XSTORM */
7819     last_idx = REG_RD8(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_INDEX_OFFSET);
7820     if (last_idx)
7821         BLOGE(sc, "XSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7822
7823     /* print the asserts */
7824     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7825
7826         row0 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i));
7827         row1 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 4);
7828         row2 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 8);
7829         row3 = REG_RD(sc, BAR_XSTRORM_INTMEM + XSTORM_ASSERT_LIST_OFFSET(i) + 12);
7830
7831         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7832             BLOGE(sc, "XSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7833                   i, row3, row2, row1, row0);
7834             rc++;
7835         } else {
7836             break;
7837         }
7838     }
7839
7840     /* TSTORM */
7841     last_idx = REG_RD8(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_INDEX_OFFSET);
7842     if (last_idx) {
7843         BLOGE(sc, "TSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7844     }
7845
7846     /* print the asserts */
7847     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7848
7849         row0 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i));
7850         row1 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 4);
7851         row2 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 8);
7852         row3 = REG_RD(sc, BAR_TSTRORM_INTMEM + TSTORM_ASSERT_LIST_OFFSET(i) + 12);
7853
7854         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7855             BLOGE(sc, "TSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7856                   i, row3, row2, row1, row0);
7857             rc++;
7858         } else {
7859             break;
7860         }
7861     }
7862
7863     /* CSTORM */
7864     last_idx = REG_RD8(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_INDEX_OFFSET);
7865     if (last_idx) {
7866         BLOGE(sc, "CSTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7867     }
7868
7869     /* print the asserts */
7870     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7871
7872         row0 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i));
7873         row1 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 4);
7874         row2 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 8);
7875         row3 = REG_RD(sc, BAR_CSTRORM_INTMEM + CSTORM_ASSERT_LIST_OFFSET(i) + 12);
7876
7877         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7878             BLOGE(sc, "CSTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7879                   i, row3, row2, row1, row0);
7880             rc++;
7881         } else {
7882             break;
7883         }
7884     }
7885
7886     /* USTORM */
7887     last_idx = REG_RD8(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_INDEX_OFFSET);
7888     if (last_idx) {
7889         BLOGE(sc, "USTORM_ASSERT_LIST_INDEX 0x%x\n", last_idx);
7890     }
7891
7892     /* print the asserts */
7893     for (i = 0; i < STORM_ASSERT_ARRAY_SIZE; i++) {
7894
7895         row0 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i));
7896         row1 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 4);
7897         row2 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 8);
7898         row3 = REG_RD(sc, BAR_USTRORM_INTMEM + USTORM_ASSERT_LIST_OFFSET(i) + 12);
7899
7900         if (row0 != COMMON_ASM_INVALID_ASSERT_OPCODE) {
7901             BLOGE(sc, "USTORM_ASSERT_INDEX 0x%x = 0x%08x 0x%08x 0x%08x 0x%08x\n",
7902                   i, row3, row2, row1, row0);
7903             rc++;
7904         } else {
7905             break;
7906         }
7907     }
7908
7909     return (rc);
7910 }
7911
7912 static void
7913 bxe_attn_int_deasserted3(struct bxe_softc *sc,
7914                          uint32_t         attn)
7915 {
7916     int func = SC_FUNC(sc);
7917     uint32_t val;
7918
7919     if (attn & EVEREST_GEN_ATTN_IN_USE_MASK) {
7920
7921         if (attn & BXE_PMF_LINK_ASSERT(sc)) {
7922
7923             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
7924             bxe_read_mf_cfg(sc);
7925             sc->devinfo.mf_info.mf_config[SC_VN(sc)] =
7926                 MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
7927             val = SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_status);
7928
7929             if (val & DRV_STATUS_DCC_EVENT_MASK)
7930                 bxe_dcc_event(sc, (val & DRV_STATUS_DCC_EVENT_MASK));
7931
7932             if (val & DRV_STATUS_SET_MF_BW)
7933                 bxe_set_mf_bw(sc);
7934
7935             if (val & DRV_STATUS_DRV_INFO_REQ)
7936                 bxe_handle_drv_info_req(sc);
7937
7938             if ((sc->port.pmf == 0) && (val & DRV_STATUS_PMF))
7939                 bxe_pmf_update(sc);
7940
7941             if (val & DRV_STATUS_EEE_NEGOTIATION_RESULTS)
7942                 bxe_handle_eee_event(sc);
7943
7944             if (sc->link_vars.periodic_flags &
7945                 ELINK_PERIODIC_FLAGS_LINK_EVENT) {
7946                 /* sync with link */
7947                 bxe_acquire_phy_lock(sc);
7948                 sc->link_vars.periodic_flags &=
7949                     ~ELINK_PERIODIC_FLAGS_LINK_EVENT;
7950                 bxe_release_phy_lock(sc);
7951                 if (IS_MF(sc))
7952                     ; // XXX bxe_link_sync_notify(sc);
7953                 bxe_link_report(sc);
7954             }
7955
7956             /*
7957              * Always call it here: bxe_link_report() will
7958              * prevent the link indication duplication.
7959              */
7960             bxe_link_status_update(sc);
7961
7962         } else if (attn & BXE_MC_ASSERT_BITS) {
7963
7964             BLOGE(sc, "MC assert!\n");
7965             bxe_mc_assert(sc);
7966             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_10, 0);
7967             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_9, 0);
7968             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_8, 0);
7969             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_7, 0);
7970             bxe_panic(sc, ("MC assert!\n"));
7971
7972         } else if (attn & BXE_MCP_ASSERT) {
7973
7974             BLOGE(sc, "MCP assert!\n");
7975             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_11, 0);
7976             // XXX bxe_fw_dump(sc);
7977
7978         } else {
7979             BLOGE(sc, "Unknown HW assert! (attn 0x%08x)\n", attn);
7980         }
7981     }
7982
7983     if (attn & EVEREST_LATCHED_ATTN_IN_USE_MASK) {
7984         BLOGE(sc, "LATCHED attention 0x%08x (masked)\n", attn);
7985         if (attn & BXE_GRC_TIMEOUT) {
7986             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_TIMEOUT_ATTN);
7987             BLOGE(sc, "GRC time-out 0x%08x\n", val);
7988         }
7989         if (attn & BXE_GRC_RSV) {
7990             val = CHIP_IS_E1(sc) ? 0 : REG_RD(sc, MISC_REG_GRC_RSV_ATTN);
7991             BLOGE(sc, "GRC reserved 0x%08x\n", val);
7992         }
7993         REG_WR(sc, MISC_REG_AEU_CLR_LATCH_SIGNAL, 0x7ff);
7994     }
7995 }
7996
7997 static void
7998 bxe_attn_int_deasserted2(struct bxe_softc *sc,
7999                          uint32_t         attn)
8000 {
8001     int port = SC_PORT(sc);
8002     int reg_offset;
8003     uint32_t val0, mask0, val1, mask1;
8004     uint32_t val;
8005
8006     if (attn & AEU_INPUTS_ATTN_BITS_CFC_HW_INTERRUPT) {
8007         val = REG_RD(sc, CFC_REG_CFC_INT_STS_CLR);
8008         BLOGE(sc, "CFC hw attention 0x%08x\n", val);
8009         /* CFC error attention */
8010         if (val & 0x2) {
8011             BLOGE(sc, "FATAL error from CFC\n");
8012         }
8013     }
8014
8015     if (attn & AEU_INPUTS_ATTN_BITS_PXP_HW_INTERRUPT) {
8016         val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_0);
8017         BLOGE(sc, "PXP hw attention-0 0x%08x\n", val);
8018         /* RQ_USDMDP_FIFO_OVERFLOW */
8019         if (val & 0x18000) {
8020             BLOGE(sc, "FATAL error from PXP\n");
8021         }
8022
8023         if (!CHIP_IS_E1x(sc)) {
8024             val = REG_RD(sc, PXP_REG_PXP_INT_STS_CLR_1);
8025             BLOGE(sc, "PXP hw attention-1 0x%08x\n", val);
8026         }
8027     }
8028
8029 #define PXP2_EOP_ERROR_BIT  PXP2_PXP2_INT_STS_CLR_0_REG_WR_PGLUE_EOP_ERROR
8030 #define AEU_PXP2_HW_INT_BIT AEU_INPUTS_ATTN_BITS_PXPPCICLOCKCLIENT_HW_INTERRUPT
8031
8032     if (attn & AEU_PXP2_HW_INT_BIT) {
8033         /*  CQ47854 workaround do not panic on
8034          *  PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8035          */
8036         if (!CHIP_IS_E1x(sc)) {
8037             mask0 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_0);
8038             val1 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_1);
8039             mask1 = REG_RD(sc, PXP2_REG_PXP2_INT_MASK_1);
8040             val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_0);
8041             /*
8042              * If the olny PXP2_EOP_ERROR_BIT is set in
8043              * STS0 and STS1 - clear it
8044              *
8045              * probably we lose additional attentions between
8046              * STS0 and STS_CLR0, in this case user will not
8047              * be notified about them
8048              */
8049             if (val0 & mask0 & PXP2_EOP_ERROR_BIT &&
8050                 !(val1 & mask1))
8051                 val0 = REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
8052
8053             /* print the register, since no one can restore it */
8054             BLOGE(sc, "PXP2_REG_PXP2_INT_STS_CLR_0 0x%08x\n", val0);
8055
8056             /*
8057              * if PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR
8058              * then notify
8059              */
8060             if (val0 & PXP2_EOP_ERROR_BIT) {
8061                 BLOGE(sc, "PXP2_WR_PGLUE_EOP_ERROR\n");
8062
8063                 /*
8064                  * if only PXP2_PXP2_INT_STS_0_REG_WR_PGLUE_EOP_ERROR is
8065                  * set then clear attention from PXP2 block without panic
8066                  */
8067                 if (((val0 & mask0) == PXP2_EOP_ERROR_BIT) &&
8068                     ((val1 & mask1) == 0))
8069                     attn &= ~AEU_PXP2_HW_INT_BIT;
8070             }
8071         }
8072     }
8073
8074     if (attn & HW_INTERRUT_ASSERT_SET_2) {
8075         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_2 :
8076                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_2);
8077
8078         val = REG_RD(sc, reg_offset);
8079         val &= ~(attn & HW_INTERRUT_ASSERT_SET_2);
8080         REG_WR(sc, reg_offset, val);
8081
8082         BLOGE(sc, "FATAL HW block attention set2 0x%x\n",
8083               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_2));
8084         bxe_panic(sc, ("HW block attention set2\n"));
8085     }
8086 }
8087
8088 static void
8089 bxe_attn_int_deasserted1(struct bxe_softc *sc,
8090                          uint32_t         attn)
8091 {
8092     int port = SC_PORT(sc);
8093     int reg_offset;
8094     uint32_t val;
8095
8096     if (attn & AEU_INPUTS_ATTN_BITS_DOORBELLQ_HW_INTERRUPT) {
8097         val = REG_RD(sc, DORQ_REG_DORQ_INT_STS_CLR);
8098         BLOGE(sc, "DB hw attention 0x%08x\n", val);
8099         /* DORQ discard attention */
8100         if (val & 0x2) {
8101             BLOGE(sc, "FATAL error from DORQ\n");
8102         }
8103     }
8104
8105     if (attn & HW_INTERRUT_ASSERT_SET_1) {
8106         reg_offset = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_1 :
8107                              MISC_REG_AEU_ENABLE1_FUNC_0_OUT_1);
8108
8109         val = REG_RD(sc, reg_offset);
8110         val &= ~(attn & HW_INTERRUT_ASSERT_SET_1);
8111         REG_WR(sc, reg_offset, val);
8112
8113         BLOGE(sc, "FATAL HW block attention set1 0x%08x\n",
8114               (uint32_t)(attn & HW_INTERRUT_ASSERT_SET_1));
8115         bxe_panic(sc, ("HW block attention set1\n"));
8116     }
8117 }
8118
8119 static void
8120 bxe_attn_int_deasserted0(struct bxe_softc *sc,
8121                          uint32_t         attn)
8122 {
8123     int port = SC_PORT(sc);
8124     int reg_offset;
8125     uint32_t val;
8126
8127     reg_offset = (port) ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
8128                           MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
8129
8130     if (attn & AEU_INPUTS_ATTN_BITS_SPIO5) {
8131         val = REG_RD(sc, reg_offset);
8132         val &= ~AEU_INPUTS_ATTN_BITS_SPIO5;
8133         REG_WR(sc, reg_offset, val);
8134
8135         BLOGW(sc, "SPIO5 hw attention\n");
8136
8137         /* Fan failure attention */
8138         elink_hw_reset_phy(&sc->link_params);
8139         bxe_fan_failure(sc);
8140     }
8141
8142     if ((attn & sc->link_vars.aeu_int_mask) && sc->port.pmf) {
8143         bxe_acquire_phy_lock(sc);
8144         elink_handle_module_detect_int(&sc->link_params);
8145         bxe_release_phy_lock(sc);
8146     }
8147
8148     if (attn & HW_INTERRUT_ASSERT_SET_0) {
8149         val = REG_RD(sc, reg_offset);
8150         val &= ~(attn & HW_INTERRUT_ASSERT_SET_0);
8151         REG_WR(sc, reg_offset, val);
8152
8153         bxe_panic(sc, ("FATAL HW block attention set0 0x%lx\n",
8154                        (attn & HW_INTERRUT_ASSERT_SET_0)));
8155     }
8156 }
8157
8158 static void
8159 bxe_attn_int_deasserted(struct bxe_softc *sc,
8160                         uint32_t         deasserted)
8161 {
8162     struct attn_route attn;
8163     struct attn_route *group_mask;
8164     int port = SC_PORT(sc);
8165     int index;
8166     uint32_t reg_addr;
8167     uint32_t val;
8168     uint32_t aeu_mask;
8169     uint8_t global = FALSE;
8170
8171     /*
8172      * Need to take HW lock because MCP or other port might also
8173      * try to handle this event.
8174      */
8175     bxe_acquire_alr(sc);
8176
8177     if (bxe_chk_parity_attn(sc, &global, TRUE)) {
8178         /* XXX
8179          * In case of parity errors don't handle attentions so that
8180          * other function would "see" parity errors.
8181          */
8182         sc->recovery_state = BXE_RECOVERY_INIT;
8183         // XXX schedule a recovery task...
8184         /* disable HW interrupts */
8185         bxe_int_disable(sc);
8186         bxe_release_alr(sc);
8187         return;
8188     }
8189
8190     attn.sig[0] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 + port*4);
8191     attn.sig[1] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_2_FUNC_0 + port*4);
8192     attn.sig[2] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_3_FUNC_0 + port*4);
8193     attn.sig[3] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_4_FUNC_0 + port*4);
8194     if (!CHIP_IS_E1x(sc)) {
8195         attn.sig[4] = REG_RD(sc, MISC_REG_AEU_AFTER_INVERT_5_FUNC_0 + port*4);
8196     } else {
8197         attn.sig[4] = 0;
8198     }
8199
8200     BLOGD(sc, DBG_INTR, "attn: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n",
8201           attn.sig[0], attn.sig[1], attn.sig[2], attn.sig[3], attn.sig[4]);
8202
8203     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
8204         if (deasserted & (1 << index)) {
8205             group_mask = &sc->attn_group[index];
8206
8207             BLOGD(sc, DBG_INTR,
8208                   "group[%d]: 0x%08x 0x%08x 0x%08x 0x%08x 0x%08x\n", index,
8209                   group_mask->sig[0], group_mask->sig[1],
8210                   group_mask->sig[2], group_mask->sig[3],
8211                   group_mask->sig[4]);
8212
8213             bxe_attn_int_deasserted4(sc, attn.sig[4] & group_mask->sig[4]);
8214             bxe_attn_int_deasserted3(sc, attn.sig[3] & group_mask->sig[3]);
8215             bxe_attn_int_deasserted1(sc, attn.sig[1] & group_mask->sig[1]);
8216             bxe_attn_int_deasserted2(sc, attn.sig[2] & group_mask->sig[2]);
8217             bxe_attn_int_deasserted0(sc, attn.sig[0] & group_mask->sig[0]);
8218         }
8219     }
8220
8221     bxe_release_alr(sc);
8222
8223     if (sc->devinfo.int_block == INT_BLOCK_HC) {
8224         reg_addr = (HC_REG_COMMAND_REG + port*32 +
8225                     COMMAND_REG_ATTN_BITS_CLR);
8226     } else {
8227         reg_addr = (BAR_IGU_INTMEM + IGU_CMD_ATTN_BIT_CLR_UPPER*8);
8228     }
8229
8230     val = ~deasserted;
8231     BLOGD(sc, DBG_INTR,
8232           "about to mask 0x%08x at %s addr 0x%08x\n", val,
8233           (sc->devinfo.int_block == INT_BLOCK_HC) ? "HC" : "IGU", reg_addr);
8234     REG_WR(sc, reg_addr, val);
8235
8236     if (~sc->attn_state & deasserted) {
8237         BLOGE(sc, "IGU error\n");
8238     }
8239
8240     reg_addr = port ? MISC_REG_AEU_MASK_ATTN_FUNC_1 :
8241                       MISC_REG_AEU_MASK_ATTN_FUNC_0;
8242
8243     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8244
8245     aeu_mask = REG_RD(sc, reg_addr);
8246
8247     BLOGD(sc, DBG_INTR, "aeu_mask 0x%08x newly deasserted 0x%08x\n",
8248           aeu_mask, deasserted);
8249     aeu_mask |= (deasserted & 0x3ff);
8250     BLOGD(sc, DBG_INTR, "new mask 0x%08x\n", aeu_mask);
8251
8252     REG_WR(sc, reg_addr, aeu_mask);
8253     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_PORT0_ATT_MASK + port);
8254
8255     BLOGD(sc, DBG_INTR, "attn_state 0x%08x\n", sc->attn_state);
8256     sc->attn_state &= ~deasserted;
8257     BLOGD(sc, DBG_INTR, "new state 0x%08x\n", sc->attn_state);
8258 }
8259
8260 static void
8261 bxe_attn_int(struct bxe_softc *sc)
8262 {
8263     /* read local copy of bits */
8264     uint32_t attn_bits = le32toh(sc->def_sb->atten_status_block.attn_bits);
8265     uint32_t attn_ack = le32toh(sc->def_sb->atten_status_block.attn_bits_ack);
8266     uint32_t attn_state = sc->attn_state;
8267
8268     /* look for changed bits */
8269     uint32_t asserted   =  attn_bits & ~attn_ack & ~attn_state;
8270     uint32_t deasserted = ~attn_bits &  attn_ack &  attn_state;
8271
8272     BLOGD(sc, DBG_INTR,
8273           "attn_bits 0x%08x attn_ack 0x%08x asserted 0x%08x deasserted 0x%08x\n",
8274           attn_bits, attn_ack, asserted, deasserted);
8275
8276     if (~(attn_bits ^ attn_ack) & (attn_bits ^ attn_state)) {
8277         BLOGE(sc, "BAD attention state\n");
8278     }
8279
8280     /* handle bits that were raised */
8281     if (asserted) {
8282         bxe_attn_int_asserted(sc, asserted);
8283     }
8284
8285     if (deasserted) {
8286         bxe_attn_int_deasserted(sc, deasserted);
8287     }
8288 }
8289
8290 static uint16_t
8291 bxe_update_dsb_idx(struct bxe_softc *sc)
8292 {
8293     struct host_sp_status_block *def_sb = sc->def_sb;
8294     uint16_t rc = 0;
8295
8296     mb(); /* status block is written to by the chip */
8297
8298     if (sc->def_att_idx != def_sb->atten_status_block.attn_bits_index) {
8299         sc->def_att_idx = def_sb->atten_status_block.attn_bits_index;
8300         rc |= BXE_DEF_SB_ATT_IDX;
8301     }
8302
8303     if (sc->def_idx != def_sb->sp_sb.running_index) {
8304         sc->def_idx = def_sb->sp_sb.running_index;
8305         rc |= BXE_DEF_SB_IDX;
8306     }
8307
8308     mb();
8309
8310     return (rc);
8311 }
8312
8313 static inline struct ecore_queue_sp_obj *
8314 bxe_cid_to_q_obj(struct bxe_softc *sc,
8315                  uint32_t         cid)
8316 {
8317     BLOGD(sc, DBG_SP, "retrieving fp from cid %d\n", cid);
8318     return (&sc->sp_objs[CID_TO_FP(cid, sc)].q_obj);
8319 }
8320
8321 static void
8322 bxe_handle_mcast_eqe(struct bxe_softc *sc)
8323 {
8324     struct ecore_mcast_ramrod_params rparam;
8325     int rc;
8326
8327     memset(&rparam, 0, sizeof(rparam));
8328
8329     rparam.mcast_obj = &sc->mcast_obj;
8330
8331     BXE_MCAST_LOCK(sc);
8332
8333     /* clear pending state for the last command */
8334     sc->mcast_obj.raw.clear_pending(&sc->mcast_obj.raw);
8335
8336     /* if there are pending mcast commands - send them */
8337     if (sc->mcast_obj.check_pending(&sc->mcast_obj)) {
8338         rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_CONT);
8339         if (rc < 0) {
8340             BLOGD(sc, DBG_SP,
8341                 "ERROR: Failed to send pending mcast commands (%d)\n", rc);
8342         }
8343     }
8344
8345     BXE_MCAST_UNLOCK(sc);
8346 }
8347
8348 static void
8349 bxe_handle_classification_eqe(struct bxe_softc      *sc,
8350                               union event_ring_elem *elem)
8351 {
8352     unsigned long ramrod_flags = 0;
8353     int rc = 0;
8354     uint32_t cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8355     struct ecore_vlan_mac_obj *vlan_mac_obj;
8356
8357     /* always push next commands out, don't wait here */
8358     bit_set(&ramrod_flags, RAMROD_CONT);
8359
8360     switch (le32toh(elem->message.data.eth_event.echo) >> BXE_SWCID_SHIFT) {
8361     case ECORE_FILTER_MAC_PENDING:
8362         BLOGD(sc, DBG_SP, "Got SETUP_MAC completions\n");
8363         vlan_mac_obj = &sc->sp_objs[cid].mac_obj;
8364         break;
8365
8366     case ECORE_FILTER_MCAST_PENDING:
8367         BLOGD(sc, DBG_SP, "Got SETUP_MCAST completions\n");
8368         /*
8369          * This is only relevant for 57710 where multicast MACs are
8370          * configured as unicast MACs using the same ramrod.
8371          */
8372         bxe_handle_mcast_eqe(sc);
8373         return;
8374
8375     default:
8376         BLOGE(sc, "Unsupported classification command: %d\n",
8377               elem->message.data.eth_event.echo);
8378         return;
8379     }
8380
8381     rc = vlan_mac_obj->complete(sc, vlan_mac_obj, elem, &ramrod_flags);
8382
8383     if (rc < 0) {
8384         BLOGE(sc, "Failed to schedule new commands (%d)\n", rc);
8385     } else if (rc > 0) {
8386         BLOGD(sc, DBG_SP, "Scheduled next pending commands...\n");
8387     }
8388 }
8389
8390 static void
8391 bxe_handle_rx_mode_eqe(struct bxe_softc      *sc,
8392                        union event_ring_elem *elem)
8393 {
8394     bxe_clear_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state);
8395
8396     /* send rx_mode command again if was requested */
8397     if (bxe_test_and_clear_bit(ECORE_FILTER_RX_MODE_SCHED,
8398                                &sc->sp_state)) {
8399         bxe_set_storm_rx_mode(sc);
8400     }
8401 }
8402
8403 static void
8404 bxe_update_eq_prod(struct bxe_softc *sc,
8405                    uint16_t         prod)
8406 {
8407     storm_memset_eq_prod(sc, prod, SC_FUNC(sc));
8408     wmb(); /* keep prod updates ordered */
8409 }
8410
8411 static void
8412 bxe_eq_int(struct bxe_softc *sc)
8413 {
8414     uint16_t hw_cons, sw_cons, sw_prod;
8415     union event_ring_elem *elem;
8416     uint8_t echo;
8417     uint32_t cid;
8418     uint8_t opcode;
8419     int spqe_cnt = 0;
8420     struct ecore_queue_sp_obj *q_obj;
8421     struct ecore_func_sp_obj *f_obj = &sc->func_obj;
8422     struct ecore_raw_obj *rss_raw = &sc->rss_conf_obj.raw;
8423
8424     hw_cons = le16toh(*sc->eq_cons_sb);
8425
8426     /*
8427      * The hw_cons range is 1-255, 257 - the sw_cons range is 0-254, 256.
8428      * when we get to the next-page we need to adjust so the loop
8429      * condition below will be met. The next element is the size of a
8430      * regular element and hence incrementing by 1
8431      */
8432     if ((hw_cons & EQ_DESC_MAX_PAGE) == EQ_DESC_MAX_PAGE) {
8433         hw_cons++;
8434     }
8435
8436     /*
8437      * This function may never run in parallel with itself for a
8438      * specific sc and no need for a read memory barrier here.
8439      */
8440     sw_cons = sc->eq_cons;
8441     sw_prod = sc->eq_prod;
8442
8443     BLOGD(sc, DBG_SP,"EQ: hw_cons=%u sw_cons=%u eq_spq_left=0x%lx\n",
8444           hw_cons, sw_cons, atomic_load_acq_long(&sc->eq_spq_left));
8445
8446     for (;
8447          sw_cons != hw_cons;
8448          sw_prod = NEXT_EQ_IDX(sw_prod), sw_cons = NEXT_EQ_IDX(sw_cons)) {
8449
8450         elem = &sc->eq[EQ_DESC(sw_cons)];
8451
8452         /* elem CID originates from FW, actually LE */
8453         cid = SW_CID(elem->message.data.cfc_del_event.cid);
8454         opcode = elem->message.opcode;
8455
8456         /* handle eq element */
8457         switch (opcode) {
8458
8459         case EVENT_RING_OPCODE_STAT_QUERY:
8460             BLOGD(sc, DBG_SP, "got statistics completion event %d\n",
8461                   sc->stats_comp++);
8462             /* nothing to do with stats comp */
8463             goto next_spqe;
8464
8465         case EVENT_RING_OPCODE_CFC_DEL:
8466             /* handle according to cid range */
8467             /* we may want to verify here that the sc state is HALTING */
8468             BLOGD(sc, DBG_SP, "got delete ramrod for MULTI[%d]\n", cid);
8469             q_obj = bxe_cid_to_q_obj(sc, cid);
8470             if (q_obj->complete_cmd(sc, q_obj, ECORE_Q_CMD_CFC_DEL)) {
8471                 break;
8472             }
8473             goto next_spqe;
8474
8475         case EVENT_RING_OPCODE_STOP_TRAFFIC:
8476             BLOGD(sc, DBG_SP, "got STOP TRAFFIC\n");
8477             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_STOP)) {
8478                 break;
8479             }
8480             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_PAUSED);
8481             goto next_spqe;
8482
8483         case EVENT_RING_OPCODE_START_TRAFFIC:
8484             BLOGD(sc, DBG_SP, "got START TRAFFIC\n");
8485             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_TX_START)) {
8486                 break;
8487             }
8488             // XXX bxe_dcbx_set_params(sc, BXE_DCBX_STATE_TX_RELEASED);
8489             goto next_spqe;
8490
8491         case EVENT_RING_OPCODE_FUNCTION_UPDATE:
8492             echo = elem->message.data.function_update_event.echo;
8493             if (echo == SWITCH_UPDATE) {
8494                 BLOGD(sc, DBG_SP, "got FUNC_SWITCH_UPDATE ramrod\n");
8495                 if (f_obj->complete_cmd(sc, f_obj,
8496                                         ECORE_F_CMD_SWITCH_UPDATE)) {
8497                     break;
8498                 }
8499             }
8500             else {
8501                 BLOGD(sc, DBG_SP,
8502                       "AFEX: ramrod completed FUNCTION_UPDATE\n");
8503             }
8504             goto next_spqe;
8505
8506         case EVENT_RING_OPCODE_FORWARD_SETUP:
8507             q_obj = &bxe_fwd_sp_obj(sc, q_obj);
8508             if (q_obj->complete_cmd(sc, q_obj,
8509                                     ECORE_Q_CMD_SETUP_TX_ONLY)) {
8510                 break;
8511             }
8512             goto next_spqe;
8513
8514         case EVENT_RING_OPCODE_FUNCTION_START:
8515             BLOGD(sc, DBG_SP, "got FUNC_START ramrod\n");
8516             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_START)) {
8517                 break;
8518             }
8519             goto next_spqe;
8520
8521         case EVENT_RING_OPCODE_FUNCTION_STOP:
8522             BLOGD(sc, DBG_SP, "got FUNC_STOP ramrod\n");
8523             if (f_obj->complete_cmd(sc, f_obj, ECORE_F_CMD_STOP)) {
8524                 break;
8525             }
8526             goto next_spqe;
8527         }
8528
8529         switch (opcode | sc->state) {
8530         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPEN):
8531         case (EVENT_RING_OPCODE_RSS_UPDATE_RULES | BXE_STATE_OPENING_WAITING_PORT):
8532             cid = elem->message.data.eth_event.echo & BXE_SWCID_MASK;
8533             BLOGD(sc, DBG_SP, "got RSS_UPDATE ramrod. CID %d\n", cid);
8534             rss_raw->clear_pending(rss_raw);
8535             break;
8536
8537         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_OPEN):
8538         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_DIAG):
8539         case (EVENT_RING_OPCODE_SET_MAC | BXE_STATE_CLOSING_WAITING_HALT):
8540         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_OPEN):
8541         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_DIAG):
8542         case (EVENT_RING_OPCODE_CLASSIFICATION_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8543             BLOGD(sc, DBG_SP, "got (un)set mac ramrod\n");
8544             bxe_handle_classification_eqe(sc, elem);
8545             break;
8546
8547         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_OPEN):
8548         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_DIAG):
8549         case (EVENT_RING_OPCODE_MULTICAST_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8550             BLOGD(sc, DBG_SP, "got mcast ramrod\n");
8551             bxe_handle_mcast_eqe(sc);
8552             break;
8553
8554         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_OPEN):
8555         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_DIAG):
8556         case (EVENT_RING_OPCODE_FILTERS_RULES | BXE_STATE_CLOSING_WAITING_HALT):
8557             BLOGD(sc, DBG_SP, "got rx_mode ramrod\n");
8558             bxe_handle_rx_mode_eqe(sc, elem);
8559             break;
8560
8561         default:
8562             /* unknown event log error and continue */
8563             BLOGE(sc, "Unknown EQ event %d, sc->state 0x%x\n",
8564                   elem->message.opcode, sc->state);
8565         }
8566
8567 next_spqe:
8568         spqe_cnt++;
8569     } /* for */
8570
8571     mb();
8572     atomic_add_acq_long(&sc->eq_spq_left, spqe_cnt);
8573
8574     sc->eq_cons = sw_cons;
8575     sc->eq_prod = sw_prod;
8576
8577     /* make sure that above mem writes were issued towards the memory */
8578     wmb();
8579
8580     /* update producer */
8581     bxe_update_eq_prod(sc, sc->eq_prod);
8582 }
8583
8584 static void
8585 bxe_handle_sp_tq(void *context,
8586                  int  pending)
8587 {
8588     struct bxe_softc *sc = (struct bxe_softc *)context;
8589     uint16_t status;
8590
8591     BLOGD(sc, DBG_SP, "---> SP TASK <---\n");
8592
8593     /* what work needs to be performed? */
8594     status = bxe_update_dsb_idx(sc);
8595
8596     BLOGD(sc, DBG_SP, "dsb status 0x%04x\n", status);
8597
8598     /* HW attentions */
8599     if (status & BXE_DEF_SB_ATT_IDX) {
8600         BLOGD(sc, DBG_SP, "---> ATTN INTR <---\n");
8601         bxe_attn_int(sc);
8602         status &= ~BXE_DEF_SB_ATT_IDX;
8603     }
8604
8605     /* SP events: STAT_QUERY and others */
8606     if (status & BXE_DEF_SB_IDX) {
8607         /* handle EQ completions */
8608         BLOGD(sc, DBG_SP, "---> EQ INTR <---\n");
8609         bxe_eq_int(sc);
8610         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID,
8611                    le16toh(sc->def_idx), IGU_INT_NOP, 1);
8612         status &= ~BXE_DEF_SB_IDX;
8613     }
8614
8615     /* if status is non zero then something went wrong */
8616     if (__predict_false(status)) {
8617         BLOGE(sc, "Got an unknown SP interrupt! (0x%04x)\n", status);
8618     }
8619
8620     /* ack status block only if something was actually handled */
8621     bxe_ack_sb(sc, sc->igu_dsb_id, ATTENTION_ID,
8622                le16toh(sc->def_att_idx), IGU_INT_ENABLE, 1);
8623
8624     /*
8625      * Must be called after the EQ processing (since eq leads to sriov
8626      * ramrod completion flows).
8627      * This flow may have been scheduled by the arrival of a ramrod
8628      * completion, or by the sriov code rescheduling itself.
8629      */
8630     // XXX bxe_iov_sp_task(sc);
8631
8632 }
8633
8634 static void
8635 bxe_handle_fp_tq(void *context,
8636                  int  pending)
8637 {
8638     struct bxe_fastpath *fp = (struct bxe_fastpath *)context;
8639     struct bxe_softc *sc = fp->sc;
8640     uint8_t more_tx = FALSE;
8641     uint8_t more_rx = FALSE;
8642
8643     BLOGD(sc, DBG_INTR, "---> FP TASK QUEUE (%d) <---\n", fp->index);
8644
8645     /* XXX
8646      * IFF_DRV_RUNNING state can't be checked here since we process
8647      * slowpath events on a client queue during setup. Instead
8648      * we need to add a "process/continue" flag here that the driver
8649      * can use to tell the task here not to do anything.
8650      */
8651 #if 0
8652     if (!(sc->ifnet->if_drv_flags & IFF_DRV_RUNNING)) {
8653         return;
8654     }
8655 #endif
8656
8657     /* update the fastpath index */
8658     bxe_update_fp_sb_idx(fp);
8659
8660     /* XXX add loop here if ever support multiple tx CoS */
8661     /* fp->txdata[cos] */
8662     if (bxe_has_tx_work(fp)) {
8663         BXE_FP_TX_LOCK(fp);
8664         more_tx = bxe_txeof(sc, fp);
8665         BXE_FP_TX_UNLOCK(fp);
8666     }
8667
8668     if (bxe_has_rx_work(fp)) {
8669         more_rx = bxe_rxeof(sc, fp);
8670     }
8671
8672     if (more_rx /*|| more_tx*/) {
8673         /* still more work to do */
8674         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8675         return;
8676     }
8677
8678     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8679                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8680 }
8681
8682 static void
8683 bxe_task_fp(struct bxe_fastpath *fp)
8684 {
8685     struct bxe_softc *sc = fp->sc;
8686     uint8_t more_tx = FALSE;
8687     uint8_t more_rx = FALSE;
8688
8689     BLOGD(sc, DBG_INTR, "---> FP TASK ISR (%d) <---\n", fp->index);
8690
8691     /* update the fastpath index */
8692     bxe_update_fp_sb_idx(fp);
8693
8694     /* XXX add loop here if ever support multiple tx CoS */
8695     /* fp->txdata[cos] */
8696     if (bxe_has_tx_work(fp)) {
8697         BXE_FP_TX_LOCK(fp);
8698         more_tx = bxe_txeof(sc, fp);
8699         BXE_FP_TX_UNLOCK(fp);
8700     }
8701
8702     if (bxe_has_rx_work(fp)) {
8703         more_rx = bxe_rxeof(sc, fp);
8704     }
8705
8706     if (more_rx /*|| more_tx*/) {
8707         /* still more work to do, bail out if this ISR and process later */
8708         taskqueue_enqueue_fast(fp->tq, &fp->tq_task);
8709         return;
8710     }
8711
8712     /*
8713      * Here we write the fastpath index taken before doing any tx or rx work.
8714      * It is very well possible other hw events occurred up to this point and
8715      * they were actually processed accordingly above. Since we're going to
8716      * write an older fastpath index, an interrupt is coming which we might
8717      * not do any work in.
8718      */
8719     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID,
8720                le16toh(fp->fp_hc_idx), IGU_INT_ENABLE, 1);
8721 }
8722
8723 /*
8724  * Legacy interrupt entry point.
8725  *
8726  * Verifies that the controller generated the interrupt and
8727  * then calls a separate routine to handle the various
8728  * interrupt causes: link, RX, and TX.
8729  */
8730 static void
8731 bxe_intr_legacy(void *xsc)
8732 {
8733     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8734     struct bxe_fastpath *fp;
8735     uint16_t status, mask;
8736     int i;
8737
8738     BLOGD(sc, DBG_INTR, "---> BXE INTx <---\n");
8739
8740     /*
8741      * 0 for ustorm, 1 for cstorm
8742      * the bits returned from ack_int() are 0-15
8743      * bit 0 = attention status block
8744      * bit 1 = fast path status block
8745      * a mask of 0x2 or more = tx/rx event
8746      * a mask of 1 = slow path event
8747      */
8748
8749     status = bxe_ack_int(sc);
8750
8751     /* the interrupt is not for us */
8752     if (__predict_false(status == 0)) {
8753         BLOGD(sc, DBG_INTR, "Not our interrupt!\n");
8754         return;
8755     }
8756
8757     BLOGD(sc, DBG_INTR, "Interrupt status 0x%04x\n", status);
8758
8759     FOR_EACH_ETH_QUEUE(sc, i) {
8760         fp = &sc->fp[i];
8761         mask = (0x2 << (fp->index + CNIC_SUPPORT(sc)));
8762         if (status & mask) {
8763             /* acknowledge and disable further fastpath interrupts */
8764             bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8765             bxe_task_fp(fp);
8766             status &= ~mask;
8767         }
8768     }
8769
8770     if (__predict_false(status & 0x1)) {
8771         /* acknowledge and disable further slowpath interrupts */
8772         bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8773
8774         /* schedule slowpath handler */
8775         taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8776
8777         status &= ~0x1;
8778     }
8779
8780     if (__predict_false(status)) {
8781         BLOGW(sc, "Unexpected fastpath status (0x%08x)!\n", status);
8782     }
8783 }
8784
8785 /* slowpath interrupt entry point */
8786 static void
8787 bxe_intr_sp(void *xsc)
8788 {
8789     struct bxe_softc *sc = (struct bxe_softc *)xsc;
8790
8791     BLOGD(sc, (DBG_INTR | DBG_SP), "---> SP INTR <---\n");
8792
8793     /* acknowledge and disable further slowpath interrupts */
8794     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8795
8796     /* schedule slowpath handler */
8797     taskqueue_enqueue_fast(sc->sp_tq, &sc->sp_tq_task);
8798 }
8799
8800 /* fastpath interrupt entry point */
8801 static void
8802 bxe_intr_fp(void *xfp)
8803 {
8804     struct bxe_fastpath *fp = (struct bxe_fastpath *)xfp;
8805     struct bxe_softc *sc = fp->sc;
8806
8807     BLOGD(sc, DBG_INTR, "---> FP INTR %d <---\n", fp->index);
8808
8809     BLOGD(sc, DBG_INTR,
8810           "(cpu=%d) MSI-X fp=%d fw_sb=%d igu_sb=%d\n",
8811           curcpu, fp->index, fp->fw_sb_id, fp->igu_sb_id);
8812
8813     /* acknowledge and disable further fastpath interrupts */
8814     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_DISABLE, 0);
8815
8816     bxe_task_fp(fp);
8817 }
8818
8819 /* Release all interrupts allocated by the driver. */
8820 static void
8821 bxe_interrupt_free(struct bxe_softc *sc)
8822 {
8823     int i;
8824
8825     switch (sc->interrupt_mode) {
8826     case INTR_MODE_INTX:
8827         BLOGD(sc, DBG_LOAD, "Releasing legacy INTx vector\n");
8828         if (sc->intr[0].resource != NULL) {
8829             bus_release_resource(sc->dev,
8830                                  SYS_RES_IRQ,
8831                                  sc->intr[0].rid,
8832                                  sc->intr[0].resource);
8833         }
8834         break;
8835     case INTR_MODE_MSI:
8836         for (i = 0; i < sc->intr_count; i++) {
8837             BLOGD(sc, DBG_LOAD, "Releasing MSI vector %d\n", i);
8838             if (sc->intr[i].resource && sc->intr[i].rid) {
8839                 bus_release_resource(sc->dev,
8840                                      SYS_RES_IRQ,
8841                                      sc->intr[i].rid,
8842                                      sc->intr[i].resource);
8843             }
8844         }
8845         pci_release_msi(sc->dev);
8846         break;
8847     case INTR_MODE_MSIX:
8848         for (i = 0; i < sc->intr_count; i++) {
8849             BLOGD(sc, DBG_LOAD, "Releasing MSI-X vector %d\n", i);
8850             if (sc->intr[i].resource && sc->intr[i].rid) {
8851                 bus_release_resource(sc->dev,
8852                                      SYS_RES_IRQ,
8853                                      sc->intr[i].rid,
8854                                      sc->intr[i].resource);
8855             }
8856         }
8857         pci_release_msi(sc->dev);
8858         break;
8859     default:
8860         /* nothing to do as initial allocation failed */
8861         break;
8862     }
8863 }
8864
8865 /*
8866  * This function determines and allocates the appropriate
8867  * interrupt based on system capabilites and user request.
8868  *
8869  * The user may force a particular interrupt mode, specify
8870  * the number of receive queues, specify the method for
8871  * distribuitng received frames to receive queues, or use
8872  * the default settings which will automatically select the
8873  * best supported combination.  In addition, the OS may or
8874  * may not support certain combinations of these settings.
8875  * This routine attempts to reconcile the settings requested
8876  * by the user with the capabilites available from the system
8877  * to select the optimal combination of features.
8878  *
8879  * Returns:
8880  *   0 = Success, !0 = Failure.
8881  */
8882 static int
8883 bxe_interrupt_alloc(struct bxe_softc *sc)
8884 {
8885     int msix_count = 0;
8886     int msi_count = 0;
8887     int num_requested = 0;
8888     int num_allocated = 0;
8889     int rid, i, j;
8890     int rc;
8891
8892     /* get the number of available MSI/MSI-X interrupts from the OS */
8893     if (sc->interrupt_mode > 0) {
8894         if (sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) {
8895             msix_count = pci_msix_count(sc->dev);
8896         }
8897
8898         if (sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) {
8899             msi_count = pci_msi_count(sc->dev);
8900         }
8901
8902         BLOGD(sc, DBG_LOAD, "%d MSI and %d MSI-X vectors available\n",
8903               msi_count, msix_count);
8904     }
8905
8906     do { /* try allocating MSI-X interrupt resources (at least 2) */
8907         if (sc->interrupt_mode != INTR_MODE_MSIX) {
8908             break;
8909         }
8910
8911         if (((sc->devinfo.pcie_cap_flags & BXE_MSIX_CAPABLE_FLAG) == 0) ||
8912             (msix_count < 2)) {
8913             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8914             break;
8915         }
8916
8917         /* ask for the necessary number of MSI-X vectors */
8918         num_requested = min((sc->num_queues + 1), msix_count);
8919
8920         BLOGD(sc, DBG_LOAD, "Requesting %d MSI-X vectors\n", num_requested);
8921
8922         num_allocated = num_requested;
8923         if ((rc = pci_alloc_msix(sc->dev, &num_allocated)) != 0) {
8924             BLOGE(sc, "MSI-X alloc failed! (%d)\n", rc);
8925             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8926             break;
8927         }
8928
8929         if (num_allocated < 2) { /* possible? */
8930             BLOGE(sc, "MSI-X allocation less than 2!\n");
8931             sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8932             pci_release_msi(sc->dev);
8933             break;
8934         }
8935
8936         BLOGI(sc, "MSI-X vectors Requested %d and Allocated %d\n",
8937               num_requested, num_allocated);
8938
8939         /* best effort so use the number of vectors allocated to us */
8940         sc->intr_count = num_allocated;
8941         sc->num_queues = num_allocated - 1;
8942
8943         rid = 1; /* initial resource identifier */
8944
8945         /* allocate the MSI-X vectors */
8946         for (i = 0; i < num_allocated; i++) {
8947             sc->intr[i].rid = (rid + i);
8948
8949             if ((sc->intr[i].resource =
8950                  bus_alloc_resource_any(sc->dev,
8951                                         SYS_RES_IRQ,
8952                                         &sc->intr[i].rid,
8953                                         RF_ACTIVE)) == NULL) {
8954                 BLOGE(sc, "Failed to map MSI-X[%d] (rid=%d)!\n",
8955                       i, (rid + i));
8956
8957                 for (j = (i - 1); j >= 0; j--) {
8958                     bus_release_resource(sc->dev,
8959                                          SYS_RES_IRQ,
8960                                          sc->intr[j].rid,
8961                                          sc->intr[j].resource);
8962                 }
8963
8964                 sc->intr_count = 0;
8965                 sc->num_queues = 0;
8966                 sc->interrupt_mode = INTR_MODE_MSI; /* try MSI next */
8967                 pci_release_msi(sc->dev);
8968                 break;
8969             }
8970
8971             BLOGD(sc, DBG_LOAD, "Mapped MSI-X[%d] (rid=%d)\n", i, (rid + i));
8972         }
8973     } while (0);
8974
8975     do { /* try allocating MSI vector resources (at least 2) */
8976         if (sc->interrupt_mode != INTR_MODE_MSI) {
8977             break;
8978         }
8979
8980         if (((sc->devinfo.pcie_cap_flags & BXE_MSI_CAPABLE_FLAG) == 0) ||
8981             (msi_count < 1)) {
8982             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8983             break;
8984         }
8985
8986         /* ask for a single MSI vector */
8987         num_requested = 1;
8988
8989         BLOGD(sc, DBG_LOAD, "Requesting %d MSI vectors\n", num_requested);
8990
8991         num_allocated = num_requested;
8992         if ((rc = pci_alloc_msi(sc->dev, &num_allocated)) != 0) {
8993             BLOGE(sc, "MSI alloc failed (%d)!\n", rc);
8994             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
8995             break;
8996         }
8997
8998         if (num_allocated != 1) { /* possible? */
8999             BLOGE(sc, "MSI allocation is not 1!\n");
9000             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9001             pci_release_msi(sc->dev);
9002             break;
9003         }
9004
9005         BLOGI(sc, "MSI vectors Requested %d and Allocated %d\n",
9006               num_requested, num_allocated);
9007
9008         /* best effort so use the number of vectors allocated to us */
9009         sc->intr_count = num_allocated;
9010         sc->num_queues = num_allocated;
9011
9012         rid = 1; /* initial resource identifier */
9013
9014         sc->intr[0].rid = rid;
9015
9016         if ((sc->intr[0].resource =
9017              bus_alloc_resource_any(sc->dev,
9018                                     SYS_RES_IRQ,
9019                                     &sc->intr[0].rid,
9020                                     RF_ACTIVE)) == NULL) {
9021             BLOGE(sc, "Failed to map MSI[0] (rid=%d)!\n", rid);
9022             sc->intr_count = 0;
9023             sc->num_queues = 0;
9024             sc->interrupt_mode = INTR_MODE_INTX; /* try INTx next */
9025             pci_release_msi(sc->dev);
9026             break;
9027         }
9028
9029         BLOGD(sc, DBG_LOAD, "Mapped MSI[0] (rid=%d)\n", rid);
9030     } while (0);
9031
9032     do { /* try allocating INTx vector resources */
9033         if (sc->interrupt_mode != INTR_MODE_INTX) {
9034             break;
9035         }
9036
9037         BLOGD(sc, DBG_LOAD, "Requesting legacy INTx interrupt\n");
9038
9039         /* only one vector for INTx */
9040         sc->intr_count = 1;
9041         sc->num_queues = 1;
9042
9043         rid = 0; /* initial resource identifier */
9044
9045         sc->intr[0].rid = rid;
9046
9047         if ((sc->intr[0].resource =
9048              bus_alloc_resource_any(sc->dev,
9049                                     SYS_RES_IRQ,
9050                                     &sc->intr[0].rid,
9051                                     (RF_ACTIVE | RF_SHAREABLE))) == NULL) {
9052             BLOGE(sc, "Failed to map INTx (rid=%d)!\n", rid);
9053             sc->intr_count = 0;
9054             sc->num_queues = 0;
9055             sc->interrupt_mode = -1; /* Failed! */
9056             break;
9057         }
9058
9059         BLOGD(sc, DBG_LOAD, "Mapped INTx (rid=%d)\n", rid);
9060     } while (0);
9061
9062     if (sc->interrupt_mode == -1) {
9063         BLOGE(sc, "Interrupt Allocation: FAILED!!!\n");
9064         rc = 1;
9065     } else {
9066         BLOGD(sc, DBG_LOAD,
9067               "Interrupt Allocation: interrupt_mode=%d, num_queues=%d\n",
9068               sc->interrupt_mode, sc->num_queues);
9069         rc = 0;
9070     }
9071
9072     return (rc);
9073 }
9074
9075 static void
9076 bxe_interrupt_detach(struct bxe_softc *sc)
9077 {
9078     struct bxe_fastpath *fp;
9079     int i;
9080
9081     /* release interrupt resources */
9082     for (i = 0; i < sc->intr_count; i++) {
9083         if (sc->intr[i].resource && sc->intr[i].tag) {
9084             BLOGD(sc, DBG_LOAD, "Disabling interrupt vector %d\n", i);
9085             bus_teardown_intr(sc->dev, sc->intr[i].resource, sc->intr[i].tag);
9086         }
9087     }
9088
9089     for (i = 0; i < sc->num_queues; i++) {
9090         fp = &sc->fp[i];
9091         if (fp->tq) {
9092             taskqueue_drain(fp->tq, &fp->tq_task);
9093             taskqueue_drain(fp->tq, &fp->tx_task);
9094             while (taskqueue_cancel_timeout(fp->tq, &fp->tx_timeout_task,
9095                 NULL))
9096                 taskqueue_drain_timeout(fp->tq, &fp->tx_timeout_task);
9097             taskqueue_free(fp->tq);
9098             fp->tq = NULL;
9099         }
9100     }
9101
9102
9103     if (sc->sp_tq) {
9104         taskqueue_drain(sc->sp_tq, &sc->sp_tq_task);
9105         taskqueue_free(sc->sp_tq);
9106         sc->sp_tq = NULL;
9107     }
9108 }
9109
9110 /*
9111  * Enables interrupts and attach to the ISR.
9112  *
9113  * When using multiple MSI/MSI-X vectors the first vector
9114  * is used for slowpath operations while all remaining
9115  * vectors are used for fastpath operations.  If only a
9116  * single MSI/MSI-X vector is used (SINGLE_ISR) then the
9117  * ISR must look for both slowpath and fastpath completions.
9118  */
9119 static int
9120 bxe_interrupt_attach(struct bxe_softc *sc)
9121 {
9122     struct bxe_fastpath *fp;
9123     int rc = 0;
9124     int i;
9125
9126     snprintf(sc->sp_tq_name, sizeof(sc->sp_tq_name),
9127              "bxe%d_sp_tq", sc->unit);
9128     TASK_INIT(&sc->sp_tq_task, 0, bxe_handle_sp_tq, sc);
9129     sc->sp_tq = taskqueue_create(sc->sp_tq_name, M_NOWAIT,
9130                                  taskqueue_thread_enqueue,
9131                                  &sc->sp_tq);
9132     taskqueue_start_threads(&sc->sp_tq, 1, PWAIT, /* lower priority */
9133                             "%s", sc->sp_tq_name);
9134
9135
9136     for (i = 0; i < sc->num_queues; i++) {
9137         fp = &sc->fp[i];
9138         snprintf(fp->tq_name, sizeof(fp->tq_name),
9139                  "bxe%d_fp%d_tq", sc->unit, i);
9140         TASK_INIT(&fp->tq_task, 0, bxe_handle_fp_tq, fp);
9141         TASK_INIT(&fp->tx_task, 0, bxe_tx_mq_start_deferred, fp);
9142         fp->tq = taskqueue_create(fp->tq_name, M_NOWAIT,
9143                                   taskqueue_thread_enqueue,
9144                                   &fp->tq);
9145         TIMEOUT_TASK_INIT(fp->tq, &fp->tx_timeout_task, 0,
9146                           bxe_tx_mq_start_deferred, fp);
9147         taskqueue_start_threads(&fp->tq, 1, PI_NET, /* higher priority */
9148                                 "%s", fp->tq_name);
9149     }
9150
9151     /* setup interrupt handlers */
9152     if (sc->interrupt_mode == INTR_MODE_MSIX) {
9153         BLOGD(sc, DBG_LOAD, "Enabling slowpath MSI-X[0] vector\n");
9154
9155         /*
9156          * Setup the interrupt handler. Note that we pass the driver instance
9157          * to the interrupt handler for the slowpath.
9158          */
9159         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9160                                  (INTR_TYPE_NET | INTR_MPSAFE),
9161                                  NULL, bxe_intr_sp, sc,
9162                                  &sc->intr[0].tag)) != 0) {
9163             BLOGE(sc, "Failed to allocate MSI-X[0] vector (%d)\n", rc);
9164             goto bxe_interrupt_attach_exit;
9165         }
9166
9167         bus_describe_intr(sc->dev, sc->intr[0].resource,
9168                           sc->intr[0].tag, "sp");
9169
9170         /* bus_bind_intr(sc->dev, sc->intr[0].resource, 0); */
9171
9172         /* initialize the fastpath vectors (note the first was used for sp) */
9173         for (i = 0; i < sc->num_queues; i++) {
9174             fp = &sc->fp[i];
9175             BLOGD(sc, DBG_LOAD, "Enabling MSI-X[%d] vector\n", (i + 1));
9176
9177             /*
9178              * Setup the interrupt handler. Note that we pass the
9179              * fastpath context to the interrupt handler in this
9180              * case.
9181              */
9182             if ((rc = bus_setup_intr(sc->dev, sc->intr[i + 1].resource,
9183                                      (INTR_TYPE_NET | INTR_MPSAFE),
9184                                      NULL, bxe_intr_fp, fp,
9185                                      &sc->intr[i + 1].tag)) != 0) {
9186                 BLOGE(sc, "Failed to allocate MSI-X[%d] vector (%d)\n",
9187                       (i + 1), rc);
9188                 goto bxe_interrupt_attach_exit;
9189             }
9190
9191             bus_describe_intr(sc->dev, sc->intr[i + 1].resource,
9192                               sc->intr[i + 1].tag, "fp%02d", i);
9193
9194             /* bind the fastpath instance to a cpu */
9195             if (sc->num_queues > 1) {
9196                 bus_bind_intr(sc->dev, sc->intr[i + 1].resource, i);
9197             }
9198
9199             fp->state = BXE_FP_STATE_IRQ;
9200         }
9201     } else if (sc->interrupt_mode == INTR_MODE_MSI) {
9202         BLOGD(sc, DBG_LOAD, "Enabling MSI[0] vector\n");
9203
9204         /*
9205          * Setup the interrupt handler. Note that we pass the
9206          * driver instance to the interrupt handler which
9207          * will handle both the slowpath and fastpath.
9208          */
9209         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9210                                  (INTR_TYPE_NET | INTR_MPSAFE),
9211                                  NULL, bxe_intr_legacy, sc,
9212                                  &sc->intr[0].tag)) != 0) {
9213             BLOGE(sc, "Failed to allocate MSI[0] vector (%d)\n", rc);
9214             goto bxe_interrupt_attach_exit;
9215         }
9216
9217     } else { /* (sc->interrupt_mode == INTR_MODE_INTX) */
9218         BLOGD(sc, DBG_LOAD, "Enabling INTx interrupts\n");
9219
9220         /*
9221          * Setup the interrupt handler. Note that we pass the
9222          * driver instance to the interrupt handler which
9223          * will handle both the slowpath and fastpath.
9224          */
9225         if ((rc = bus_setup_intr(sc->dev, sc->intr[0].resource,
9226                                  (INTR_TYPE_NET | INTR_MPSAFE),
9227                                  NULL, bxe_intr_legacy, sc,
9228                                  &sc->intr[0].tag)) != 0) {
9229             BLOGE(sc, "Failed to allocate INTx interrupt (%d)\n", rc);
9230             goto bxe_interrupt_attach_exit;
9231         }
9232     }
9233
9234 bxe_interrupt_attach_exit:
9235
9236     return (rc);
9237 }
9238
9239 static int  bxe_init_hw_common_chip(struct bxe_softc *sc);
9240 static int  bxe_init_hw_common(struct bxe_softc *sc);
9241 static int  bxe_init_hw_port(struct bxe_softc *sc);
9242 static int  bxe_init_hw_func(struct bxe_softc *sc);
9243 static void bxe_reset_common(struct bxe_softc *sc);
9244 static void bxe_reset_port(struct bxe_softc *sc);
9245 static void bxe_reset_func(struct bxe_softc *sc);
9246 static int  bxe_gunzip_init(struct bxe_softc *sc);
9247 static void bxe_gunzip_end(struct bxe_softc *sc);
9248 static int  bxe_init_firmware(struct bxe_softc *sc);
9249 static void bxe_release_firmware(struct bxe_softc *sc);
9250
9251 static struct
9252 ecore_func_sp_drv_ops bxe_func_sp_drv = {
9253     .init_hw_cmn_chip = bxe_init_hw_common_chip,
9254     .init_hw_cmn      = bxe_init_hw_common,
9255     .init_hw_port     = bxe_init_hw_port,
9256     .init_hw_func     = bxe_init_hw_func,
9257
9258     .reset_hw_cmn     = bxe_reset_common,
9259     .reset_hw_port    = bxe_reset_port,
9260     .reset_hw_func    = bxe_reset_func,
9261
9262     .gunzip_init      = bxe_gunzip_init,
9263     .gunzip_end       = bxe_gunzip_end,
9264
9265     .init_fw          = bxe_init_firmware,
9266     .release_fw       = bxe_release_firmware,
9267 };
9268
9269 static void
9270 bxe_init_func_obj(struct bxe_softc *sc)
9271 {
9272     sc->dmae_ready = 0;
9273
9274     ecore_init_func_obj(sc,
9275                         &sc->func_obj,
9276                         BXE_SP(sc, func_rdata),
9277                         BXE_SP_MAPPING(sc, func_rdata),
9278                         BXE_SP(sc, func_afex_rdata),
9279                         BXE_SP_MAPPING(sc, func_afex_rdata),
9280                         &bxe_func_sp_drv);
9281 }
9282
9283 static int
9284 bxe_init_hw(struct bxe_softc *sc,
9285             uint32_t         load_code)
9286 {
9287     struct ecore_func_state_params func_params = { NULL };
9288     int rc;
9289
9290     /* prepare the parameters for function state transitions */
9291     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
9292
9293     func_params.f_obj = &sc->func_obj;
9294     func_params.cmd = ECORE_F_CMD_HW_INIT;
9295
9296     func_params.params.hw_init.load_phase = load_code;
9297
9298     /*
9299      * Via a plethora of function pointers, we will eventually reach
9300      * bxe_init_hw_common(), bxe_init_hw_port(), or bxe_init_hw_func().
9301      */
9302     rc = ecore_func_state_change(sc, &func_params);
9303
9304     return (rc);
9305 }
9306
9307 static void
9308 bxe_fill(struct bxe_softc *sc,
9309          uint32_t         addr,
9310          int              fill,
9311          uint32_t         len)
9312 {
9313     uint32_t i;
9314
9315     if (!(len % 4) && !(addr % 4)) {
9316         for (i = 0; i < len; i += 4) {
9317             REG_WR(sc, (addr + i), fill);
9318         }
9319     } else {
9320         for (i = 0; i < len; i++) {
9321             REG_WR8(sc, (addr + i), fill);
9322         }
9323     }
9324 }
9325
9326 /* writes FP SP data to FW - data_size in dwords */
9327 static void
9328 bxe_wr_fp_sb_data(struct bxe_softc *sc,
9329                   int              fw_sb_id,
9330                   uint32_t         *sb_data_p,
9331                   uint32_t         data_size)
9332 {
9333     int index;
9334
9335     for (index = 0; index < data_size; index++) {
9336         REG_WR(sc,
9337                (BAR_CSTRORM_INTMEM +
9338                 CSTORM_STATUS_BLOCK_DATA_OFFSET(fw_sb_id) +
9339                 (sizeof(uint32_t) * index)),
9340                *(sb_data_p + index));
9341     }
9342 }
9343
9344 static void
9345 bxe_zero_fp_sb(struct bxe_softc *sc,
9346                int              fw_sb_id)
9347 {
9348     struct hc_status_block_data_e2 sb_data_e2;
9349     struct hc_status_block_data_e1x sb_data_e1x;
9350     uint32_t *sb_data_p;
9351     uint32_t data_size = 0;
9352
9353     if (!CHIP_IS_E1x(sc)) {
9354         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9355         sb_data_e2.common.state = SB_DISABLED;
9356         sb_data_e2.common.p_func.vf_valid = FALSE;
9357         sb_data_p = (uint32_t *)&sb_data_e2;
9358         data_size = (sizeof(struct hc_status_block_data_e2) /
9359                      sizeof(uint32_t));
9360     } else {
9361         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9362         sb_data_e1x.common.state = SB_DISABLED;
9363         sb_data_e1x.common.p_func.vf_valid = FALSE;
9364         sb_data_p = (uint32_t *)&sb_data_e1x;
9365         data_size = (sizeof(struct hc_status_block_data_e1x) /
9366                      sizeof(uint32_t));
9367     }
9368
9369     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9370
9371     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_STATUS_BLOCK_OFFSET(fw_sb_id)),
9372              0, CSTORM_STATUS_BLOCK_SIZE);
9373     bxe_fill(sc, (BAR_CSTRORM_INTMEM + CSTORM_SYNC_BLOCK_OFFSET(fw_sb_id)),
9374              0, CSTORM_SYNC_BLOCK_SIZE);
9375 }
9376
9377 static void
9378 bxe_wr_sp_sb_data(struct bxe_softc               *sc,
9379                   struct hc_sp_status_block_data *sp_sb_data)
9380 {
9381     int i;
9382
9383     for (i = 0;
9384          i < (sizeof(struct hc_sp_status_block_data) / sizeof(uint32_t));
9385          i++) {
9386         REG_WR(sc,
9387                (BAR_CSTRORM_INTMEM +
9388                 CSTORM_SP_STATUS_BLOCK_DATA_OFFSET(SC_FUNC(sc)) +
9389                 (i * sizeof(uint32_t))),
9390                *((uint32_t *)sp_sb_data + i));
9391     }
9392 }
9393
9394 static void
9395 bxe_zero_sp_sb(struct bxe_softc *sc)
9396 {
9397     struct hc_sp_status_block_data sp_sb_data;
9398
9399     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9400
9401     sp_sb_data.state           = SB_DISABLED;
9402     sp_sb_data.p_func.vf_valid = FALSE;
9403
9404     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9405
9406     bxe_fill(sc,
9407              (BAR_CSTRORM_INTMEM +
9408               CSTORM_SP_STATUS_BLOCK_OFFSET(SC_FUNC(sc))),
9409               0, CSTORM_SP_STATUS_BLOCK_SIZE);
9410     bxe_fill(sc,
9411              (BAR_CSTRORM_INTMEM +
9412               CSTORM_SP_SYNC_BLOCK_OFFSET(SC_FUNC(sc))),
9413               0, CSTORM_SP_SYNC_BLOCK_SIZE);
9414 }
9415
9416 static void
9417 bxe_setup_ndsb_state_machine(struct hc_status_block_sm *hc_sm,
9418                              int                       igu_sb_id,
9419                              int                       igu_seg_id)
9420 {
9421     hc_sm->igu_sb_id      = igu_sb_id;
9422     hc_sm->igu_seg_id     = igu_seg_id;
9423     hc_sm->timer_value    = 0xFF;
9424     hc_sm->time_to_expire = 0xFFFFFFFF;
9425 }
9426
9427 static void
9428 bxe_map_sb_state_machines(struct hc_index_data *index_data)
9429 {
9430     /* zero out state machine indices */
9431
9432     /* rx indices */
9433     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags &= ~HC_INDEX_DATA_SM_ID;
9434
9435     /* tx indices */
9436     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags      &= ~HC_INDEX_DATA_SM_ID;
9437     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags &= ~HC_INDEX_DATA_SM_ID;
9438     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags &= ~HC_INDEX_DATA_SM_ID;
9439     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags &= ~HC_INDEX_DATA_SM_ID;
9440
9441     /* map indices */
9442
9443     /* rx indices */
9444     index_data[HC_INDEX_ETH_RX_CQ_CONS].flags |=
9445         (SM_RX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9446
9447     /* tx indices */
9448     index_data[HC_INDEX_OOO_TX_CQ_CONS].flags |=
9449         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9450     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS0].flags |=
9451         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9452     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS1].flags |=
9453         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9454     index_data[HC_INDEX_ETH_TX_CQ_CONS_COS2].flags |=
9455         (SM_TX_ID << HC_INDEX_DATA_SM_ID_SHIFT);
9456 }
9457
9458 static void
9459 bxe_init_sb(struct bxe_softc *sc,
9460             bus_addr_t       busaddr,
9461             int              vfid,
9462             uint8_t          vf_valid,
9463             int              fw_sb_id,
9464             int              igu_sb_id)
9465 {
9466     struct hc_status_block_data_e2  sb_data_e2;
9467     struct hc_status_block_data_e1x sb_data_e1x;
9468     struct hc_status_block_sm       *hc_sm_p;
9469     uint32_t *sb_data_p;
9470     int igu_seg_id;
9471     int data_size;
9472
9473     if (CHIP_INT_MODE_IS_BC(sc)) {
9474         igu_seg_id = HC_SEG_ACCESS_NORM;
9475     } else {
9476         igu_seg_id = IGU_SEG_ACCESS_NORM;
9477     }
9478
9479     bxe_zero_fp_sb(sc, fw_sb_id);
9480
9481     if (!CHIP_IS_E1x(sc)) {
9482         memset(&sb_data_e2, 0, sizeof(struct hc_status_block_data_e2));
9483         sb_data_e2.common.state = SB_ENABLED;
9484         sb_data_e2.common.p_func.pf_id = SC_FUNC(sc);
9485         sb_data_e2.common.p_func.vf_id = vfid;
9486         sb_data_e2.common.p_func.vf_valid = vf_valid;
9487         sb_data_e2.common.p_func.vnic_id = SC_VN(sc);
9488         sb_data_e2.common.same_igu_sb_1b = TRUE;
9489         sb_data_e2.common.host_sb_addr.hi = U64_HI(busaddr);
9490         sb_data_e2.common.host_sb_addr.lo = U64_LO(busaddr);
9491         hc_sm_p = sb_data_e2.common.state_machine;
9492         sb_data_p = (uint32_t *)&sb_data_e2;
9493         data_size = (sizeof(struct hc_status_block_data_e2) /
9494                      sizeof(uint32_t));
9495         bxe_map_sb_state_machines(sb_data_e2.index_data);
9496     } else {
9497         memset(&sb_data_e1x, 0, sizeof(struct hc_status_block_data_e1x));
9498         sb_data_e1x.common.state = SB_ENABLED;
9499         sb_data_e1x.common.p_func.pf_id = SC_FUNC(sc);
9500         sb_data_e1x.common.p_func.vf_id = 0xff;
9501         sb_data_e1x.common.p_func.vf_valid = FALSE;
9502         sb_data_e1x.common.p_func.vnic_id = SC_VN(sc);
9503         sb_data_e1x.common.same_igu_sb_1b = TRUE;
9504         sb_data_e1x.common.host_sb_addr.hi = U64_HI(busaddr);
9505         sb_data_e1x.common.host_sb_addr.lo = U64_LO(busaddr);
9506         hc_sm_p = sb_data_e1x.common.state_machine;
9507         sb_data_p = (uint32_t *)&sb_data_e1x;
9508         data_size = (sizeof(struct hc_status_block_data_e1x) /
9509                      sizeof(uint32_t));
9510         bxe_map_sb_state_machines(sb_data_e1x.index_data);
9511     }
9512
9513     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_RX_ID], igu_sb_id, igu_seg_id);
9514     bxe_setup_ndsb_state_machine(&hc_sm_p[SM_TX_ID], igu_sb_id, igu_seg_id);
9515
9516     BLOGD(sc, DBG_LOAD, "Init FW SB %d\n", fw_sb_id);
9517
9518     /* write indices to HW - PCI guarantees endianity of regpairs */
9519     bxe_wr_fp_sb_data(sc, fw_sb_id, sb_data_p, data_size);
9520 }
9521
9522 static inline uint8_t
9523 bxe_fp_qzone_id(struct bxe_fastpath *fp)
9524 {
9525     if (CHIP_IS_E1x(fp->sc)) {
9526         return (fp->cl_id + SC_PORT(fp->sc) * ETH_MAX_RX_CLIENTS_E1H);
9527     } else {
9528         return (fp->cl_id);
9529     }
9530 }
9531
9532 static inline uint32_t
9533 bxe_rx_ustorm_prods_offset(struct bxe_softc    *sc,
9534                            struct bxe_fastpath *fp)
9535 {
9536     uint32_t offset = BAR_USTRORM_INTMEM;
9537
9538     if (!CHIP_IS_E1x(sc)) {
9539         offset += USTORM_RX_PRODS_E2_OFFSET(fp->cl_qzone_id);
9540     } else {
9541         offset += USTORM_RX_PRODS_E1X_OFFSET(SC_PORT(sc), fp->cl_id);
9542     }
9543
9544     return (offset);
9545 }
9546
9547 static void
9548 bxe_init_eth_fp(struct bxe_softc *sc,
9549                 int              idx)
9550 {
9551     struct bxe_fastpath *fp = &sc->fp[idx];
9552     uint32_t cids[ECORE_MULTI_TX_COS] = { 0 };
9553     unsigned long q_type = 0;
9554     int cos;
9555
9556     fp->sc    = sc;
9557     fp->index = idx;
9558
9559     fp->igu_sb_id = (sc->igu_base_sb + idx + CNIC_SUPPORT(sc));
9560     fp->fw_sb_id = (sc->base_fw_ndsb + idx + CNIC_SUPPORT(sc));
9561
9562     fp->cl_id = (CHIP_IS_E1x(sc)) ?
9563                     (SC_L_ID(sc) + idx) :
9564                     /* want client ID same as IGU SB ID for non-E1 */
9565                     fp->igu_sb_id;
9566     fp->cl_qzone_id = bxe_fp_qzone_id(fp);
9567
9568     /* setup sb indices */
9569     if (!CHIP_IS_E1x(sc)) {
9570         fp->sb_index_values  = fp->status_block.e2_sb->sb.index_values;
9571         fp->sb_running_index = fp->status_block.e2_sb->sb.running_index;
9572     } else {
9573         fp->sb_index_values  = fp->status_block.e1x_sb->sb.index_values;
9574         fp->sb_running_index = fp->status_block.e1x_sb->sb.running_index;
9575     }
9576
9577     /* init shortcut */
9578     fp->ustorm_rx_prods_offset = bxe_rx_ustorm_prods_offset(sc, fp);
9579
9580     fp->rx_cq_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_RX_CQ_CONS];
9581
9582     /*
9583      * XXX If multiple CoS is ever supported then each fastpath structure
9584      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
9585      */
9586     for (cos = 0; cos < sc->max_cos; cos++) {
9587         cids[cos] = idx;
9588     }
9589     fp->tx_cons_sb = &fp->sb_index_values[HC_INDEX_ETH_TX_CQ_CONS_COS0];
9590
9591     /* nothing more for a VF to do */
9592     if (IS_VF(sc)) {
9593         return;
9594     }
9595
9596     bxe_init_sb(sc, fp->sb_dma.paddr, BXE_VF_ID_INVALID, FALSE,
9597                 fp->fw_sb_id, fp->igu_sb_id);
9598
9599     bxe_update_fp_sb_idx(fp);
9600
9601     /* Configure Queue State object */
9602     bit_set(&q_type, ECORE_Q_TYPE_HAS_RX);
9603     bit_set(&q_type, ECORE_Q_TYPE_HAS_TX);
9604
9605     ecore_init_queue_obj(sc,
9606                          &sc->sp_objs[idx].q_obj,
9607                          fp->cl_id,
9608                          cids,
9609                          sc->max_cos,
9610                          SC_FUNC(sc),
9611                          BXE_SP(sc, q_rdata),
9612                          BXE_SP_MAPPING(sc, q_rdata),
9613                          q_type);
9614
9615     /* configure classification DBs */
9616     ecore_init_mac_obj(sc,
9617                        &sc->sp_objs[idx].mac_obj,
9618                        fp->cl_id,
9619                        idx,
9620                        SC_FUNC(sc),
9621                        BXE_SP(sc, mac_rdata),
9622                        BXE_SP_MAPPING(sc, mac_rdata),
9623                        ECORE_FILTER_MAC_PENDING,
9624                        &sc->sp_state,
9625                        ECORE_OBJ_TYPE_RX_TX,
9626                        &sc->macs_pool);
9627
9628     BLOGD(sc, DBG_LOAD, "fp[%d]: sb=%p cl_id=%d fw_sb=%d igu_sb=%d\n",
9629           idx, fp->status_block.e2_sb, fp->cl_id, fp->fw_sb_id, fp->igu_sb_id);
9630 }
9631
9632 static inline void
9633 bxe_update_rx_prod(struct bxe_softc    *sc,
9634                    struct bxe_fastpath *fp,
9635                    uint16_t            rx_bd_prod,
9636                    uint16_t            rx_cq_prod,
9637                    uint16_t            rx_sge_prod)
9638 {
9639     struct ustorm_eth_rx_producers rx_prods = { 0 };
9640     uint32_t i;
9641
9642     /* update producers */
9643     rx_prods.bd_prod  = rx_bd_prod;
9644     rx_prods.cqe_prod = rx_cq_prod;
9645     rx_prods.sge_prod = rx_sge_prod;
9646
9647     /*
9648      * Make sure that the BD and SGE data is updated before updating the
9649      * producers since FW might read the BD/SGE right after the producer
9650      * is updated.
9651      * This is only applicable for weak-ordered memory model archs such
9652      * as IA-64. The following barrier is also mandatory since FW will
9653      * assumes BDs must have buffers.
9654      */
9655     wmb();
9656
9657     for (i = 0; i < (sizeof(rx_prods) / 4); i++) {
9658         REG_WR(sc,
9659                (fp->ustorm_rx_prods_offset + (i * 4)),
9660                ((uint32_t *)&rx_prods)[i]);
9661     }
9662
9663     wmb(); /* keep prod updates ordered */
9664
9665     BLOGD(sc, DBG_RX,
9666           "RX fp[%d]: wrote prods bd_prod=%u cqe_prod=%u sge_prod=%u\n",
9667           fp->index, rx_bd_prod, rx_cq_prod, rx_sge_prod);
9668 }
9669
9670 static void
9671 bxe_init_rx_rings(struct bxe_softc *sc)
9672 {
9673     struct bxe_fastpath *fp;
9674     int i;
9675
9676     for (i = 0; i < sc->num_queues; i++) {
9677         fp = &sc->fp[i];
9678
9679         fp->rx_bd_cons = 0;
9680
9681         /*
9682          * Activate the BD ring...
9683          * Warning, this will generate an interrupt (to the TSTORM)
9684          * so this can only be done after the chip is initialized
9685          */
9686         bxe_update_rx_prod(sc, fp,
9687                            fp->rx_bd_prod,
9688                            fp->rx_cq_prod,
9689                            fp->rx_sge_prod);
9690
9691         if (i != 0) {
9692             continue;
9693         }
9694
9695         if (CHIP_IS_E1(sc)) {
9696             REG_WR(sc,
9697                    (BAR_USTRORM_INTMEM +
9698                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc))),
9699                    U64_LO(fp->rcq_dma.paddr));
9700             REG_WR(sc,
9701                    (BAR_USTRORM_INTMEM +
9702                     USTORM_MEM_WORKAROUND_ADDRESS_OFFSET(SC_FUNC(sc)) + 4),
9703                    U64_HI(fp->rcq_dma.paddr));
9704         }
9705     }
9706 }
9707
9708 static void
9709 bxe_init_tx_ring_one(struct bxe_fastpath *fp)
9710 {
9711     SET_FLAG(fp->tx_db.data.header.data, DOORBELL_HDR_T_DB_TYPE, 1);
9712     fp->tx_db.data.zero_fill1 = 0;
9713     fp->tx_db.data.prod = 0;
9714
9715     fp->tx_pkt_prod = 0;
9716     fp->tx_pkt_cons = 0;
9717     fp->tx_bd_prod = 0;
9718     fp->tx_bd_cons = 0;
9719     fp->eth_q_stats.tx_pkts = 0;
9720 }
9721
9722 static inline void
9723 bxe_init_tx_rings(struct bxe_softc *sc)
9724 {
9725     int i;
9726
9727     for (i = 0; i < sc->num_queues; i++) {
9728         bxe_init_tx_ring_one(&sc->fp[i]);
9729     }
9730 }
9731
9732 static void
9733 bxe_init_def_sb(struct bxe_softc *sc)
9734 {
9735     struct host_sp_status_block *def_sb = sc->def_sb;
9736     bus_addr_t mapping = sc->def_sb_dma.paddr;
9737     int igu_sp_sb_index;
9738     int igu_seg_id;
9739     int port = SC_PORT(sc);
9740     int func = SC_FUNC(sc);
9741     int reg_offset, reg_offset_en5;
9742     uint64_t section;
9743     int index, sindex;
9744     struct hc_sp_status_block_data sp_sb_data;
9745
9746     memset(&sp_sb_data, 0, sizeof(struct hc_sp_status_block_data));
9747
9748     if (CHIP_INT_MODE_IS_BC(sc)) {
9749         igu_sp_sb_index = DEF_SB_IGU_ID;
9750         igu_seg_id = HC_SEG_ACCESS_DEF;
9751     } else {
9752         igu_sp_sb_index = sc->igu_dsb_id;
9753         igu_seg_id = IGU_SEG_ACCESS_DEF;
9754     }
9755
9756     /* attentions */
9757     section = ((uint64_t)mapping +
9758                offsetof(struct host_sp_status_block, atten_status_block));
9759     def_sb->atten_status_block.status_block_id = igu_sp_sb_index;
9760     sc->attn_state = 0;
9761
9762     reg_offset = (port) ?
9763                      MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
9764                      MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0;
9765     reg_offset_en5 = (port) ?
9766                          MISC_REG_AEU_ENABLE5_FUNC_1_OUT_0 :
9767                          MISC_REG_AEU_ENABLE5_FUNC_0_OUT_0;
9768
9769     for (index = 0; index < MAX_DYNAMIC_ATTN_GRPS; index++) {
9770         /* take care of sig[0]..sig[4] */
9771         for (sindex = 0; sindex < 4; sindex++) {
9772             sc->attn_group[index].sig[sindex] =
9773                 REG_RD(sc, (reg_offset + (sindex * 0x4) + (0x10 * index)));
9774         }
9775
9776         if (!CHIP_IS_E1x(sc)) {
9777             /*
9778              * enable5 is separate from the rest of the registers,
9779              * and the address skip is 4 and not 16 between the
9780              * different groups
9781              */
9782             sc->attn_group[index].sig[4] =
9783                 REG_RD(sc, (reg_offset_en5 + (0x4 * index)));
9784         } else {
9785             sc->attn_group[index].sig[4] = 0;
9786         }
9787     }
9788
9789     if (sc->devinfo.int_block == INT_BLOCK_HC) {
9790         reg_offset = (port) ?
9791                          HC_REG_ATTN_MSG1_ADDR_L :
9792                          HC_REG_ATTN_MSG0_ADDR_L;
9793         REG_WR(sc, reg_offset, U64_LO(section));
9794         REG_WR(sc, (reg_offset + 4), U64_HI(section));
9795     } else if (!CHIP_IS_E1x(sc)) {
9796         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_L, U64_LO(section));
9797         REG_WR(sc, IGU_REG_ATTN_MSG_ADDR_H, U64_HI(section));
9798     }
9799
9800     section = ((uint64_t)mapping +
9801                offsetof(struct host_sp_status_block, sp_sb));
9802
9803     bxe_zero_sp_sb(sc);
9804
9805     /* PCI guarantees endianity of regpair */
9806     sp_sb_data.state           = SB_ENABLED;
9807     sp_sb_data.host_sb_addr.lo = U64_LO(section);
9808     sp_sb_data.host_sb_addr.hi = U64_HI(section);
9809     sp_sb_data.igu_sb_id       = igu_sp_sb_index;
9810     sp_sb_data.igu_seg_id      = igu_seg_id;
9811     sp_sb_data.p_func.pf_id    = func;
9812     sp_sb_data.p_func.vnic_id  = SC_VN(sc);
9813     sp_sb_data.p_func.vf_id    = 0xff;
9814
9815     bxe_wr_sp_sb_data(sc, &sp_sb_data);
9816
9817     bxe_ack_sb(sc, sc->igu_dsb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
9818 }
9819
9820 static void
9821 bxe_init_sp_ring(struct bxe_softc *sc)
9822 {
9823     atomic_store_rel_long(&sc->cq_spq_left, MAX_SPQ_PENDING);
9824     sc->spq_prod_idx = 0;
9825     sc->dsb_sp_prod = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_ETH_DEF_CONS];
9826     sc->spq_prod_bd = sc->spq;
9827     sc->spq_last_bd = (sc->spq_prod_bd + MAX_SP_DESC_CNT);
9828 }
9829
9830 static void
9831 bxe_init_eq_ring(struct bxe_softc *sc)
9832 {
9833     union event_ring_elem *elem;
9834     int i;
9835
9836     for (i = 1; i <= NUM_EQ_PAGES; i++) {
9837         elem = &sc->eq[EQ_DESC_CNT_PAGE * i - 1];
9838
9839         elem->next_page.addr.hi = htole32(U64_HI(sc->eq_dma.paddr +
9840                                                  BCM_PAGE_SIZE *
9841                                                  (i % NUM_EQ_PAGES)));
9842         elem->next_page.addr.lo = htole32(U64_LO(sc->eq_dma.paddr +
9843                                                  BCM_PAGE_SIZE *
9844                                                  (i % NUM_EQ_PAGES)));
9845     }
9846
9847     sc->eq_cons    = 0;
9848     sc->eq_prod    = NUM_EQ_DESC;
9849     sc->eq_cons_sb = &sc->def_sb->sp_sb.index_values[HC_SP_INDEX_EQ_CONS];
9850
9851     atomic_store_rel_long(&sc->eq_spq_left,
9852                           (min((MAX_SP_DESC_CNT - MAX_SPQ_PENDING),
9853                                NUM_EQ_DESC) - 1));
9854 }
9855
9856 static void
9857 bxe_init_internal_common(struct bxe_softc *sc)
9858 {
9859     int i;
9860
9861     /*
9862      * Zero this manually as its initialization is currently missing
9863      * in the initTool.
9864      */
9865     for (i = 0; i < (USTORM_AGG_DATA_SIZE >> 2); i++) {
9866         REG_WR(sc,
9867                (BAR_USTRORM_INTMEM + USTORM_AGG_DATA_OFFSET + (i * 4)),
9868                0);
9869     }
9870
9871     if (!CHIP_IS_E1x(sc)) {
9872         REG_WR8(sc, (BAR_CSTRORM_INTMEM + CSTORM_IGU_MODE_OFFSET),
9873                 CHIP_INT_MODE_IS_BC(sc) ? HC_IGU_BC_MODE : HC_IGU_NBC_MODE);
9874     }
9875 }
9876
9877 static void
9878 bxe_init_internal(struct bxe_softc *sc,
9879                   uint32_t         load_code)
9880 {
9881     switch (load_code) {
9882     case FW_MSG_CODE_DRV_LOAD_COMMON:
9883     case FW_MSG_CODE_DRV_LOAD_COMMON_CHIP:
9884         bxe_init_internal_common(sc);
9885         /* no break */
9886
9887     case FW_MSG_CODE_DRV_LOAD_PORT:
9888         /* nothing to do */
9889         /* no break */
9890
9891     case FW_MSG_CODE_DRV_LOAD_FUNCTION:
9892         /* internal memory per function is initialized inside bxe_pf_init */
9893         break;
9894
9895     default:
9896         BLOGE(sc, "Unknown load_code (0x%x) from MCP\n", load_code);
9897         break;
9898     }
9899 }
9900
9901 static void
9902 storm_memset_func_cfg(struct bxe_softc                         *sc,
9903                       struct tstorm_eth_function_common_config *tcfg,
9904                       uint16_t                                  abs_fid)
9905 {
9906     uint32_t addr;
9907     size_t size;
9908
9909     addr = (BAR_TSTRORM_INTMEM +
9910             TSTORM_FUNCTION_COMMON_CONFIG_OFFSET(abs_fid));
9911     size = sizeof(struct tstorm_eth_function_common_config);
9912     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)tcfg);
9913 }
9914
9915 static void
9916 bxe_func_init(struct bxe_softc            *sc,
9917               struct bxe_func_init_params *p)
9918 {
9919     struct tstorm_eth_function_common_config tcfg = { 0 };
9920
9921     if (CHIP_IS_E1x(sc)) {
9922         storm_memset_func_cfg(sc, &tcfg, p->func_id);
9923     }
9924
9925     /* Enable the function in the FW */
9926     storm_memset_vf_to_pf(sc, p->func_id, p->pf_id);
9927     storm_memset_func_en(sc, p->func_id, 1);
9928
9929     /* spq */
9930     if (p->func_flgs & FUNC_FLG_SPQ) {
9931         storm_memset_spq_addr(sc, p->spq_map, p->func_id);
9932         REG_WR(sc,
9933                (XSEM_REG_FAST_MEMORY + XSTORM_SPQ_PROD_OFFSET(p->func_id)),
9934                p->spq_prod);
9935     }
9936 }
9937
9938 /*
9939  * Calculates the sum of vn_min_rates.
9940  * It's needed for further normalizing of the min_rates.
9941  * Returns:
9942  *   sum of vn_min_rates.
9943  *     or
9944  *   0 - if all the min_rates are 0.
9945  * In the later case fainess algorithm should be deactivated.
9946  * If all min rates are not zero then those that are zeroes will be set to 1.
9947  */
9948 static void
9949 bxe_calc_vn_min(struct bxe_softc       *sc,
9950                 struct cmng_init_input *input)
9951 {
9952     uint32_t vn_cfg;
9953     uint32_t vn_min_rate;
9954     int all_zero = 1;
9955     int vn;
9956
9957     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
9958         vn_cfg = sc->devinfo.mf_info.mf_config[vn];
9959         vn_min_rate = (((vn_cfg & FUNC_MF_CFG_MIN_BW_MASK) >>
9960                         FUNC_MF_CFG_MIN_BW_SHIFT) * 100);
9961
9962         if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
9963             /* skip hidden VNs */
9964             vn_min_rate = 0;
9965         } else if (!vn_min_rate) {
9966             /* If min rate is zero - set it to 100 */
9967             vn_min_rate = DEF_MIN_RATE;
9968         } else {
9969             all_zero = 0;
9970         }
9971
9972         input->vnic_min_rate[vn] = vn_min_rate;
9973     }
9974
9975     /* if ETS or all min rates are zeros - disable fairness */
9976     if (BXE_IS_ETS_ENABLED(sc)) {
9977         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9978         BLOGD(sc, DBG_LOAD, "Fairness disabled (ETS)\n");
9979     } else if (all_zero) {
9980         input->flags.cmng_enables &= ~CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9981         BLOGD(sc, DBG_LOAD,
9982               "Fariness disabled (all MIN values are zeroes)\n");
9983     } else {
9984         input->flags.cmng_enables |= CMNG_FLAGS_PER_PORT_FAIRNESS_VN;
9985     }
9986 }
9987
9988 static inline uint16_t
9989 bxe_extract_max_cfg(struct bxe_softc *sc,
9990                     uint32_t         mf_cfg)
9991 {
9992     uint16_t max_cfg = ((mf_cfg & FUNC_MF_CFG_MAX_BW_MASK) >>
9993                         FUNC_MF_CFG_MAX_BW_SHIFT);
9994
9995     if (!max_cfg) {
9996         BLOGD(sc, DBG_LOAD, "Max BW configured to 0 - using 100 instead\n");
9997         max_cfg = 100;
9998     }
9999
10000     return (max_cfg);
10001 }
10002
10003 static void
10004 bxe_calc_vn_max(struct bxe_softc       *sc,
10005                 int                    vn,
10006                 struct cmng_init_input *input)
10007 {
10008     uint16_t vn_max_rate;
10009     uint32_t vn_cfg = sc->devinfo.mf_info.mf_config[vn];
10010     uint32_t max_cfg;
10011
10012     if (vn_cfg & FUNC_MF_CFG_FUNC_HIDE) {
10013         vn_max_rate = 0;
10014     } else {
10015         max_cfg = bxe_extract_max_cfg(sc, vn_cfg);
10016
10017         if (IS_MF_SI(sc)) {
10018             /* max_cfg in percents of linkspeed */
10019             vn_max_rate = ((sc->link_vars.line_speed * max_cfg) / 100);
10020         } else { /* SD modes */
10021             /* max_cfg is absolute in 100Mb units */
10022             vn_max_rate = (max_cfg * 100);
10023         }
10024     }
10025
10026     BLOGD(sc, DBG_LOAD, "vn %d: vn_max_rate %d\n", vn, vn_max_rate);
10027
10028     input->vnic_max_rate[vn] = vn_max_rate;
10029 }
10030
10031 static void
10032 bxe_cmng_fns_init(struct bxe_softc *sc,
10033                   uint8_t          read_cfg,
10034                   uint8_t          cmng_type)
10035 {
10036     struct cmng_init_input input;
10037     int vn;
10038
10039     memset(&input, 0, sizeof(struct cmng_init_input));
10040
10041     input.port_rate = sc->link_vars.line_speed;
10042
10043     if (cmng_type == CMNG_FNS_MINMAX) {
10044         /* read mf conf from shmem */
10045         if (read_cfg) {
10046             bxe_read_mf_cfg(sc);
10047         }
10048
10049         /* get VN min rate and enable fairness if not 0 */
10050         bxe_calc_vn_min(sc, &input);
10051
10052         /* get VN max rate */
10053         if (sc->port.pmf) {
10054             for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10055                 bxe_calc_vn_max(sc, vn, &input);
10056             }
10057         }
10058
10059         /* always enable rate shaping and fairness */
10060         input.flags.cmng_enables |= CMNG_FLAGS_PER_PORT_RATE_SHAPING_VN;
10061
10062         ecore_init_cmng(&input, &sc->cmng);
10063         return;
10064     }
10065
10066     /* rate shaping and fairness are disabled */
10067     BLOGD(sc, DBG_LOAD, "rate shaping and fairness have been disabled\n");
10068 }
10069
10070 static int
10071 bxe_get_cmng_fns_mode(struct bxe_softc *sc)
10072 {
10073     if (CHIP_REV_IS_SLOW(sc)) {
10074         return (CMNG_FNS_NONE);
10075     }
10076
10077     if (IS_MF(sc)) {
10078         return (CMNG_FNS_MINMAX);
10079     }
10080
10081     return (CMNG_FNS_NONE);
10082 }
10083
10084 static void
10085 storm_memset_cmng(struct bxe_softc *sc,
10086                   struct cmng_init *cmng,
10087                   uint8_t          port)
10088 {
10089     int vn;
10090     int func;
10091     uint32_t addr;
10092     size_t size;
10093
10094     addr = (BAR_XSTRORM_INTMEM +
10095             XSTORM_CMNG_PER_PORT_VARS_OFFSET(port));
10096     size = sizeof(struct cmng_struct_per_port);
10097     ecore_storm_memset_struct(sc, addr, size, (uint32_t *)&cmng->port);
10098
10099     for (vn = VN_0; vn < SC_MAX_VN_NUM(sc); vn++) {
10100         func = func_by_vn(sc, vn);
10101
10102         addr = (BAR_XSTRORM_INTMEM +
10103                 XSTORM_RATE_SHAPING_PER_VN_VARS_OFFSET(func));
10104         size = sizeof(struct rate_shaping_vars_per_vn);
10105         ecore_storm_memset_struct(sc, addr, size,
10106                                   (uint32_t *)&cmng->vnic.vnic_max_rate[vn]);
10107
10108         addr = (BAR_XSTRORM_INTMEM +
10109                 XSTORM_FAIRNESS_PER_VN_VARS_OFFSET(func));
10110         size = sizeof(struct fairness_vars_per_vn);
10111         ecore_storm_memset_struct(sc, addr, size,
10112                                   (uint32_t *)&cmng->vnic.vnic_min_rate[vn]);
10113     }
10114 }
10115
10116 static void
10117 bxe_pf_init(struct bxe_softc *sc)
10118 {
10119     struct bxe_func_init_params func_init = { 0 };
10120     struct event_ring_data eq_data = { { 0 } };
10121     uint16_t flags;
10122
10123     if (!CHIP_IS_E1x(sc)) {
10124         /* reset IGU PF statistics: MSIX + ATTN */
10125         /* PF */
10126         REG_WR(sc,
10127                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10128                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10129                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10130                0);
10131         /* ATTN */
10132         REG_WR(sc,
10133                (IGU_REG_STATISTIC_NUM_MESSAGE_SENT +
10134                 (BXE_IGU_STAS_MSG_VF_CNT * 4) +
10135                 (BXE_IGU_STAS_MSG_PF_CNT * 4) +
10136                 ((CHIP_IS_MODE_4_PORT(sc) ? SC_FUNC(sc) : SC_VN(sc)) * 4)),
10137                0);
10138     }
10139
10140     /* function setup flags */
10141     flags = (FUNC_FLG_STATS | FUNC_FLG_LEADING | FUNC_FLG_SPQ);
10142
10143     /*
10144      * This flag is relevant for E1x only.
10145      * E2 doesn't have a TPA configuration in a function level.
10146      */
10147     flags |= (sc->ifnet->if_capenable & IFCAP_LRO) ? FUNC_FLG_TPA : 0;
10148
10149     func_init.func_flgs = flags;
10150     func_init.pf_id     = SC_FUNC(sc);
10151     func_init.func_id   = SC_FUNC(sc);
10152     func_init.spq_map   = sc->spq_dma.paddr;
10153     func_init.spq_prod  = sc->spq_prod_idx;
10154
10155     bxe_func_init(sc, &func_init);
10156
10157     memset(&sc->cmng, 0, sizeof(struct cmng_struct_per_port));
10158
10159     /*
10160      * Congestion management values depend on the link rate.
10161      * There is no active link so initial link rate is set to 10Gbps.
10162      * When the link comes up the congestion management values are
10163      * re-calculated according to the actual link rate.
10164      */
10165     sc->link_vars.line_speed = SPEED_10000;
10166     bxe_cmng_fns_init(sc, TRUE, bxe_get_cmng_fns_mode(sc));
10167
10168     /* Only the PMF sets the HW */
10169     if (sc->port.pmf) {
10170         storm_memset_cmng(sc, &sc->cmng, SC_PORT(sc));
10171     }
10172
10173     /* init Event Queue - PCI bus guarantees correct endainity */
10174     eq_data.base_addr.hi = U64_HI(sc->eq_dma.paddr);
10175     eq_data.base_addr.lo = U64_LO(sc->eq_dma.paddr);
10176     eq_data.producer     = sc->eq_prod;
10177     eq_data.index_id     = HC_SP_INDEX_EQ_CONS;
10178     eq_data.sb_id        = DEF_SB_ID;
10179     storm_memset_eq_data(sc, &eq_data, SC_FUNC(sc));
10180 }
10181
10182 static void
10183 bxe_hc_int_enable(struct bxe_softc *sc)
10184 {
10185     int port = SC_PORT(sc);
10186     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10187     uint32_t val = REG_RD(sc, addr);
10188     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10189     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10190                            (sc->intr_count == 1)) ? TRUE : FALSE;
10191     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10192
10193     if (msix) {
10194         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10195                  HC_CONFIG_0_REG_INT_LINE_EN_0);
10196         val |= (HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10197                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10198         if (single_msix) {
10199             val |= HC_CONFIG_0_REG_SINGLE_ISR_EN_0;
10200         }
10201     } else if (msi) {
10202         val &= ~HC_CONFIG_0_REG_INT_LINE_EN_0;
10203         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10204                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10205                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10206     } else {
10207         val |= (HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10208                 HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10209                 HC_CONFIG_0_REG_INT_LINE_EN_0 |
10210                 HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10211
10212         if (!CHIP_IS_E1(sc)) {
10213             BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n",
10214                   val, port, addr);
10215
10216             REG_WR(sc, addr, val);
10217
10218             val &= ~HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0;
10219         }
10220     }
10221
10222     if (CHIP_IS_E1(sc)) {
10223         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0x1FFFF);
10224     }
10225
10226     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x) mode %s\n",
10227           val, port, addr, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10228
10229     REG_WR(sc, addr, val);
10230
10231     /* ensure that HC_CONFIG is written before leading/trailing edge config */
10232     mb();
10233
10234     if (!CHIP_IS_E1(sc)) {
10235         /* init leading/trailing edge */
10236         if (IS_MF(sc)) {
10237             val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10238             if (sc->port.pmf) {
10239                 /* enable nig and gpio3 attention */
10240                 val |= 0x1100;
10241             }
10242         } else {
10243             val = 0xffff;
10244         }
10245
10246         REG_WR(sc, (HC_REG_TRAILING_EDGE_0 + port*8), val);
10247         REG_WR(sc, (HC_REG_LEADING_EDGE_0 + port*8), val);
10248     }
10249
10250     /* make sure that interrupts are indeed enabled from here on */
10251     mb();
10252 }
10253
10254 static void
10255 bxe_igu_int_enable(struct bxe_softc *sc)
10256 {
10257     uint32_t val;
10258     uint8_t msix = (sc->interrupt_mode == INTR_MODE_MSIX) ? TRUE : FALSE;
10259     uint8_t single_msix = ((sc->interrupt_mode == INTR_MODE_MSIX) &&
10260                            (sc->intr_count == 1)) ? TRUE : FALSE;
10261     uint8_t msi = (sc->interrupt_mode == INTR_MODE_MSI) ? TRUE : FALSE;
10262
10263     val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10264
10265     if (msix) {
10266         val &= ~(IGU_PF_CONF_INT_LINE_EN |
10267                  IGU_PF_CONF_SINGLE_ISR_EN);
10268         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10269                 IGU_PF_CONF_ATTN_BIT_EN);
10270         if (single_msix) {
10271             val |= IGU_PF_CONF_SINGLE_ISR_EN;
10272         }
10273     } else if (msi) {
10274         val &= ~IGU_PF_CONF_INT_LINE_EN;
10275         val |= (IGU_PF_CONF_MSI_MSIX_EN |
10276                 IGU_PF_CONF_ATTN_BIT_EN |
10277                 IGU_PF_CONF_SINGLE_ISR_EN);
10278     } else {
10279         val &= ~IGU_PF_CONF_MSI_MSIX_EN;
10280         val |= (IGU_PF_CONF_INT_LINE_EN |
10281                 IGU_PF_CONF_ATTN_BIT_EN |
10282                 IGU_PF_CONF_SINGLE_ISR_EN);
10283     }
10284
10285     /* clean previous status - need to configure igu prior to ack*/
10286     if ((!msix) || single_msix) {
10287         REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10288         bxe_ack_int(sc);
10289     }
10290
10291     val |= IGU_PF_CONF_FUNC_EN;
10292
10293     BLOGD(sc, DBG_INTR, "write 0x%x to IGU mode %s\n",
10294           val, ((msix) ? "MSI-X" : ((msi) ? "MSI" : "INTx")));
10295
10296     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10297
10298     mb();
10299
10300     /* init leading/trailing edge */
10301     if (IS_MF(sc)) {
10302         val = (0xee0f | (1 << (SC_VN(sc) + 4)));
10303         if (sc->port.pmf) {
10304             /* enable nig and gpio3 attention */
10305             val |= 0x1100;
10306         }
10307     } else {
10308         val = 0xffff;
10309     }
10310
10311     REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, val);
10312     REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, val);
10313
10314     /* make sure that interrupts are indeed enabled from here on */
10315     mb();
10316 }
10317
10318 static void
10319 bxe_int_enable(struct bxe_softc *sc)
10320 {
10321     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10322         bxe_hc_int_enable(sc);
10323     } else {
10324         bxe_igu_int_enable(sc);
10325     }
10326 }
10327
10328 static void
10329 bxe_hc_int_disable(struct bxe_softc *sc)
10330 {
10331     int port = SC_PORT(sc);
10332     uint32_t addr = (port) ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0;
10333     uint32_t val = REG_RD(sc, addr);
10334
10335     /*
10336      * In E1 we must use only PCI configuration space to disable MSI/MSIX
10337      * capablility. It's forbidden to disable IGU_PF_CONF_MSI_MSIX_EN in HC
10338      * block
10339      */
10340     if (CHIP_IS_E1(sc)) {
10341         /*
10342          * Since IGU_PF_CONF_MSI_MSIX_EN still always on use mask register
10343          * to prevent from HC sending interrupts after we exit the function
10344          */
10345         REG_WR(sc, (HC_REG_INT_MASK + port*4), 0);
10346
10347         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10348                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10349                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10350     } else {
10351         val &= ~(HC_CONFIG_0_REG_SINGLE_ISR_EN_0 |
10352                  HC_CONFIG_0_REG_MSI_MSIX_INT_EN_0 |
10353                  HC_CONFIG_0_REG_INT_LINE_EN_0 |
10354                  HC_CONFIG_0_REG_ATTN_BIT_EN_0);
10355     }
10356
10357     BLOGD(sc, DBG_INTR, "write %x to HC %d (addr 0x%x)\n", val, port, addr);
10358
10359     /* flush all outstanding writes */
10360     mb();
10361
10362     REG_WR(sc, addr, val);
10363     if (REG_RD(sc, addr) != val) {
10364         BLOGE(sc, "proper val not read from HC IGU!\n");
10365     }
10366 }
10367
10368 static void
10369 bxe_igu_int_disable(struct bxe_softc *sc)
10370 {
10371     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
10372
10373     val &= ~(IGU_PF_CONF_MSI_MSIX_EN |
10374              IGU_PF_CONF_INT_LINE_EN |
10375              IGU_PF_CONF_ATTN_BIT_EN);
10376
10377     BLOGD(sc, DBG_INTR, "write %x to IGU\n", val);
10378
10379     /* flush all outstanding writes */
10380     mb();
10381
10382     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
10383     if (REG_RD(sc, IGU_REG_PF_CONFIGURATION) != val) {
10384         BLOGE(sc, "proper val not read from IGU!\n");
10385     }
10386 }
10387
10388 static void
10389 bxe_int_disable(struct bxe_softc *sc)
10390 {
10391     if (sc->devinfo.int_block == INT_BLOCK_HC) {
10392         bxe_hc_int_disable(sc);
10393     } else {
10394         bxe_igu_int_disable(sc);
10395     }
10396 }
10397
10398 static void
10399 bxe_nic_init(struct bxe_softc *sc,
10400              int              load_code)
10401 {
10402     int i;
10403
10404     for (i = 0; i < sc->num_queues; i++) {
10405         bxe_init_eth_fp(sc, i);
10406     }
10407
10408     rmb(); /* ensure status block indices were read */
10409
10410     bxe_init_rx_rings(sc);
10411     bxe_init_tx_rings(sc);
10412
10413     if (IS_VF(sc)) {
10414         return;
10415     }
10416
10417     /* initialize MOD_ABS interrupts */
10418     elink_init_mod_abs_int(sc, &sc->link_vars,
10419                            sc->devinfo.chip_id,
10420                            sc->devinfo.shmem_base,
10421                            sc->devinfo.shmem2_base,
10422                            SC_PORT(sc));
10423
10424     bxe_init_def_sb(sc);
10425     bxe_update_dsb_idx(sc);
10426     bxe_init_sp_ring(sc);
10427     bxe_init_eq_ring(sc);
10428     bxe_init_internal(sc, load_code);
10429     bxe_pf_init(sc);
10430     bxe_stats_init(sc);
10431
10432     /* flush all before enabling interrupts */
10433     mb();
10434
10435     bxe_int_enable(sc);
10436
10437     /* check for SPIO5 */
10438     bxe_attn_int_deasserted0(sc,
10439                              REG_RD(sc,
10440                                     (MISC_REG_AEU_AFTER_INVERT_1_FUNC_0 +
10441                                      SC_PORT(sc)*4)) &
10442                              AEU_INPUTS_ATTN_BITS_SPIO5);
10443 }
10444
10445 static inline void
10446 bxe_init_objs(struct bxe_softc *sc)
10447 {
10448     /* mcast rules must be added to tx if tx switching is enabled */
10449     ecore_obj_type o_type =
10450         (sc->flags & BXE_TX_SWITCHING) ? ECORE_OBJ_TYPE_RX_TX :
10451                                          ECORE_OBJ_TYPE_RX;
10452
10453     /* RX_MODE controlling object */
10454     ecore_init_rx_mode_obj(sc, &sc->rx_mode_obj);
10455
10456     /* multicast configuration controlling object */
10457     ecore_init_mcast_obj(sc,
10458                          &sc->mcast_obj,
10459                          sc->fp[0].cl_id,
10460                          sc->fp[0].index,
10461                          SC_FUNC(sc),
10462                          SC_FUNC(sc),
10463                          BXE_SP(sc, mcast_rdata),
10464                          BXE_SP_MAPPING(sc, mcast_rdata),
10465                          ECORE_FILTER_MCAST_PENDING,
10466                          &sc->sp_state,
10467                          o_type);
10468
10469     /* Setup CAM credit pools */
10470     ecore_init_mac_credit_pool(sc,
10471                                &sc->macs_pool,
10472                                SC_FUNC(sc),
10473                                CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10474                                                  VNICS_PER_PATH(sc));
10475
10476     ecore_init_vlan_credit_pool(sc,
10477                                 &sc->vlans_pool,
10478                                 SC_ABS_FUNC(sc) >> 1,
10479                                 CHIP_IS_E1x(sc) ? VNICS_PER_PORT(sc) :
10480                                                   VNICS_PER_PATH(sc));
10481
10482     /* RSS configuration object */
10483     ecore_init_rss_config_obj(sc,
10484                               &sc->rss_conf_obj,
10485                               sc->fp[0].cl_id,
10486                               sc->fp[0].index,
10487                               SC_FUNC(sc),
10488                               SC_FUNC(sc),
10489                               BXE_SP(sc, rss_rdata),
10490                               BXE_SP_MAPPING(sc, rss_rdata),
10491                               ECORE_FILTER_RSS_CONF_PENDING,
10492                               &sc->sp_state, ECORE_OBJ_TYPE_RX);
10493 }
10494
10495 /*
10496  * Initialize the function. This must be called before sending CLIENT_SETUP
10497  * for the first client.
10498  */
10499 static inline int
10500 bxe_func_start(struct bxe_softc *sc)
10501 {
10502     struct ecore_func_state_params func_params = { NULL };
10503     struct ecore_func_start_params *start_params = &func_params.params.start;
10504
10505     /* Prepare parameters for function state transitions */
10506     bit_set(&func_params.ramrod_flags, RAMROD_COMP_WAIT);
10507
10508     func_params.f_obj = &sc->func_obj;
10509     func_params.cmd = ECORE_F_CMD_START;
10510
10511     /* Function parameters */
10512     start_params->mf_mode     = sc->devinfo.mf_info.mf_mode;
10513     start_params->sd_vlan_tag = OVLAN(sc);
10514
10515     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
10516         start_params->network_cos_mode = STATIC_COS;
10517     } else { /* CHIP_IS_E1X */
10518         start_params->network_cos_mode = FW_WRR;
10519     }
10520
10521     //start_params->gre_tunnel_mode = 0;
10522     //start_params->gre_tunnel_rss  = 0;
10523
10524     return (ecore_func_state_change(sc, &func_params));
10525 }
10526
10527 static int
10528 bxe_set_power_state(struct bxe_softc *sc,
10529                     uint8_t          state)
10530 {
10531     uint16_t pmcsr;
10532
10533     /* If there is no power capability, silently succeed */
10534     if (!(sc->devinfo.pcie_cap_flags & BXE_PM_CAPABLE_FLAG)) {
10535         BLOGW(sc, "No power capability\n");
10536         return (0);
10537     }
10538
10539     pmcsr = pci_read_config(sc->dev,
10540                             (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10541                             2);
10542
10543     switch (state) {
10544     case PCI_PM_D0:
10545         pci_write_config(sc->dev,
10546                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10547                          ((pmcsr & ~PCIM_PSTAT_DMASK) | PCIM_PSTAT_PME), 2);
10548
10549         if (pmcsr & PCIM_PSTAT_DMASK) {
10550             /* delay required during transition out of D3hot */
10551             DELAY(20000);
10552         }
10553
10554         break;
10555
10556     case PCI_PM_D3hot:
10557         /* XXX if there are other clients above don't shut down the power */
10558
10559         /* don't shut down the power for emulation and FPGA */
10560         if (CHIP_REV_IS_SLOW(sc)) {
10561             return (0);
10562         }
10563
10564         pmcsr &= ~PCIM_PSTAT_DMASK;
10565         pmcsr |= PCIM_PSTAT_D3;
10566
10567         if (sc->wol) {
10568             pmcsr |= PCIM_PSTAT_PMEENABLE;
10569         }
10570
10571         pci_write_config(sc->dev,
10572                          (sc->devinfo.pcie_pm_cap_reg + PCIR_POWER_STATUS),
10573                          pmcsr, 4);
10574
10575         /*
10576          * No more memory access after this point until device is brought back
10577          * to D0 state.
10578          */
10579         break;
10580
10581     default:
10582         BLOGE(sc, "Can't support PCI power state = 0x%x pmcsr 0x%x\n",
10583             state, pmcsr);
10584         return (-1);
10585     }
10586
10587     return (0);
10588 }
10589
10590
10591 /* return true if succeeded to acquire the lock */
10592 static uint8_t
10593 bxe_trylock_hw_lock(struct bxe_softc *sc,
10594                     uint32_t         resource)
10595 {
10596     uint32_t lock_status;
10597     uint32_t resource_bit = (1 << resource);
10598     int func = SC_FUNC(sc);
10599     uint32_t hw_lock_control_reg;
10600
10601     BLOGD(sc, DBG_LOAD, "Trying to take a resource lock 0x%x\n", resource);
10602
10603     /* Validating that the resource is within range */
10604     if (resource > HW_LOCK_MAX_RESOURCE_VALUE) {
10605         BLOGD(sc, DBG_LOAD,
10606               "resource(0x%x) > HW_LOCK_MAX_RESOURCE_VALUE(0x%x)\n",
10607               resource, HW_LOCK_MAX_RESOURCE_VALUE);
10608         return (FALSE);
10609     }
10610
10611     if (func <= 5) {
10612         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_1 + func*8);
10613     } else {
10614         hw_lock_control_reg = (MISC_REG_DRIVER_CONTROL_7 + (func - 6)*8);
10615     }
10616
10617     /* try to acquire the lock */
10618     REG_WR(sc, hw_lock_control_reg + 4, resource_bit);
10619     lock_status = REG_RD(sc, hw_lock_control_reg);
10620     if (lock_status & resource_bit) {
10621         return (TRUE);
10622     }
10623
10624     BLOGE(sc, "Failed to get a resource lock 0x%x func %d "
10625         "lock_status 0x%x resource_bit 0x%x\n", resource, func,
10626         lock_status, resource_bit);
10627
10628     return (FALSE);
10629 }
10630
10631 /*
10632  * Get the recovery leader resource id according to the engine this function
10633  * belongs to. Currently only only 2 engines is supported.
10634  */
10635 static int
10636 bxe_get_leader_lock_resource(struct bxe_softc *sc)
10637 {
10638     if (SC_PATH(sc)) {
10639         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_1);
10640     } else {
10641         return (HW_LOCK_RESOURCE_RECOVERY_LEADER_0);
10642     }
10643 }
10644
10645 /* try to acquire a leader lock for current engine */
10646 static uint8_t
10647 bxe_trylock_leader_lock(struct bxe_softc *sc)
10648 {
10649     return (bxe_trylock_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10650 }
10651
10652 static int
10653 bxe_release_leader_lock(struct bxe_softc *sc)
10654 {
10655     return (bxe_release_hw_lock(sc, bxe_get_leader_lock_resource(sc)));
10656 }
10657
10658 /* close gates #2, #3 and #4 */
10659 static void
10660 bxe_set_234_gates(struct bxe_softc *sc,
10661                   uint8_t          close)
10662 {
10663     uint32_t val;
10664
10665     /* gates #2 and #4a are closed/opened for "not E1" only */
10666     if (!CHIP_IS_E1(sc)) {
10667         /* #4 */
10668         REG_WR(sc, PXP_REG_HST_DISCARD_DOORBELLS, !!close);
10669         /* #2 */
10670         REG_WR(sc, PXP_REG_HST_DISCARD_INTERNAL_WRITES, !!close);
10671     }
10672
10673     /* #3 */
10674     if (CHIP_IS_E1x(sc)) {
10675         /* prevent interrupts from HC on both ports */
10676         val = REG_RD(sc, HC_REG_CONFIG_1);
10677         REG_WR(sc, HC_REG_CONFIG_1,
10678                (!close) ? (val | HC_CONFIG_1_REG_BLOCK_DISABLE_1) :
10679                (val & ~(uint32_t)HC_CONFIG_1_REG_BLOCK_DISABLE_1));
10680
10681         val = REG_RD(sc, HC_REG_CONFIG_0);
10682         REG_WR(sc, HC_REG_CONFIG_0,
10683                (!close) ? (val | HC_CONFIG_0_REG_BLOCK_DISABLE_0) :
10684                (val & ~(uint32_t)HC_CONFIG_0_REG_BLOCK_DISABLE_0));
10685     } else {
10686         /* Prevent incomming interrupts in IGU */
10687         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
10688
10689         REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION,
10690                (!close) ?
10691                (val | IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE) :
10692                (val & ~(uint32_t)IGU_BLOCK_CONFIGURATION_REG_BLOCK_ENABLE));
10693     }
10694
10695     BLOGD(sc, DBG_LOAD, "%s gates #2, #3 and #4\n",
10696           close ? "closing" : "opening");
10697
10698     wmb();
10699 }
10700
10701 /* poll for pending writes bit, it should get cleared in no more than 1s */
10702 static int
10703 bxe_er_poll_igu_vq(struct bxe_softc *sc)
10704 {
10705     uint32_t cnt = 1000;
10706     uint32_t pend_bits = 0;
10707
10708     do {
10709         pend_bits = REG_RD(sc, IGU_REG_PENDING_BITS_STATUS);
10710
10711         if (pend_bits == 0) {
10712             break;
10713         }
10714
10715         DELAY(1000);
10716     } while (--cnt > 0);
10717
10718     if (cnt == 0) {
10719         BLOGE(sc, "Still pending IGU requests bits=0x%08x!\n", pend_bits);
10720         return (-1);
10721     }
10722
10723     return (0);
10724 }
10725
10726 #define SHARED_MF_CLP_MAGIC  0x80000000 /* 'magic' bit */
10727
10728 static void
10729 bxe_clp_reset_prep(struct bxe_softc *sc,
10730                    uint32_t         *magic_val)
10731 {
10732     /* Do some magic... */
10733     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10734     *magic_val = val & SHARED_MF_CLP_MAGIC;
10735     MFCFG_WR(sc, shared_mf_config.clp_mb, val | SHARED_MF_CLP_MAGIC);
10736 }
10737
10738 /* restore the value of the 'magic' bit */
10739 static void
10740 bxe_clp_reset_done(struct bxe_softc *sc,
10741                    uint32_t         magic_val)
10742 {
10743     /* Restore the 'magic' bit value... */
10744     uint32_t val = MFCFG_RD(sc, shared_mf_config.clp_mb);
10745     MFCFG_WR(sc, shared_mf_config.clp_mb,
10746               (val & (~SHARED_MF_CLP_MAGIC)) | magic_val);
10747 }
10748
10749 /* prepare for MCP reset, takes care of CLP configurations */
10750 static void
10751 bxe_reset_mcp_prep(struct bxe_softc *sc,
10752                    uint32_t         *magic_val)
10753 {
10754     uint32_t shmem;
10755     uint32_t validity_offset;
10756
10757     /* set `magic' bit in order to save MF config */
10758     if (!CHIP_IS_E1(sc)) {
10759         bxe_clp_reset_prep(sc, magic_val);
10760     }
10761
10762     /* get shmem offset */
10763     shmem = REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10764     validity_offset =
10765         offsetof(struct shmem_region, validity_map[SC_PORT(sc)]);
10766
10767     /* Clear validity map flags */
10768     if (shmem > 0) {
10769         REG_WR(sc, shmem + validity_offset, 0);
10770     }
10771 }
10772
10773 #define MCP_TIMEOUT      5000   /* 5 seconds (in ms) */
10774 #define MCP_ONE_TIMEOUT  100    /* 100 ms */
10775
10776 static void
10777 bxe_mcp_wait_one(struct bxe_softc *sc)
10778 {
10779     /* special handling for emulation and FPGA (10 times longer) */
10780     if (CHIP_REV_IS_SLOW(sc)) {
10781         DELAY((MCP_ONE_TIMEOUT*10) * 1000);
10782     } else {
10783         DELAY((MCP_ONE_TIMEOUT) * 1000);
10784     }
10785 }
10786
10787 /* initialize shmem_base and waits for validity signature to appear */
10788 static int
10789 bxe_init_shmem(struct bxe_softc *sc)
10790 {
10791     int cnt = 0;
10792     uint32_t val = 0;
10793
10794     do {
10795         sc->devinfo.shmem_base     =
10796         sc->link_params.shmem_base =
10797             REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
10798
10799         if (sc->devinfo.shmem_base) {
10800             val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
10801             if (val & SHR_MEM_VALIDITY_MB)
10802                 return (0);
10803         }
10804
10805         bxe_mcp_wait_one(sc);
10806
10807     } while (cnt++ < (MCP_TIMEOUT / MCP_ONE_TIMEOUT));
10808
10809     BLOGE(sc, "BAD MCP validity signature\n");
10810
10811     return (-1);
10812 }
10813
10814 static int
10815 bxe_reset_mcp_comp(struct bxe_softc *sc,
10816                    uint32_t         magic_val)
10817 {
10818     int rc = bxe_init_shmem(sc);
10819
10820     /* Restore the `magic' bit value */
10821     if (!CHIP_IS_E1(sc)) {
10822         bxe_clp_reset_done(sc, magic_val);
10823     }
10824
10825     return (rc);
10826 }
10827
10828 static void
10829 bxe_pxp_prep(struct bxe_softc *sc)
10830 {
10831     if (!CHIP_IS_E1(sc)) {
10832         REG_WR(sc, PXP2_REG_RD_START_INIT, 0);
10833         REG_WR(sc, PXP2_REG_RQ_RBC_DONE, 0);
10834         wmb();
10835     }
10836 }
10837
10838 /*
10839  * Reset the whole chip except for:
10840  *      - PCIE core
10841  *      - PCI Glue, PSWHST, PXP/PXP2 RF (all controlled by one reset bit)
10842  *      - IGU
10843  *      - MISC (including AEU)
10844  *      - GRC
10845  *      - RBCN, RBCP
10846  */
10847 static void
10848 bxe_process_kill_chip_reset(struct bxe_softc *sc,
10849                             uint8_t          global)
10850 {
10851     uint32_t not_reset_mask1, reset_mask1, not_reset_mask2, reset_mask2;
10852     uint32_t global_bits2, stay_reset2;
10853
10854     /*
10855      * Bits that have to be set in reset_mask2 if we want to reset 'global'
10856      * (per chip) blocks.
10857      */
10858     global_bits2 =
10859         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CPU |
10860         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_CMN_CORE;
10861
10862     /*
10863      * Don't reset the following blocks.
10864      * Important: per port blocks (such as EMAC, BMAC, UMAC) can't be
10865      *            reset, as in 4 port device they might still be owned
10866      *            by the MCP (there is only one leader per path).
10867      */
10868     not_reset_mask1 =
10869         MISC_REGISTERS_RESET_REG_1_RST_HC |
10870         MISC_REGISTERS_RESET_REG_1_RST_PXPV |
10871         MISC_REGISTERS_RESET_REG_1_RST_PXP;
10872
10873     not_reset_mask2 =
10874         MISC_REGISTERS_RESET_REG_2_RST_PCI_MDIO |
10875         MISC_REGISTERS_RESET_REG_2_RST_EMAC0_HARD_CORE |
10876         MISC_REGISTERS_RESET_REG_2_RST_EMAC1_HARD_CORE |
10877         MISC_REGISTERS_RESET_REG_2_RST_MISC_CORE |
10878         MISC_REGISTERS_RESET_REG_2_RST_RBCN |
10879         MISC_REGISTERS_RESET_REG_2_RST_GRC  |
10880         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_RESET_REG_HARD_CORE |
10881         MISC_REGISTERS_RESET_REG_2_RST_MCP_N_HARD_CORE_RST_B |
10882         MISC_REGISTERS_RESET_REG_2_RST_ATC |
10883         MISC_REGISTERS_RESET_REG_2_PGLC |
10884         MISC_REGISTERS_RESET_REG_2_RST_BMAC0 |
10885         MISC_REGISTERS_RESET_REG_2_RST_BMAC1 |
10886         MISC_REGISTERS_RESET_REG_2_RST_EMAC0 |
10887         MISC_REGISTERS_RESET_REG_2_RST_EMAC1 |
10888         MISC_REGISTERS_RESET_REG_2_UMAC0 |
10889         MISC_REGISTERS_RESET_REG_2_UMAC1;
10890
10891     /*
10892      * Keep the following blocks in reset:
10893      *  - all xxMACs are handled by the elink code.
10894      */
10895     stay_reset2 =
10896         MISC_REGISTERS_RESET_REG_2_XMAC |
10897         MISC_REGISTERS_RESET_REG_2_XMAC_SOFT;
10898
10899     /* Full reset masks according to the chip */
10900     reset_mask1 = 0xffffffff;
10901
10902     if (CHIP_IS_E1(sc))
10903         reset_mask2 = 0xffff;
10904     else if (CHIP_IS_E1H(sc))
10905         reset_mask2 = 0x1ffff;
10906     else if (CHIP_IS_E2(sc))
10907         reset_mask2 = 0xfffff;
10908     else /* CHIP_IS_E3 */
10909         reset_mask2 = 0x3ffffff;
10910
10911     /* Don't reset global blocks unless we need to */
10912     if (!global)
10913         reset_mask2 &= ~global_bits2;
10914
10915     /*
10916      * In case of attention in the QM, we need to reset PXP
10917      * (MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR) before QM
10918      * because otherwise QM reset would release 'close the gates' shortly
10919      * before resetting the PXP, then the PSWRQ would send a write
10920      * request to PGLUE. Then when PXP is reset, PGLUE would try to
10921      * read the payload data from PSWWR, but PSWWR would not
10922      * respond. The write queue in PGLUE would stuck, dmae commands
10923      * would not return. Therefore it's important to reset the second
10924      * reset register (containing the
10925      * MISC_REGISTERS_RESET_REG_2_RST_PXP_RQ_RD_WR bit) before the
10926      * first one (containing the MISC_REGISTERS_RESET_REG_1_RST_QM
10927      * bit).
10928      */
10929     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR,
10930            reset_mask2 & (~not_reset_mask2));
10931
10932     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
10933            reset_mask1 & (~not_reset_mask1));
10934
10935     mb();
10936     wmb();
10937
10938     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET,
10939            reset_mask2 & (~stay_reset2));
10940
10941     mb();
10942     wmb();
10943
10944     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, reset_mask1);
10945     wmb();
10946 }
10947
10948 static int
10949 bxe_process_kill(struct bxe_softc *sc,
10950                  uint8_t          global)
10951 {
10952     int cnt = 1000;
10953     uint32_t val = 0;
10954     uint32_t sr_cnt, blk_cnt, port_is_idle_0, port_is_idle_1, pgl_exp_rom2;
10955     uint32_t tags_63_32 = 0;
10956
10957     /* Empty the Tetris buffer, wait for 1s */
10958     do {
10959         sr_cnt  = REG_RD(sc, PXP2_REG_RD_SR_CNT);
10960         blk_cnt = REG_RD(sc, PXP2_REG_RD_BLK_CNT);
10961         port_is_idle_0 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_0);
10962         port_is_idle_1 = REG_RD(sc, PXP2_REG_RD_PORT_IS_IDLE_1);
10963         pgl_exp_rom2 = REG_RD(sc, PXP2_REG_PGL_EXP_ROM2);
10964         if (CHIP_IS_E3(sc)) {
10965             tags_63_32 = REG_RD(sc, PGLUE_B_REG_TAGS_63_32);
10966         }
10967
10968         if ((sr_cnt == 0x7e) && (blk_cnt == 0xa0) &&
10969             ((port_is_idle_0 & 0x1) == 0x1) &&
10970             ((port_is_idle_1 & 0x1) == 0x1) &&
10971             (pgl_exp_rom2 == 0xffffffff) &&
10972             (!CHIP_IS_E3(sc) || (tags_63_32 == 0xffffffff)))
10973             break;
10974         DELAY(1000);
10975     } while (cnt-- > 0);
10976
10977     if (cnt <= 0) {
10978         BLOGE(sc, "ERROR: Tetris buffer didn't get empty or there "
10979                   "are still outstanding read requests after 1s! "
10980                   "sr_cnt=0x%08x, blk_cnt=0x%08x, port_is_idle_0=0x%08x, "
10981                   "port_is_idle_1=0x%08x, pgl_exp_rom2=0x%08x\n",
10982               sr_cnt, blk_cnt, port_is_idle_0,
10983               port_is_idle_1, pgl_exp_rom2);
10984         return (-1);
10985     }
10986
10987     mb();
10988
10989     /* Close gates #2, #3 and #4 */
10990     bxe_set_234_gates(sc, TRUE);
10991
10992     /* Poll for IGU VQs for 57712 and newer chips */
10993     if (!CHIP_IS_E1x(sc) && bxe_er_poll_igu_vq(sc)) {
10994         return (-1);
10995     }
10996
10997     /* XXX indicate that "process kill" is in progress to MCP */
10998
10999     /* clear "unprepared" bit */
11000     REG_WR(sc, MISC_REG_UNPREPARED, 0);
11001     mb();
11002
11003     /* Make sure all is written to the chip before the reset */
11004     wmb();
11005
11006     /*
11007      * Wait for 1ms to empty GLUE and PCI-E core queues,
11008      * PSWHST, GRC and PSWRD Tetris buffer.
11009      */
11010     DELAY(1000);
11011
11012     /* Prepare to chip reset: */
11013     /* MCP */
11014     if (global) {
11015         bxe_reset_mcp_prep(sc, &val);
11016     }
11017
11018     /* PXP */
11019     bxe_pxp_prep(sc);
11020     mb();
11021
11022     /* reset the chip */
11023     bxe_process_kill_chip_reset(sc, global);
11024     mb();
11025
11026     /* clear errors in PGB */
11027     if (!CHIP_IS_E1(sc))
11028         REG_WR(sc, PGLUE_B_REG_LATCHED_ERRORS_CLR, 0x7f);
11029
11030     /* Recover after reset: */
11031     /* MCP */
11032     if (global && bxe_reset_mcp_comp(sc, val)) {
11033         return (-1);
11034     }
11035
11036     /* XXX add resetting the NO_MCP mode DB here */
11037
11038     /* Open the gates #2, #3 and #4 */
11039     bxe_set_234_gates(sc, FALSE);
11040
11041     /* XXX
11042      * IGU/AEU preparation bring back the AEU/IGU to a reset state
11043      * re-enable attentions
11044      */
11045
11046     return (0);
11047 }
11048
11049 static int
11050 bxe_leader_reset(struct bxe_softc *sc)
11051 {
11052     int rc = 0;
11053     uint8_t global = bxe_reset_is_global(sc);
11054     uint32_t load_code;
11055
11056     /*
11057      * If not going to reset MCP, load "fake" driver to reset HW while
11058      * driver is owner of the HW.
11059      */
11060     if (!global && !BXE_NOMCP(sc)) {
11061         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_REQ,
11062                                    DRV_MSG_CODE_LOAD_REQ_WITH_LFA);
11063         if (!load_code) {
11064             BLOGE(sc, "MCP response failure, aborting\n");
11065             rc = -1;
11066             goto exit_leader_reset;
11067         }
11068
11069         if ((load_code != FW_MSG_CODE_DRV_LOAD_COMMON_CHIP) &&
11070             (load_code != FW_MSG_CODE_DRV_LOAD_COMMON)) {
11071             BLOGE(sc, "MCP unexpected response, aborting\n");
11072             rc = -1;
11073             goto exit_leader_reset2;
11074         }
11075
11076         load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
11077         if (!load_code) {
11078             BLOGE(sc, "MCP response failure, aborting\n");
11079             rc = -1;
11080             goto exit_leader_reset2;
11081         }
11082     }
11083
11084     /* try to recover after the failure */
11085     if (bxe_process_kill(sc, global)) {
11086         BLOGE(sc, "Something bad occurred on engine %d!\n", SC_PATH(sc));
11087         rc = -1;
11088         goto exit_leader_reset2;
11089     }
11090
11091     /*
11092      * Clear the RESET_IN_PROGRESS and RESET_GLOBAL bits and update the driver
11093      * state.
11094      */
11095     bxe_set_reset_done(sc);
11096     if (global) {
11097         bxe_clear_reset_global(sc);
11098     }
11099
11100 exit_leader_reset2:
11101
11102     /* unload "fake driver" if it was loaded */
11103     if (!global && !BXE_NOMCP(sc)) {
11104         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
11105         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
11106     }
11107
11108 exit_leader_reset:
11109
11110     sc->is_leader = 0;
11111     bxe_release_leader_lock(sc);
11112
11113     mb();
11114     return (rc);
11115 }
11116
11117 /*
11118  * prepare INIT transition, parameters configured:
11119  *   - HC configuration
11120  *   - Queue's CDU context
11121  */
11122 static void
11123 bxe_pf_q_prep_init(struct bxe_softc               *sc,
11124                    struct bxe_fastpath            *fp,
11125                    struct ecore_queue_init_params *init_params)
11126 {
11127     uint8_t cos;
11128     int cxt_index, cxt_offset;
11129
11130     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->rx.flags);
11131     bxe_set_bit(ECORE_Q_FLG_HC, &init_params->tx.flags);
11132
11133     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->rx.flags);
11134     bxe_set_bit(ECORE_Q_FLG_HC_EN, &init_params->tx.flags);
11135
11136     /* HC rate */
11137     init_params->rx.hc_rate =
11138         sc->hc_rx_ticks ? (1000000 / sc->hc_rx_ticks) : 0;
11139     init_params->tx.hc_rate =
11140         sc->hc_tx_ticks ? (1000000 / sc->hc_tx_ticks) : 0;
11141
11142     /* FW SB ID */
11143     init_params->rx.fw_sb_id = init_params->tx.fw_sb_id = fp->fw_sb_id;
11144
11145     /* CQ index among the SB indices */
11146     init_params->rx.sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11147     init_params->tx.sb_cq_index = HC_INDEX_ETH_FIRST_TX_CQ_CONS;
11148
11149     /* set maximum number of COSs supported by this queue */
11150     init_params->max_cos = sc->max_cos;
11151
11152     BLOGD(sc, DBG_LOAD, "fp %d setting queue params max cos to %d\n",
11153           fp->index, init_params->max_cos);
11154
11155     /* set the context pointers queue object */
11156     for (cos = FIRST_TX_COS_INDEX; cos < init_params->max_cos; cos++) {
11157         /* XXX change index/cid here if ever support multiple tx CoS */
11158         /* fp->txdata[cos]->cid */
11159         cxt_index = fp->index / ILT_PAGE_CIDS;
11160         cxt_offset = fp->index - (cxt_index * ILT_PAGE_CIDS);
11161         init_params->cxts[cos] = &sc->context[cxt_index].vcxt[cxt_offset].eth;
11162     }
11163 }
11164
11165 /* set flags that are common for the Tx-only and not normal connections */
11166 static unsigned long
11167 bxe_get_common_flags(struct bxe_softc    *sc,
11168                      struct bxe_fastpath *fp,
11169                      uint8_t             zero_stats)
11170 {
11171     unsigned long flags = 0;
11172
11173     /* PF driver will always initialize the Queue to an ACTIVE state */
11174     bxe_set_bit(ECORE_Q_FLG_ACTIVE, &flags);
11175
11176     /*
11177      * tx only connections collect statistics (on the same index as the
11178      * parent connection). The statistics are zeroed when the parent
11179      * connection is initialized.
11180      */
11181
11182     bxe_set_bit(ECORE_Q_FLG_STATS, &flags);
11183     if (zero_stats) {
11184         bxe_set_bit(ECORE_Q_FLG_ZERO_STATS, &flags);
11185     }
11186
11187     /*
11188      * tx only connections can support tx-switching, though their
11189      * CoS-ness doesn't survive the loopback
11190      */
11191     if (sc->flags & BXE_TX_SWITCHING) {
11192         bxe_set_bit(ECORE_Q_FLG_TX_SWITCH, &flags);
11193     }
11194
11195     bxe_set_bit(ECORE_Q_FLG_PCSUM_ON_PKT, &flags);
11196
11197     return (flags);
11198 }
11199
11200 static unsigned long
11201 bxe_get_q_flags(struct bxe_softc    *sc,
11202                 struct bxe_fastpath *fp,
11203                 uint8_t             leading)
11204 {
11205     unsigned long flags = 0;
11206
11207     if (IS_MF_SD(sc)) {
11208         bxe_set_bit(ECORE_Q_FLG_OV, &flags);
11209     }
11210
11211     if (sc->ifnet->if_capenable & IFCAP_LRO) {
11212         bxe_set_bit(ECORE_Q_FLG_TPA, &flags);
11213         bxe_set_bit(ECORE_Q_FLG_TPA_IPV6, &flags);
11214     }
11215
11216     if (leading) {
11217         bxe_set_bit(ECORE_Q_FLG_LEADING_RSS, &flags);
11218         bxe_set_bit(ECORE_Q_FLG_MCAST, &flags);
11219     }
11220
11221     bxe_set_bit(ECORE_Q_FLG_VLAN, &flags);
11222
11223     /* merge with common flags */
11224     return (flags | bxe_get_common_flags(sc, fp, TRUE));
11225 }
11226
11227 static void
11228 bxe_pf_q_prep_general(struct bxe_softc                  *sc,
11229                       struct bxe_fastpath               *fp,
11230                       struct ecore_general_setup_params *gen_init,
11231                       uint8_t                           cos)
11232 {
11233     gen_init->stat_id = bxe_stats_id(fp);
11234     gen_init->spcl_id = fp->cl_id;
11235     gen_init->mtu = sc->mtu;
11236     gen_init->cos = cos;
11237 }
11238
11239 static void
11240 bxe_pf_rx_q_prep(struct bxe_softc              *sc,
11241                  struct bxe_fastpath           *fp,
11242                  struct rxq_pause_params       *pause,
11243                  struct ecore_rxq_setup_params *rxq_init)
11244 {
11245     uint8_t max_sge = 0;
11246     uint16_t sge_sz = 0;
11247     uint16_t tpa_agg_size = 0;
11248
11249     pause->sge_th_lo = SGE_TH_LO(sc);
11250     pause->sge_th_hi = SGE_TH_HI(sc);
11251
11252     /* validate SGE ring has enough to cross high threshold */
11253     if (sc->dropless_fc &&
11254             (pause->sge_th_hi + FW_PREFETCH_CNT) >
11255             (RX_SGE_USABLE_PER_PAGE * RX_SGE_NUM_PAGES)) {
11256         BLOGW(sc, "sge ring threshold limit\n");
11257     }
11258
11259     /* minimum max_aggregation_size is 2*MTU (two full buffers) */
11260     tpa_agg_size = (2 * sc->mtu);
11261     if (tpa_agg_size < sc->max_aggregation_size) {
11262         tpa_agg_size = sc->max_aggregation_size;
11263     }
11264
11265     max_sge = SGE_PAGE_ALIGN(sc->mtu) >> SGE_PAGE_SHIFT;
11266     max_sge = ((max_sge + PAGES_PER_SGE - 1) &
11267                    (~(PAGES_PER_SGE - 1))) >> PAGES_PER_SGE_SHIFT;
11268     sge_sz = (uint16_t)min(SGE_PAGES, 0xffff);
11269
11270     /* pause - not for e1 */
11271     if (!CHIP_IS_E1(sc)) {
11272         pause->bd_th_lo = BD_TH_LO(sc);
11273         pause->bd_th_hi = BD_TH_HI(sc);
11274
11275         pause->rcq_th_lo = RCQ_TH_LO(sc);
11276         pause->rcq_th_hi = RCQ_TH_HI(sc);
11277
11278         /* validate rings have enough entries to cross high thresholds */
11279         if (sc->dropless_fc &&
11280             pause->bd_th_hi + FW_PREFETCH_CNT >
11281             sc->rx_ring_size) {
11282             BLOGW(sc, "rx bd ring threshold limit\n");
11283         }
11284
11285         if (sc->dropless_fc &&
11286             pause->rcq_th_hi + FW_PREFETCH_CNT >
11287             RCQ_NUM_PAGES * RCQ_USABLE_PER_PAGE) {
11288             BLOGW(sc, "rcq ring threshold limit\n");
11289         }
11290
11291         pause->pri_map = 1;
11292     }
11293
11294     /* rxq setup */
11295     rxq_init->dscr_map   = fp->rx_dma.paddr;
11296     rxq_init->sge_map    = fp->rx_sge_dma.paddr;
11297     rxq_init->rcq_map    = fp->rcq_dma.paddr;
11298     rxq_init->rcq_np_map = (fp->rcq_dma.paddr + BCM_PAGE_SIZE);
11299
11300     /*
11301      * This should be a maximum number of data bytes that may be
11302      * placed on the BD (not including paddings).
11303      */
11304     rxq_init->buf_sz = (fp->rx_buf_size -
11305                         IP_HEADER_ALIGNMENT_PADDING);
11306
11307     rxq_init->cl_qzone_id     = fp->cl_qzone_id;
11308     rxq_init->tpa_agg_sz      = tpa_agg_size;
11309     rxq_init->sge_buf_sz      = sge_sz;
11310     rxq_init->max_sges_pkt    = max_sge;
11311     rxq_init->rss_engine_id   = SC_FUNC(sc);
11312     rxq_init->mcast_engine_id = SC_FUNC(sc);
11313
11314     /*
11315      * Maximum number or simultaneous TPA aggregation for this Queue.
11316      * For PF Clients it should be the maximum available number.
11317      * VF driver(s) may want to define it to a smaller value.
11318      */
11319     rxq_init->max_tpa_queues = MAX_AGG_QS(sc);
11320
11321     rxq_init->cache_line_log = BXE_RX_ALIGN_SHIFT;
11322     rxq_init->fw_sb_id = fp->fw_sb_id;
11323
11324     rxq_init->sb_cq_index = HC_INDEX_ETH_RX_CQ_CONS;
11325
11326     /*
11327      * configure silent vlan removal
11328      * if multi function mode is afex, then mask default vlan
11329      */
11330     if (IS_MF_AFEX(sc)) {
11331         rxq_init->silent_removal_value =
11332             sc->devinfo.mf_info.afex_def_vlan_tag;
11333         rxq_init->silent_removal_mask = EVL_VLID_MASK;
11334     }
11335 }
11336
11337 static void
11338 bxe_pf_tx_q_prep(struct bxe_softc              *sc,
11339                  struct bxe_fastpath           *fp,
11340                  struct ecore_txq_setup_params *txq_init,
11341                  uint8_t                       cos)
11342 {
11343     /*
11344      * XXX If multiple CoS is ever supported then each fastpath structure
11345      * will need to maintain tx producer/consumer/dma/etc values *per* CoS.
11346      * fp->txdata[cos]->tx_dma.paddr;
11347      */
11348     txq_init->dscr_map     = fp->tx_dma.paddr;
11349     txq_init->sb_cq_index  = HC_INDEX_ETH_FIRST_TX_CQ_CONS + cos;
11350     txq_init->traffic_type = LLFC_TRAFFIC_TYPE_NW;
11351     txq_init->fw_sb_id     = fp->fw_sb_id;
11352
11353     /*
11354      * set the TSS leading client id for TX classfication to the
11355      * leading RSS client id
11356      */
11357     txq_init->tss_leading_cl_id = BXE_FP(sc, 0, cl_id);
11358 }
11359
11360 /*
11361  * This function performs 2 steps in a queue state machine:
11362  *   1) RESET->INIT
11363  *   2) INIT->SETUP
11364  */
11365 static int
11366 bxe_setup_queue(struct bxe_softc    *sc,
11367                 struct bxe_fastpath *fp,
11368                 uint8_t             leading)
11369 {
11370     struct ecore_queue_state_params q_params = { NULL };
11371     struct ecore_queue_setup_params *setup_params =
11372                         &q_params.params.setup;
11373     int rc;
11374
11375     BLOGD(sc, DBG_LOAD, "setting up queue %d\n", fp->index);
11376
11377     bxe_ack_sb(sc, fp->igu_sb_id, USTORM_ID, 0, IGU_INT_ENABLE, 0);
11378
11379     q_params.q_obj = &BXE_SP_OBJ(sc, fp).q_obj;
11380
11381     /* we want to wait for completion in this context */
11382     bxe_set_bit(RAMROD_COMP_WAIT, &q_params.ramrod_flags);
11383
11384     /* prepare the INIT parameters */
11385     bxe_pf_q_prep_init(sc, fp, &q_params.params.init);
11386
11387     /* Set the command */
11388     q_params.cmd = ECORE_Q_CMD_INIT;
11389
11390     /* Change the state to INIT */
11391     rc = ecore_queue_state_change(sc, &q_params);
11392     if (rc) {
11393         BLOGE(sc, "Queue(%d) INIT failed rc = %d\n", fp->index, rc);
11394         return (rc);
11395     }
11396
11397     BLOGD(sc, DBG_LOAD, "init complete\n");
11398
11399     /* now move the Queue to the SETUP state */
11400     memset(setup_params, 0, sizeof(*setup_params));
11401
11402     /* set Queue flags */
11403     setup_params->flags = bxe_get_q_flags(sc, fp, leading);
11404
11405     /* set general SETUP parameters */
11406     bxe_pf_q_prep_general(sc, fp, &setup_params->gen_params,
11407                           FIRST_TX_COS_INDEX);
11408
11409     bxe_pf_rx_q_prep(sc, fp,
11410                      &setup_params->pause_params,
11411                      &setup_params->rxq_params);
11412
11413     bxe_pf_tx_q_prep(sc, fp,
11414                      &setup_params->txq_params,
11415                      FIRST_TX_COS_INDEX);
11416
11417     /* Set the command */
11418     q_params.cmd = ECORE_Q_CMD_SETUP;
11419
11420     /* change the state to SETUP */
11421     rc = ecore_queue_state_change(sc, &q_params);
11422     if (rc) {
11423         BLOGE(sc, "Queue(%d) SETUP failed (rc = %d)\n", fp->index, rc);
11424         return (rc);
11425     }
11426
11427     return (rc);
11428 }
11429
11430 static int
11431 bxe_setup_leading(struct bxe_softc *sc)
11432 {
11433     return (bxe_setup_queue(sc, &sc->fp[0], TRUE));
11434 }
11435
11436 static int
11437 bxe_config_rss_pf(struct bxe_softc            *sc,
11438                   struct ecore_rss_config_obj *rss_obj,
11439                   uint8_t                     config_hash)
11440 {
11441     struct ecore_config_rss_params params = { NULL };
11442     int i;
11443
11444     /*
11445      * Although RSS is meaningless when there is a single HW queue we
11446      * still need it enabled in order to have HW Rx hash generated.
11447      */
11448
11449     params.rss_obj = rss_obj;
11450
11451     bxe_set_bit(RAMROD_COMP_WAIT, &params.ramrod_flags);
11452
11453     bxe_set_bit(ECORE_RSS_MODE_REGULAR, &params.rss_flags);
11454
11455     /* RSS configuration */
11456     bxe_set_bit(ECORE_RSS_IPV4, &params.rss_flags);
11457     bxe_set_bit(ECORE_RSS_IPV4_TCP, &params.rss_flags);
11458     bxe_set_bit(ECORE_RSS_IPV6, &params.rss_flags);
11459     bxe_set_bit(ECORE_RSS_IPV6_TCP, &params.rss_flags);
11460     if (rss_obj->udp_rss_v4) {
11461         bxe_set_bit(ECORE_RSS_IPV4_UDP, &params.rss_flags);
11462     }
11463     if (rss_obj->udp_rss_v6) {
11464         bxe_set_bit(ECORE_RSS_IPV6_UDP, &params.rss_flags);
11465     }
11466
11467     /* Hash bits */
11468     params.rss_result_mask = MULTI_MASK;
11469
11470     memcpy(params.ind_table, rss_obj->ind_table, sizeof(params.ind_table));
11471
11472     if (config_hash) {
11473         /* RSS keys */
11474         for (i = 0; i < sizeof(params.rss_key) / 4; i++) {
11475             params.rss_key[i] = arc4random();
11476         }
11477
11478         bxe_set_bit(ECORE_RSS_SET_SRCH, &params.rss_flags);
11479     }
11480
11481     return (ecore_config_rss(sc, &params));
11482 }
11483
11484 static int
11485 bxe_config_rss_eth(struct bxe_softc *sc,
11486                    uint8_t          config_hash)
11487 {
11488     return (bxe_config_rss_pf(sc, &sc->rss_conf_obj, config_hash));
11489 }
11490
11491 static int
11492 bxe_init_rss_pf(struct bxe_softc *sc)
11493 {
11494     uint8_t num_eth_queues = BXE_NUM_ETH_QUEUES(sc);
11495     int i;
11496
11497     /*
11498      * Prepare the initial contents of the indirection table if
11499      * RSS is enabled
11500      */
11501     for (i = 0; i < sizeof(sc->rss_conf_obj.ind_table); i++) {
11502         sc->rss_conf_obj.ind_table[i] =
11503             (sc->fp->cl_id + (i % num_eth_queues));
11504     }
11505
11506     if (sc->udp_rss) {
11507         sc->rss_conf_obj.udp_rss_v4 = sc->rss_conf_obj.udp_rss_v6 = 1;
11508     }
11509
11510     /*
11511      * For 57710 and 57711 SEARCHER configuration (rss_keys) is
11512      * per-port, so if explicit configuration is needed, do it only
11513      * for a PMF.
11514      *
11515      * For 57712 and newer it's a per-function configuration.
11516      */
11517     return (bxe_config_rss_eth(sc, sc->port.pmf || !CHIP_IS_E1x(sc)));
11518 }
11519
11520 static int
11521 bxe_set_mac_one(struct bxe_softc          *sc,
11522                 uint8_t                   *mac,
11523                 struct ecore_vlan_mac_obj *obj,
11524                 uint8_t                   set,
11525                 int                       mac_type,
11526                 unsigned long             *ramrod_flags)
11527 {
11528     struct ecore_vlan_mac_ramrod_params ramrod_param;
11529     int rc;
11530
11531     memset(&ramrod_param, 0, sizeof(ramrod_param));
11532
11533     /* fill in general parameters */
11534     ramrod_param.vlan_mac_obj = obj;
11535     ramrod_param.ramrod_flags = *ramrod_flags;
11536
11537     /* fill a user request section if needed */
11538     if (!bxe_test_bit(RAMROD_CONT, ramrod_flags)) {
11539         memcpy(ramrod_param.user_req.u.mac.mac, mac, ETH_ALEN);
11540
11541         bxe_set_bit(mac_type, &ramrod_param.user_req.vlan_mac_flags);
11542
11543         /* Set the command: ADD or DEL */
11544         ramrod_param.user_req.cmd = (set) ? ECORE_VLAN_MAC_ADD :
11545                                             ECORE_VLAN_MAC_DEL;
11546     }
11547
11548     rc = ecore_config_vlan_mac(sc, &ramrod_param);
11549
11550     if (rc == ECORE_EXISTS) {
11551         BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
11552         /* do not treat adding same MAC as error */
11553         rc = 0;
11554     } else if (rc < 0) {
11555         BLOGE(sc, "%s MAC failed (%d)\n", (set ? "Set" : "Delete"), rc);
11556     }
11557
11558     return (rc);
11559 }
11560
11561 static int
11562 bxe_set_eth_mac(struct bxe_softc *sc,
11563                 uint8_t          set)
11564 {
11565     unsigned long ramrod_flags = 0;
11566
11567     BLOGD(sc, DBG_LOAD, "Adding Ethernet MAC\n");
11568
11569     bxe_set_bit(RAMROD_COMP_WAIT, &ramrod_flags);
11570
11571     /* Eth MAC is set on RSS leading client (fp[0]) */
11572     return (bxe_set_mac_one(sc, sc->link_params.mac_addr,
11573                             &sc->sp_objs->mac_obj,
11574                             set, ECORE_ETH_MAC, &ramrod_flags));
11575 }
11576
11577 static int
11578 bxe_get_cur_phy_idx(struct bxe_softc *sc)
11579 {
11580     uint32_t sel_phy_idx = 0;
11581
11582     if (sc->link_params.num_phys <= 1) {
11583         return (ELINK_INT_PHY);
11584     }
11585
11586     if (sc->link_vars.link_up) {
11587         sel_phy_idx = ELINK_EXT_PHY1;
11588         /* In case link is SERDES, check if the ELINK_EXT_PHY2 is the one */
11589         if ((sc->link_vars.link_status & LINK_STATUS_SERDES_LINK) &&
11590             (sc->link_params.phy[ELINK_EXT_PHY2].supported &
11591              ELINK_SUPPORTED_FIBRE))
11592             sel_phy_idx = ELINK_EXT_PHY2;
11593     } else {
11594         switch (elink_phy_selection(&sc->link_params)) {
11595         case PORT_HW_CFG_PHY_SELECTION_HARDWARE_DEFAULT:
11596         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY:
11597         case PORT_HW_CFG_PHY_SELECTION_FIRST_PHY_PRIORITY:
11598                sel_phy_idx = ELINK_EXT_PHY1;
11599                break;
11600         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY:
11601         case PORT_HW_CFG_PHY_SELECTION_SECOND_PHY_PRIORITY:
11602                sel_phy_idx = ELINK_EXT_PHY2;
11603                break;
11604         }
11605     }
11606
11607     return (sel_phy_idx);
11608 }
11609
11610 static int
11611 bxe_get_link_cfg_idx(struct bxe_softc *sc)
11612 {
11613     uint32_t sel_phy_idx = bxe_get_cur_phy_idx(sc);
11614
11615     /*
11616      * The selected activated PHY is always after swapping (in case PHY
11617      * swapping is enabled). So when swapping is enabled, we need to reverse
11618      * the configuration
11619      */
11620
11621     if (sc->link_params.multi_phy_config & PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
11622         if (sel_phy_idx == ELINK_EXT_PHY1)
11623             sel_phy_idx = ELINK_EXT_PHY2;
11624         else if (sel_phy_idx == ELINK_EXT_PHY2)
11625             sel_phy_idx = ELINK_EXT_PHY1;
11626     }
11627
11628     return (ELINK_LINK_CONFIG_IDX(sel_phy_idx));
11629 }
11630
11631 static void
11632 bxe_set_requested_fc(struct bxe_softc *sc)
11633 {
11634     /*
11635      * Initialize link parameters structure variables
11636      * It is recommended to turn off RX FC for jumbo frames
11637      * for better performance
11638      */
11639     if (CHIP_IS_E1x(sc) && (sc->mtu > 5000)) {
11640         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_TX;
11641     } else {
11642         sc->link_params.req_fc_auto_adv = ELINK_FLOW_CTRL_BOTH;
11643     }
11644 }
11645
11646 static void
11647 bxe_calc_fc_adv(struct bxe_softc *sc)
11648 {
11649     uint8_t cfg_idx = bxe_get_link_cfg_idx(sc);
11650     switch (sc->link_vars.ieee_fc &
11651             MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_MASK) {
11652     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_NONE:
11653     default:
11654         sc->port.advertising[cfg_idx] &= ~(ADVERTISED_Asym_Pause |
11655                                            ADVERTISED_Pause);
11656         break;
11657
11658     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_BOTH:
11659         sc->port.advertising[cfg_idx] |= (ADVERTISED_Asym_Pause |
11660                                           ADVERTISED_Pause);
11661         break;
11662
11663     case MDIO_COMBO_IEEE0_AUTO_NEG_ADV_PAUSE_ASYMMETRIC:
11664         sc->port.advertising[cfg_idx] |= ADVERTISED_Asym_Pause;
11665         break;
11666     }
11667 }
11668
11669 static uint16_t
11670 bxe_get_mf_speed(struct bxe_softc *sc)
11671 {
11672     uint16_t line_speed = sc->link_vars.line_speed;
11673     if (IS_MF(sc)) {
11674         uint16_t maxCfg =
11675             bxe_extract_max_cfg(sc, sc->devinfo.mf_info.mf_config[SC_VN(sc)]);
11676
11677         /* calculate the current MAX line speed limit for the MF devices */
11678         if (IS_MF_SI(sc)) {
11679             line_speed = (line_speed * maxCfg) / 100;
11680         } else { /* SD mode */
11681             uint16_t vn_max_rate = maxCfg * 100;
11682
11683             if (vn_max_rate < line_speed) {
11684                 line_speed = vn_max_rate;
11685             }
11686         }
11687     }
11688
11689     return (line_speed);
11690 }
11691
11692 static void
11693 bxe_fill_report_data(struct bxe_softc            *sc,
11694                      struct bxe_link_report_data *data)
11695 {
11696     uint16_t line_speed = bxe_get_mf_speed(sc);
11697
11698     memset(data, 0, sizeof(*data));
11699
11700     /* fill the report data with the effective line speed */
11701     data->line_speed = line_speed;
11702
11703     /* Link is down */
11704     if (!sc->link_vars.link_up || (sc->flags & BXE_MF_FUNC_DIS)) {
11705         bxe_set_bit(BXE_LINK_REPORT_LINK_DOWN, &data->link_report_flags);
11706     }
11707
11708     /* Full DUPLEX */
11709     if (sc->link_vars.duplex == DUPLEX_FULL) {
11710         bxe_set_bit(BXE_LINK_REPORT_FULL_DUPLEX, &data->link_report_flags);
11711     }
11712
11713     /* Rx Flow Control is ON */
11714     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_RX) {
11715         bxe_set_bit(BXE_LINK_REPORT_RX_FC_ON, &data->link_report_flags);
11716     }
11717
11718     /* Tx Flow Control is ON */
11719     if (sc->link_vars.flow_ctrl & ELINK_FLOW_CTRL_TX) {
11720         bxe_set_bit(BXE_LINK_REPORT_TX_FC_ON, &data->link_report_flags);
11721     }
11722 }
11723
11724 /* report link status to OS, should be called under phy_lock */
11725 static void
11726 bxe_link_report_locked(struct bxe_softc *sc)
11727 {
11728     struct bxe_link_report_data cur_data;
11729
11730     /* reread mf_cfg */
11731     if (IS_PF(sc) && !CHIP_IS_E1(sc)) {
11732         bxe_read_mf_cfg(sc);
11733     }
11734
11735     /* Read the current link report info */
11736     bxe_fill_report_data(sc, &cur_data);
11737
11738     /* Don't report link down or exactly the same link status twice */
11739     if (!memcmp(&cur_data, &sc->last_reported_link, sizeof(cur_data)) ||
11740         (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11741                       &sc->last_reported_link.link_report_flags) &&
11742          bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11743                       &cur_data.link_report_flags))) {
11744         return;
11745     }
11746
11747     sc->link_cnt++;
11748
11749     /* report new link params and remember the state for the next time */
11750     memcpy(&sc->last_reported_link, &cur_data, sizeof(cur_data));
11751
11752     if (bxe_test_bit(BXE_LINK_REPORT_LINK_DOWN,
11753                      &cur_data.link_report_flags)) {
11754         if_link_state_change(sc->ifnet, LINK_STATE_DOWN);
11755         BLOGI(sc, "NIC Link is Down\n");
11756     } else {
11757         const char *duplex;
11758         const char *flow;
11759
11760         if (bxe_test_and_clear_bit(BXE_LINK_REPORT_FULL_DUPLEX,
11761                                    &cur_data.link_report_flags)) {
11762             duplex = "full";
11763         } else {
11764             duplex = "half";
11765         }
11766
11767         /*
11768          * Handle the FC at the end so that only these flags would be
11769          * possibly set. This way we may easily check if there is no FC
11770          * enabled.
11771          */
11772         if (cur_data.link_report_flags) {
11773             if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11774                              &cur_data.link_report_flags) &&
11775                 bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11776                              &cur_data.link_report_flags)) {
11777                 flow = "ON - receive & transmit";
11778             } else if (bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11779                                     &cur_data.link_report_flags) &&
11780                        !bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11781                                      &cur_data.link_report_flags)) {
11782                 flow = "ON - receive";
11783             } else if (!bxe_test_bit(BXE_LINK_REPORT_RX_FC_ON,
11784                                      &cur_data.link_report_flags) &&
11785                        bxe_test_bit(BXE_LINK_REPORT_TX_FC_ON,
11786                                     &cur_data.link_report_flags)) {
11787                 flow = "ON - transmit";
11788             } else {
11789                 flow = "none"; /* possible? */
11790             }
11791         } else {
11792             flow = "none";
11793         }
11794
11795         if_link_state_change(sc->ifnet, LINK_STATE_UP);
11796         BLOGI(sc, "NIC Link is Up, %d Mbps %s duplex, Flow control: %s\n",
11797               cur_data.line_speed, duplex, flow);
11798     }
11799 }
11800
11801 static void
11802 bxe_link_report(struct bxe_softc *sc)
11803 {
11804     bxe_acquire_phy_lock(sc);
11805     bxe_link_report_locked(sc);
11806     bxe_release_phy_lock(sc);
11807 }
11808
11809 static void
11810 bxe_link_status_update(struct bxe_softc *sc)
11811 {
11812     if (sc->state != BXE_STATE_OPEN) {
11813         return;
11814     }
11815
11816     if (IS_PF(sc) && !CHIP_REV_IS_SLOW(sc)) {
11817         elink_link_status_update(&sc->link_params, &sc->link_vars);
11818     } else {
11819         sc->port.supported[0] |= (ELINK_SUPPORTED_10baseT_Half |
11820                                   ELINK_SUPPORTED_10baseT_Full |
11821                                   ELINK_SUPPORTED_100baseT_Half |
11822                                   ELINK_SUPPORTED_100baseT_Full |
11823                                   ELINK_SUPPORTED_1000baseT_Full |
11824                                   ELINK_SUPPORTED_2500baseX_Full |
11825                                   ELINK_SUPPORTED_10000baseT_Full |
11826                                   ELINK_SUPPORTED_TP |
11827                                   ELINK_SUPPORTED_FIBRE |
11828                                   ELINK_SUPPORTED_Autoneg |
11829                                   ELINK_SUPPORTED_Pause |
11830                                   ELINK_SUPPORTED_Asym_Pause);
11831         sc->port.advertising[0] = sc->port.supported[0];
11832
11833         sc->link_params.sc                = sc;
11834         sc->link_params.port              = SC_PORT(sc);
11835         sc->link_params.req_duplex[0]     = DUPLEX_FULL;
11836         sc->link_params.req_flow_ctrl[0]  = ELINK_FLOW_CTRL_NONE;
11837         sc->link_params.req_line_speed[0] = SPEED_10000;
11838         sc->link_params.speed_cap_mask[0] = 0x7f0000;
11839         sc->link_params.switch_cfg        = ELINK_SWITCH_CFG_10G;
11840
11841         if (CHIP_REV_IS_FPGA(sc)) {
11842             sc->link_vars.mac_type    = ELINK_MAC_TYPE_EMAC;
11843             sc->link_vars.line_speed  = ELINK_SPEED_1000;
11844             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11845                                          LINK_STATUS_SPEED_AND_DUPLEX_1000TFD);
11846         } else {
11847             sc->link_vars.mac_type    = ELINK_MAC_TYPE_BMAC;
11848             sc->link_vars.line_speed  = ELINK_SPEED_10000;
11849             sc->link_vars.link_status = (LINK_STATUS_LINK_UP |
11850                                          LINK_STATUS_SPEED_AND_DUPLEX_10GTFD);
11851         }
11852
11853         sc->link_vars.link_up = 1;
11854
11855         sc->link_vars.duplex    = DUPLEX_FULL;
11856         sc->link_vars.flow_ctrl = ELINK_FLOW_CTRL_NONE;
11857
11858         if (IS_PF(sc)) {
11859             REG_WR(sc, NIG_REG_EGRESS_DRAIN0_MODE + sc->link_params.port*4, 0);
11860             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11861             bxe_link_report(sc);
11862         }
11863     }
11864
11865     if (IS_PF(sc)) {
11866         if (sc->link_vars.link_up) {
11867             bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11868         } else {
11869             bxe_stats_handle(sc, STATS_EVENT_STOP);
11870         }
11871         bxe_link_report(sc);
11872     } else {
11873         bxe_link_report(sc);
11874         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11875     }
11876 }
11877
11878 static int
11879 bxe_initial_phy_init(struct bxe_softc *sc,
11880                      int              load_mode)
11881 {
11882     int rc, cfg_idx = bxe_get_link_cfg_idx(sc);
11883     uint16_t req_line_speed = sc->link_params.req_line_speed[cfg_idx];
11884     struct elink_params *lp = &sc->link_params;
11885
11886     bxe_set_requested_fc(sc);
11887
11888     if (CHIP_REV_IS_SLOW(sc)) {
11889         uint32_t bond = CHIP_BOND_ID(sc);
11890         uint32_t feat = 0;
11891
11892         if (CHIP_IS_E2(sc) && CHIP_IS_MODE_4_PORT(sc)) {
11893             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11894         } else if (bond & 0x4) {
11895             if (CHIP_IS_E3(sc)) {
11896                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_XMAC;
11897             } else {
11898                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_BMAC;
11899             }
11900         } else if (bond & 0x8) {
11901             if (CHIP_IS_E3(sc)) {
11902                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_UMAC;
11903             } else {
11904                 feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11905             }
11906         }
11907
11908         /* disable EMAC for E3 and above */
11909         if (bond & 0x2) {
11910             feat |= ELINK_FEATURE_CONFIG_EMUL_DISABLE_EMAC;
11911         }
11912
11913         sc->link_params.feature_config_flags |= feat;
11914     }
11915
11916     bxe_acquire_phy_lock(sc);
11917
11918     if (load_mode == LOAD_DIAG) {
11919         lp->loopback_mode = ELINK_LOOPBACK_XGXS;
11920         /* Prefer doing PHY loopback at 10G speed, if possible */
11921         if (lp->req_line_speed[cfg_idx] < ELINK_SPEED_10000) {
11922             if (lp->speed_cap_mask[cfg_idx] &
11923                 PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
11924                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_10000;
11925             } else {
11926                 lp->req_line_speed[cfg_idx] = ELINK_SPEED_1000;
11927             }
11928         }
11929     }
11930
11931     if (load_mode == LOAD_LOOPBACK_EXT) {
11932         lp->loopback_mode = ELINK_LOOPBACK_EXT;
11933     }
11934
11935     rc = elink_phy_init(&sc->link_params, &sc->link_vars);
11936
11937     bxe_release_phy_lock(sc);
11938
11939     bxe_calc_fc_adv(sc);
11940
11941     if (sc->link_vars.link_up) {
11942         bxe_stats_handle(sc, STATS_EVENT_LINK_UP);
11943         bxe_link_report(sc);
11944     }
11945
11946     if (!CHIP_REV_IS_SLOW(sc)) {
11947         bxe_periodic_start(sc);
11948     }
11949
11950     sc->link_params.req_line_speed[cfg_idx] = req_line_speed;
11951     return (rc);
11952 }
11953
11954 /* must be called under IF_ADDR_LOCK */
11955 static int
11956 bxe_init_mcast_macs_list(struct bxe_softc                 *sc,
11957                          struct ecore_mcast_ramrod_params *p)
11958 {
11959     struct ifnet *ifp = sc->ifnet;
11960     int mc_count = 0;
11961     struct ifmultiaddr *ifma;
11962     struct ecore_mcast_list_elem *mc_mac;
11963
11964     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
11965         if (ifma->ifma_addr->sa_family != AF_LINK) {
11966             continue;
11967         }
11968
11969         mc_count++;
11970     }
11971
11972     ECORE_LIST_INIT(&p->mcast_list);
11973     p->mcast_list_len = 0;
11974
11975     if (!mc_count) {
11976         return (0);
11977     }
11978
11979     mc_mac = malloc(sizeof(*mc_mac) * mc_count, M_DEVBUF,
11980                     (M_NOWAIT | M_ZERO));
11981     if (!mc_mac) {
11982         BLOGE(sc, "Failed to allocate temp mcast list\n");
11983         return (-1);
11984     }
11985     bzero(mc_mac, (sizeof(*mc_mac) * mc_count));
11986
11987     TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
11988         if (ifma->ifma_addr->sa_family != AF_LINK) {
11989             continue;
11990         }
11991
11992         mc_mac->mac = (uint8_t *)LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
11993         ECORE_LIST_PUSH_TAIL(&mc_mac->link, &p->mcast_list);
11994
11995         BLOGD(sc, DBG_LOAD,
11996               "Setting MCAST %02X:%02X:%02X:%02X:%02X:%02X\n",
11997               mc_mac->mac[0], mc_mac->mac[1], mc_mac->mac[2],
11998               mc_mac->mac[3], mc_mac->mac[4], mc_mac->mac[5]);
11999
12000         mc_mac++;
12001     }
12002
12003     p->mcast_list_len = mc_count;
12004
12005     return (0);
12006 }
12007
12008 static void
12009 bxe_free_mcast_macs_list(struct ecore_mcast_ramrod_params *p)
12010 {
12011     struct ecore_mcast_list_elem *mc_mac =
12012         ECORE_LIST_FIRST_ENTRY(&p->mcast_list,
12013                                struct ecore_mcast_list_elem,
12014                                link);
12015
12016     if (mc_mac) {
12017         /* only a single free as all mc_macs are in the same heap array */
12018         free(mc_mac, M_DEVBUF);
12019     }
12020 }
12021
12022 static int
12023 bxe_set_mc_list(struct bxe_softc *sc)
12024 {
12025     struct ecore_mcast_ramrod_params rparam = { NULL };
12026     int rc = 0;
12027
12028     rparam.mcast_obj = &sc->mcast_obj;
12029
12030     BXE_MCAST_LOCK(sc);
12031
12032     /* first, clear all configured multicast MACs */
12033     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_DEL);
12034     if (rc < 0) {
12035         BLOGE(sc, "Failed to clear multicast configuration: %d\n", rc);
12036         BXE_MCAST_UNLOCK(sc);
12037         return (rc);
12038     }
12039
12040     /* configure a new MACs list */
12041     rc = bxe_init_mcast_macs_list(sc, &rparam);
12042     if (rc) {
12043         BLOGE(sc, "Failed to create mcast MACs list (%d)\n", rc);
12044         BXE_MCAST_UNLOCK(sc);
12045         return (rc);
12046     }
12047
12048     /* Now add the new MACs */
12049     rc = ecore_config_mcast(sc, &rparam, ECORE_MCAST_CMD_ADD);
12050     if (rc < 0) {
12051         BLOGE(sc, "Failed to set new mcast config (%d)\n", rc);
12052     }
12053
12054     bxe_free_mcast_macs_list(&rparam);
12055
12056     BXE_MCAST_UNLOCK(sc);
12057
12058     return (rc);
12059 }
12060
12061 static int
12062 bxe_set_uc_list(struct bxe_softc *sc)
12063 {
12064     struct ifnet *ifp = sc->ifnet;
12065     struct ecore_vlan_mac_obj *mac_obj = &sc->sp_objs->mac_obj;
12066     struct ifaddr *ifa;
12067     unsigned long ramrod_flags = 0;
12068     int rc;
12069
12070 #if __FreeBSD_version < 800000
12071     IF_ADDR_LOCK(ifp);
12072 #else
12073     if_addr_rlock(ifp);
12074 #endif
12075
12076     /* first schedule a cleanup up of old configuration */
12077     rc = bxe_del_all_macs(sc, mac_obj, ECORE_UC_LIST_MAC, FALSE);
12078     if (rc < 0) {
12079         BLOGE(sc, "Failed to schedule delete of all ETH MACs (%d)\n", rc);
12080 #if __FreeBSD_version < 800000
12081         IF_ADDR_UNLOCK(ifp);
12082 #else
12083         if_addr_runlock(ifp);
12084 #endif
12085         return (rc);
12086     }
12087
12088     ifa = ifp->if_addr;
12089     while (ifa) {
12090         if (ifa->ifa_addr->sa_family != AF_LINK) {
12091             ifa = TAILQ_NEXT(ifa, ifa_link);
12092             continue;
12093         }
12094
12095         rc = bxe_set_mac_one(sc, (uint8_t *)LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
12096                              mac_obj, TRUE, ECORE_UC_LIST_MAC, &ramrod_flags);
12097         if (rc == -EEXIST) {
12098             BLOGD(sc, DBG_SP, "Failed to schedule ADD operations (EEXIST)\n");
12099             /* do not treat adding same MAC as an error */
12100             rc = 0;
12101         } else if (rc < 0) {
12102             BLOGE(sc, "Failed to schedule ADD operations (%d)\n", rc);
12103 #if __FreeBSD_version < 800000
12104             IF_ADDR_UNLOCK(ifp);
12105 #else
12106             if_addr_runlock(ifp);
12107 #endif
12108             return (rc);
12109         }
12110
12111         ifa = TAILQ_NEXT(ifa, ifa_link);
12112     }
12113
12114 #if __FreeBSD_version < 800000
12115     IF_ADDR_UNLOCK(ifp);
12116 #else
12117     if_addr_runlock(ifp);
12118 #endif
12119
12120     /* Execute the pending commands */
12121     bit_set(&ramrod_flags, RAMROD_CONT);
12122     return (bxe_set_mac_one(sc, NULL, mac_obj, FALSE /* don't care */,
12123                             ECORE_UC_LIST_MAC, &ramrod_flags));
12124 }
12125
12126 static void
12127 bxe_set_rx_mode(struct bxe_softc *sc)
12128 {
12129     struct ifnet *ifp = sc->ifnet;
12130     uint32_t rx_mode = BXE_RX_MODE_NORMAL;
12131
12132     if (sc->state != BXE_STATE_OPEN) {
12133         BLOGD(sc, DBG_SP, "state is %x, returning\n", sc->state);
12134         return;
12135     }
12136
12137     BLOGD(sc, DBG_SP, "ifp->if_flags=0x%x\n", ifp->if_flags);
12138
12139     if (ifp->if_flags & IFF_PROMISC) {
12140         rx_mode = BXE_RX_MODE_PROMISC;
12141     } else if ((ifp->if_flags & IFF_ALLMULTI) ||
12142                ((ifp->if_amcount > BXE_MAX_MULTICAST) &&
12143                 CHIP_IS_E1(sc))) {
12144         rx_mode = BXE_RX_MODE_ALLMULTI;
12145     } else {
12146         if (IS_PF(sc)) {
12147             /* some multicasts */
12148             if (bxe_set_mc_list(sc) < 0) {
12149                 rx_mode = BXE_RX_MODE_ALLMULTI;
12150             }
12151             if (bxe_set_uc_list(sc) < 0) {
12152                 rx_mode = BXE_RX_MODE_PROMISC;
12153             }
12154         }
12155     }
12156
12157     sc->rx_mode = rx_mode;
12158
12159     /* schedule the rx_mode command */
12160     if (bxe_test_bit(ECORE_FILTER_RX_MODE_PENDING, &sc->sp_state)) {
12161         BLOGD(sc, DBG_LOAD, "Scheduled setting rx_mode with ECORE...\n");
12162         bxe_set_bit(ECORE_FILTER_RX_MODE_SCHED, &sc->sp_state);
12163         return;
12164     }
12165
12166     if (IS_PF(sc)) {
12167         bxe_set_storm_rx_mode(sc);
12168     }
12169 }
12170
12171
12172 /* update flags in shmem */
12173 static void
12174 bxe_update_drv_flags(struct bxe_softc *sc,
12175                      uint32_t         flags,
12176                      uint32_t         set)
12177 {
12178     uint32_t drv_flags;
12179
12180     if (SHMEM2_HAS(sc, drv_flags)) {
12181         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12182         drv_flags = SHMEM2_RD(sc, drv_flags);
12183
12184         if (set) {
12185             SET_FLAGS(drv_flags, flags);
12186         } else {
12187             RESET_FLAGS(drv_flags, flags);
12188         }
12189
12190         SHMEM2_WR(sc, drv_flags, drv_flags);
12191         BLOGD(sc, DBG_LOAD, "drv_flags 0x%08x\n", drv_flags);
12192
12193         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_DRV_FLAGS);
12194     }
12195 }
12196
12197 /* periodic timer callout routine, only runs when the interface is up */
12198
12199 static void
12200 bxe_periodic_callout_func(void *xsc)
12201 {
12202     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12203     int i;
12204
12205     if (!BXE_CORE_TRYLOCK(sc)) {
12206         /* just bail and try again next time */
12207
12208         if ((sc->state == BXE_STATE_OPEN) &&
12209             (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12210             /* schedule the next periodic callout */
12211             callout_reset(&sc->periodic_callout, hz,
12212                           bxe_periodic_callout_func, sc);
12213         }
12214
12215         return;
12216     }
12217
12218     if ((sc->state != BXE_STATE_OPEN) ||
12219         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_STOP)) {
12220         BLOGW(sc, "periodic callout exit (state=0x%x)\n", sc->state);
12221         BXE_CORE_UNLOCK(sc);
12222         return;
12223     }
12224
12225
12226     /* Check for TX timeouts on any fastpath. */
12227     FOR_EACH_QUEUE(sc, i) {
12228         if (bxe_watchdog(sc, &sc->fp[i]) != 0) {
12229             /* Ruh-Roh, chip was reset! */
12230             break;
12231         }
12232     }
12233
12234     if (!CHIP_REV_IS_SLOW(sc)) {
12235         /*
12236          * This barrier is needed to ensure the ordering between the writing
12237          * to the sc->port.pmf in the bxe_nic_load() or bxe_pmf_update() and
12238          * the reading here.
12239          */
12240         mb();
12241         if (sc->port.pmf) {
12242             bxe_acquire_phy_lock(sc);
12243             elink_period_func(&sc->link_params, &sc->link_vars);
12244             bxe_release_phy_lock(sc);
12245         }
12246     }
12247
12248     if (IS_PF(sc) && !(sc->flags & BXE_NO_PULSE)) {
12249         int mb_idx = SC_FW_MB_IDX(sc);
12250         uint32_t drv_pulse;
12251         uint32_t mcp_pulse;
12252
12253         ++sc->fw_drv_pulse_wr_seq;
12254         sc->fw_drv_pulse_wr_seq &= DRV_PULSE_SEQ_MASK;
12255
12256         drv_pulse = sc->fw_drv_pulse_wr_seq;
12257         bxe_drv_pulse(sc);
12258
12259         mcp_pulse = (SHMEM_RD(sc, func_mb[mb_idx].mcp_pulse_mb) &
12260                      MCP_PULSE_SEQ_MASK);
12261
12262         /*
12263          * The delta between driver pulse and mcp response should
12264          * be 1 (before mcp response) or 0 (after mcp response).
12265          */
12266         if ((drv_pulse != mcp_pulse) &&
12267             (drv_pulse != ((mcp_pulse + 1) & MCP_PULSE_SEQ_MASK))) {
12268             /* someone lost a heartbeat... */
12269             BLOGE(sc, "drv_pulse (0x%x) != mcp_pulse (0x%x)\n",
12270                   drv_pulse, mcp_pulse);
12271         }
12272     }
12273
12274     /* state is BXE_STATE_OPEN */
12275     bxe_stats_handle(sc, STATS_EVENT_UPDATE);
12276
12277     BXE_CORE_UNLOCK(sc);
12278
12279     if ((sc->state == BXE_STATE_OPEN) &&
12280         (atomic_load_acq_long(&sc->periodic_flags) == PERIODIC_GO)) {
12281         /* schedule the next periodic callout */
12282         callout_reset(&sc->periodic_callout, hz,
12283                       bxe_periodic_callout_func, sc);
12284     }
12285 }
12286
12287 static void
12288 bxe_periodic_start(struct bxe_softc *sc)
12289 {
12290     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_GO);
12291     callout_reset(&sc->periodic_callout, hz, bxe_periodic_callout_func, sc);
12292 }
12293
12294 static void
12295 bxe_periodic_stop(struct bxe_softc *sc)
12296 {
12297     atomic_store_rel_long(&sc->periodic_flags, PERIODIC_STOP);
12298     callout_drain(&sc->periodic_callout);
12299 }
12300
12301 /* start the controller */
12302 static __noinline int
12303 bxe_nic_load(struct bxe_softc *sc,
12304              int              load_mode)
12305 {
12306     uint32_t val;
12307     int load_code = 0;
12308     int i, rc = 0;
12309
12310     BXE_CORE_LOCK_ASSERT(sc);
12311
12312     BLOGD(sc, DBG_LOAD, "Starting NIC load...\n");
12313
12314     sc->state = BXE_STATE_OPENING_WAITING_LOAD;
12315
12316     if (IS_PF(sc)) {
12317         /* must be called before memory allocation and HW init */
12318         bxe_ilt_set_info(sc);
12319     }
12320
12321     sc->last_reported_link_state = LINK_STATE_UNKNOWN;
12322
12323     bxe_set_fp_rx_buf_size(sc);
12324
12325     if (bxe_alloc_fp_buffers(sc) != 0) {
12326         BLOGE(sc, "Failed to allocate fastpath memory\n");
12327         sc->state = BXE_STATE_CLOSED;
12328         rc = ENOMEM;
12329         goto bxe_nic_load_error0;
12330     }
12331
12332     if (bxe_alloc_mem(sc) != 0) {
12333         sc->state = BXE_STATE_CLOSED;
12334         rc = ENOMEM;
12335         goto bxe_nic_load_error0;
12336     }
12337
12338     if (bxe_alloc_fw_stats_mem(sc) != 0) {
12339         sc->state = BXE_STATE_CLOSED;
12340         rc = ENOMEM;
12341         goto bxe_nic_load_error0;
12342     }
12343
12344     if (IS_PF(sc)) {
12345         /* set pf load just before approaching the MCP */
12346         bxe_set_pf_load(sc);
12347
12348         /* if MCP exists send load request and analyze response */
12349         if (!BXE_NOMCP(sc)) {
12350             /* attempt to load pf */
12351             if (bxe_nic_load_request(sc, &load_code) != 0) {
12352                 sc->state = BXE_STATE_CLOSED;
12353                 rc = ENXIO;
12354                 goto bxe_nic_load_error1;
12355             }
12356
12357             /* what did the MCP say? */
12358             if (bxe_nic_load_analyze_req(sc, load_code) != 0) {
12359                 bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12360                 sc->state = BXE_STATE_CLOSED;
12361                 rc = ENXIO;
12362                 goto bxe_nic_load_error2;
12363             }
12364         } else {
12365             BLOGI(sc, "Device has no MCP!\n");
12366             load_code = bxe_nic_load_no_mcp(sc);
12367         }
12368
12369         /* mark PMF if applicable */
12370         bxe_nic_load_pmf(sc, load_code);
12371
12372         /* Init Function state controlling object */
12373         bxe_init_func_obj(sc);
12374
12375         /* Initialize HW */
12376         if (bxe_init_hw(sc, load_code) != 0) {
12377             BLOGE(sc, "HW init failed\n");
12378             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12379             sc->state = BXE_STATE_CLOSED;
12380             rc = ENXIO;
12381             goto bxe_nic_load_error2;
12382         }
12383     }
12384
12385     /* set ALWAYS_ALIVE bit in shmem */
12386     sc->fw_drv_pulse_wr_seq |= DRV_PULSE_ALWAYS_ALIVE;
12387     bxe_drv_pulse(sc);
12388     sc->flags |= BXE_NO_PULSE;
12389
12390     /* attach interrupts */
12391     if (bxe_interrupt_attach(sc) != 0) {
12392         sc->state = BXE_STATE_CLOSED;
12393         rc = ENXIO;
12394         goto bxe_nic_load_error2;
12395     }
12396
12397     bxe_nic_init(sc, load_code);
12398
12399     /* Init per-function objects */
12400     if (IS_PF(sc)) {
12401         bxe_init_objs(sc);
12402         // XXX bxe_iov_nic_init(sc);
12403
12404         /* set AFEX default VLAN tag to an invalid value */
12405         sc->devinfo.mf_info.afex_def_vlan_tag = -1;
12406         // XXX bxe_nic_load_afex_dcc(sc, load_code);
12407
12408         sc->state = BXE_STATE_OPENING_WAITING_PORT;
12409         rc = bxe_func_start(sc);
12410         if (rc) {
12411             BLOGE(sc, "Function start failed! rc = %d\n", rc);
12412             bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12413             sc->state = BXE_STATE_ERROR;
12414             goto bxe_nic_load_error3;
12415         }
12416
12417         /* send LOAD_DONE command to MCP */
12418         if (!BXE_NOMCP(sc)) {
12419             load_code = bxe_fw_command(sc, DRV_MSG_CODE_LOAD_DONE, 0);
12420             if (!load_code) {
12421                 BLOGE(sc, "MCP response failure, aborting\n");
12422                 sc->state = BXE_STATE_ERROR;
12423                 rc = ENXIO;
12424                 goto bxe_nic_load_error3;
12425             }
12426         }
12427
12428         rc = bxe_setup_leading(sc);
12429         if (rc) {
12430             BLOGE(sc, "Setup leading failed! rc = %d\n", rc);
12431             sc->state = BXE_STATE_ERROR;
12432             goto bxe_nic_load_error3;
12433         }
12434
12435         FOR_EACH_NONDEFAULT_ETH_QUEUE(sc, i) {
12436             rc = bxe_setup_queue(sc, &sc->fp[i], FALSE);
12437             if (rc) {
12438                 BLOGE(sc, "Queue(%d) setup failed rc = %d\n", i, rc);
12439                 sc->state = BXE_STATE_ERROR;
12440                 goto bxe_nic_load_error3;
12441             }
12442         }
12443
12444         rc = bxe_init_rss_pf(sc);
12445         if (rc) {
12446             BLOGE(sc, "PF RSS init failed\n");
12447             sc->state = BXE_STATE_ERROR;
12448             goto bxe_nic_load_error3;
12449         }
12450     }
12451     /* XXX VF */
12452
12453     /* now when Clients are configured we are ready to work */
12454     sc->state = BXE_STATE_OPEN;
12455
12456     /* Configure a ucast MAC */
12457     if (IS_PF(sc)) {
12458         rc = bxe_set_eth_mac(sc, TRUE);
12459     }
12460     if (rc) {
12461         BLOGE(sc, "Setting Ethernet MAC failed rc = %d\n", rc);
12462         sc->state = BXE_STATE_ERROR;
12463         goto bxe_nic_load_error3;
12464     }
12465
12466     if (sc->port.pmf) {
12467         rc = bxe_initial_phy_init(sc, /* XXX load_mode */LOAD_OPEN);
12468         if (rc) {
12469             sc->state = BXE_STATE_ERROR;
12470             goto bxe_nic_load_error3;
12471         }
12472     }
12473
12474     sc->link_params.feature_config_flags &=
12475         ~ELINK_FEATURE_CONFIG_BOOT_FROM_SAN;
12476
12477     /* start fast path */
12478
12479     /* Initialize Rx filter */
12480     bxe_set_rx_mode(sc);
12481
12482     /* start the Tx */
12483     switch (/* XXX load_mode */LOAD_OPEN) {
12484     case LOAD_NORMAL:
12485     case LOAD_OPEN:
12486         break;
12487
12488     case LOAD_DIAG:
12489     case LOAD_LOOPBACK_EXT:
12490         sc->state = BXE_STATE_DIAG;
12491         break;
12492
12493     default:
12494         break;
12495     }
12496
12497     if (sc->port.pmf) {
12498         bxe_update_drv_flags(sc, 1 << DRV_FLAGS_PORT_MASK, 0);
12499     } else {
12500         bxe_link_status_update(sc);
12501     }
12502
12503     /* start the periodic timer callout */
12504     bxe_periodic_start(sc);
12505
12506     if (IS_PF(sc) && SHMEM2_HAS(sc, drv_capabilities_flag)) {
12507         /* mark driver is loaded in shmem2 */
12508         val = SHMEM2_RD(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)]);
12509         SHMEM2_WR(sc, drv_capabilities_flag[SC_FW_MB_IDX(sc)],
12510                   (val |
12511                    DRV_FLAGS_CAPABILITIES_LOADED_SUPPORTED |
12512                    DRV_FLAGS_CAPABILITIES_LOADED_L2));
12513     }
12514
12515     /* wait for all pending SP commands to complete */
12516     if (IS_PF(sc) && !bxe_wait_sp_comp(sc, ~0x0UL)) {
12517         BLOGE(sc, "Timeout waiting for all SPs to complete!\n");
12518         bxe_periodic_stop(sc);
12519         bxe_nic_unload(sc, UNLOAD_CLOSE, FALSE);
12520         return (ENXIO);
12521     }
12522
12523     /* Tell the stack the driver is running! */
12524     sc->ifnet->if_drv_flags = IFF_DRV_RUNNING;
12525
12526     BLOGD(sc, DBG_LOAD, "NIC successfully loaded\n");
12527
12528     return (0);
12529
12530 bxe_nic_load_error3:
12531
12532     if (IS_PF(sc)) {
12533         bxe_int_disable_sync(sc, 1);
12534
12535         /* clean out queued objects */
12536         bxe_squeeze_objects(sc);
12537     }
12538
12539     bxe_interrupt_detach(sc);
12540
12541 bxe_nic_load_error2:
12542
12543     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
12544         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_MCP, 0);
12545         bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE, 0);
12546     }
12547
12548     sc->port.pmf = 0;
12549
12550 bxe_nic_load_error1:
12551
12552     /* clear pf_load status, as it was already set */
12553     if (IS_PF(sc)) {
12554         bxe_clear_pf_load(sc);
12555     }
12556
12557 bxe_nic_load_error0:
12558
12559     bxe_free_fw_stats_mem(sc);
12560     bxe_free_fp_buffers(sc);
12561     bxe_free_mem(sc);
12562
12563     return (rc);
12564 }
12565
12566 static int
12567 bxe_init_locked(struct bxe_softc *sc)
12568 {
12569     int other_engine = SC_PATH(sc) ? 0 : 1;
12570     uint8_t other_load_status, load_status;
12571     uint8_t global = FALSE;
12572     int rc;
12573
12574     BXE_CORE_LOCK_ASSERT(sc);
12575
12576     /* check if the driver is already running */
12577     if (sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) {
12578         BLOGD(sc, DBG_LOAD, "Init called while driver is running!\n");
12579         return (0);
12580     }
12581
12582     bxe_set_power_state(sc, PCI_PM_D0);
12583
12584     /*
12585      * If parity occurred during the unload, then attentions and/or
12586      * RECOVERY_IN_PROGRES may still be set. If so we want the first function
12587      * loaded on the current engine to complete the recovery. Parity recovery
12588      * is only relevant for PF driver.
12589      */
12590     if (IS_PF(sc)) {
12591         other_load_status = bxe_get_load_status(sc, other_engine);
12592         load_status = bxe_get_load_status(sc, SC_PATH(sc));
12593
12594         if (!bxe_reset_is_done(sc, SC_PATH(sc)) ||
12595             bxe_chk_parity_attn(sc, &global, TRUE)) {
12596             do {
12597                 /*
12598                  * If there are attentions and they are in global blocks, set
12599                  * the GLOBAL_RESET bit regardless whether it will be this
12600                  * function that will complete the recovery or not.
12601                  */
12602                 if (global) {
12603                     bxe_set_reset_global(sc);
12604                 }
12605
12606                 /*
12607                  * Only the first function on the current engine should try
12608                  * to recover in open. In case of attentions in global blocks
12609                  * only the first in the chip should try to recover.
12610                  */
12611                 if ((!load_status && (!global || !other_load_status)) &&
12612                     bxe_trylock_leader_lock(sc) && !bxe_leader_reset(sc)) {
12613                     BLOGI(sc, "Recovered during init\n");
12614                     break;
12615                 }
12616
12617                 /* recovery has failed... */
12618                 bxe_set_power_state(sc, PCI_PM_D3hot);
12619                 sc->recovery_state = BXE_RECOVERY_FAILED;
12620
12621                 BLOGE(sc, "Recovery flow hasn't properly "
12622                           "completed yet, try again later. "
12623                           "If you still see this message after a "
12624                           "few retries then power cycle is required.\n");
12625
12626                 rc = ENXIO;
12627                 goto bxe_init_locked_done;
12628             } while (0);
12629         }
12630     }
12631
12632     sc->recovery_state = BXE_RECOVERY_DONE;
12633
12634     rc = bxe_nic_load(sc, LOAD_OPEN);
12635
12636 bxe_init_locked_done:
12637
12638     if (rc) {
12639         /* Tell the stack the driver is NOT running! */
12640         BLOGE(sc, "Initialization failed, "
12641                   "stack notified driver is NOT running!\n");
12642         sc->ifnet->if_drv_flags &= ~IFF_DRV_RUNNING;
12643     }
12644
12645     return (rc);
12646 }
12647
12648 static int
12649 bxe_stop_locked(struct bxe_softc *sc)
12650 {
12651     BXE_CORE_LOCK_ASSERT(sc);
12652     return (bxe_nic_unload(sc, UNLOAD_NORMAL, TRUE));
12653 }
12654
12655 /*
12656  * Handles controller initialization when called from an unlocked routine.
12657  * ifconfig calls this function.
12658  *
12659  * Returns:
12660  *   void
12661  */
12662 static void
12663 bxe_init(void *xsc)
12664 {
12665     struct bxe_softc *sc = (struct bxe_softc *)xsc;
12666
12667     BXE_CORE_LOCK(sc);
12668     bxe_init_locked(sc);
12669     BXE_CORE_UNLOCK(sc);
12670 }
12671
12672 static int
12673 bxe_init_ifnet(struct bxe_softc *sc)
12674 {
12675     struct ifnet *ifp;
12676
12677     /* ifconfig entrypoint for media type/status reporting */
12678     ifmedia_init(&sc->ifmedia, IFM_IMASK,
12679                  bxe_ifmedia_update,
12680                  bxe_ifmedia_status);
12681
12682     /* set the default interface values */
12683     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_FDX | sc->media), 0, NULL);
12684     ifmedia_add(&sc->ifmedia, (IFM_ETHER | IFM_AUTO), 0, NULL);
12685     ifmedia_set(&sc->ifmedia, (IFM_ETHER | IFM_AUTO));
12686
12687     sc->ifmedia.ifm_media = sc->ifmedia.ifm_cur->ifm_media; /* XXX ? */
12688
12689     /* allocate the ifnet structure */
12690     if ((ifp = if_alloc(IFT_ETHER)) == NULL) {
12691         BLOGE(sc, "Interface allocation failed!\n");
12692         return (ENXIO);
12693     }
12694
12695     ifp->if_softc = sc;
12696     if_initname(ifp, device_get_name(sc->dev), device_get_unit(sc->dev));
12697     ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
12698     ifp->if_ioctl = bxe_ioctl;
12699     ifp->if_start = bxe_tx_start;
12700 #if __FreeBSD_version >= 901504
12701     ifp->if_transmit = bxe_tx_mq_start;
12702     ifp->if_qflush = bxe_mq_flush;
12703 #endif
12704 #ifdef FreeBSD8_0
12705     ifp->if_timer = 0;
12706 #endif
12707     ifp->if_init = bxe_init;
12708     ifp->if_mtu = sc->mtu;
12709     ifp->if_hwassist = (CSUM_IP       |
12710                         CSUM_TCP      |
12711                         CSUM_UDP      |
12712                         CSUM_TSO      |
12713                         CSUM_TCP_IPV6 |
12714                         CSUM_UDP_IPV6);
12715     ifp->if_capabilities =
12716 #if __FreeBSD_version < 700000
12717         (IFCAP_VLAN_MTU       |
12718          IFCAP_VLAN_HWTAGGING |
12719          IFCAP_HWCSUM         |
12720          IFCAP_JUMBO_MTU      |
12721          IFCAP_LRO);
12722 #else
12723         (IFCAP_VLAN_MTU       |
12724          IFCAP_VLAN_HWTAGGING |
12725          IFCAP_VLAN_HWTSO     |
12726          IFCAP_VLAN_HWFILTER  |
12727          IFCAP_VLAN_HWCSUM    |
12728          IFCAP_HWCSUM         |
12729          IFCAP_JUMBO_MTU      |
12730          IFCAP_LRO            |
12731          IFCAP_TSO4           |
12732          IFCAP_TSO6           |
12733          IFCAP_WOL_MAGIC);
12734 #endif
12735     ifp->if_capenable = ifp->if_capabilities;
12736     ifp->if_capenable &= ~IFCAP_WOL_MAGIC; /* XXX not yet... */
12737 #if __FreeBSD_version < 1000025
12738     ifp->if_baudrate = 1000000000;
12739 #else
12740     if_initbaudrate(ifp, IF_Gbps(10));
12741 #endif
12742     ifp->if_snd.ifq_drv_maxlen = sc->tx_ring_size;
12743
12744     IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen);
12745     IFQ_SET_READY(&ifp->if_snd);
12746
12747     sc->ifnet = ifp;
12748
12749     /* attach to the Ethernet interface list */
12750     ether_ifattach(ifp, sc->link_params.mac_addr);
12751
12752     return (0);
12753 }
12754
12755 static void
12756 bxe_deallocate_bars(struct bxe_softc *sc)
12757 {
12758     int i;
12759
12760     for (i = 0; i < MAX_BARS; i++) {
12761         if (sc->bar[i].resource != NULL) {
12762             bus_release_resource(sc->dev,
12763                                  SYS_RES_MEMORY,
12764                                  sc->bar[i].rid,
12765                                  sc->bar[i].resource);
12766             BLOGD(sc, DBG_LOAD, "Released PCI BAR%d [%02x] memory\n",
12767                   i, PCIR_BAR(i));
12768         }
12769     }
12770 }
12771
12772 static int
12773 bxe_allocate_bars(struct bxe_softc *sc)
12774 {
12775     u_int flags;
12776     int i;
12777
12778     memset(sc->bar, 0, sizeof(sc->bar));
12779
12780     for (i = 0; i < MAX_BARS; i++) {
12781
12782         /* memory resources reside at BARs 0, 2, 4 */
12783         /* Run `pciconf -lb` to see mappings */
12784         if ((i != 0) && (i != 2) && (i != 4)) {
12785             continue;
12786         }
12787
12788         sc->bar[i].rid = PCIR_BAR(i);
12789
12790         flags = RF_ACTIVE;
12791         if (i == 0) {
12792             flags |= RF_SHAREABLE;
12793         }
12794
12795         if ((sc->bar[i].resource =
12796              bus_alloc_resource_any(sc->dev,
12797                                     SYS_RES_MEMORY,
12798                                     &sc->bar[i].rid,
12799                                     flags)) == NULL) {
12800             return (0);
12801         }
12802
12803         sc->bar[i].tag    = rman_get_bustag(sc->bar[i].resource);
12804         sc->bar[i].handle = rman_get_bushandle(sc->bar[i].resource);
12805         sc->bar[i].kva    = (vm_offset_t)rman_get_virtual(sc->bar[i].resource);
12806
12807         BLOGI(sc, "PCI BAR%d [%02x] memory allocated: %p-%p (%ld) -> %p\n",
12808               i, PCIR_BAR(i),
12809               (void *)rman_get_start(sc->bar[i].resource),
12810               (void *)rman_get_end(sc->bar[i].resource),
12811               rman_get_size(sc->bar[i].resource),
12812               (void *)sc->bar[i].kva);
12813     }
12814
12815     return (0);
12816 }
12817
12818 static void
12819 bxe_get_function_num(struct bxe_softc *sc)
12820 {
12821     uint32_t val = 0;
12822
12823     /*
12824      * Read the ME register to get the function number. The ME register
12825      * holds the relative-function number and absolute-function number. The
12826      * absolute-function number appears only in E2 and above. Before that
12827      * these bits always contained zero, therefore we cannot blindly use them.
12828      */
12829
12830     val = REG_RD(sc, BAR_ME_REGISTER);
12831
12832     sc->pfunc_rel =
12833         (uint8_t)((val & ME_REG_PF_NUM) >> ME_REG_PF_NUM_SHIFT);
12834     sc->path_id =
12835         (uint8_t)((val & ME_REG_ABS_PF_NUM) >> ME_REG_ABS_PF_NUM_SHIFT) & 1;
12836
12837     if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
12838         sc->pfunc_abs = ((sc->pfunc_rel << 1) | sc->path_id);
12839     } else {
12840         sc->pfunc_abs = (sc->pfunc_rel | sc->path_id);
12841     }
12842
12843     BLOGD(sc, DBG_LOAD,
12844           "Relative function %d, Absolute function %d, Path %d\n",
12845           sc->pfunc_rel, sc->pfunc_abs, sc->path_id);
12846 }
12847
12848 static uint32_t
12849 bxe_get_shmem_mf_cfg_base(struct bxe_softc *sc)
12850 {
12851     uint32_t shmem2_size;
12852     uint32_t offset;
12853     uint32_t mf_cfg_offset_value;
12854
12855     /* Non 57712 */
12856     offset = (SHMEM_RD(sc, func_mb) +
12857               (MAX_FUNC_NUM * sizeof(struct drv_func_mb)));
12858
12859     /* 57712 plus */
12860     if (sc->devinfo.shmem2_base != 0) {
12861         shmem2_size = SHMEM2_RD(sc, size);
12862         if (shmem2_size > offsetof(struct shmem2_region, mf_cfg_addr)) {
12863             mf_cfg_offset_value = SHMEM2_RD(sc, mf_cfg_addr);
12864             if (SHMEM_MF_CFG_ADDR_NONE != mf_cfg_offset_value) {
12865                 offset = mf_cfg_offset_value;
12866             }
12867         }
12868     }
12869
12870     return (offset);
12871 }
12872
12873 static uint32_t
12874 bxe_pcie_capability_read(struct bxe_softc *sc,
12875                          int    reg,
12876                          int    width)
12877 {
12878     int pcie_reg;
12879
12880     /* ensure PCIe capability is enabled */
12881     if (pci_find_cap(sc->dev, PCIY_EXPRESS, &pcie_reg) == 0) {
12882         if (pcie_reg != 0) {
12883             BLOGD(sc, DBG_LOAD, "PCIe capability at 0x%04x\n", pcie_reg);
12884             return (pci_read_config(sc->dev, (pcie_reg + reg), width));
12885         }
12886     }
12887
12888     BLOGE(sc, "PCIe capability NOT FOUND!!!\n");
12889
12890     return (0);
12891 }
12892
12893 static uint8_t
12894 bxe_is_pcie_pending(struct bxe_softc *sc)
12895 {
12896     return (bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_STA, 2) &
12897             PCIM_EXP_STA_TRANSACTION_PND);
12898 }
12899
12900 /*
12901  * Walk the PCI capabiites list for the device to find what features are
12902  * supported. These capabilites may be enabled/disabled by firmware so it's
12903  * best to walk the list rather than make assumptions.
12904  */
12905 static void
12906 bxe_probe_pci_caps(struct bxe_softc *sc)
12907 {
12908     uint16_t link_status;
12909     int reg;
12910
12911     /* check if PCI Power Management is enabled */
12912     if (pci_find_cap(sc->dev, PCIY_PMG, &reg) == 0) {
12913         if (reg != 0) {
12914             BLOGD(sc, DBG_LOAD, "Found PM capability at 0x%04x\n", reg);
12915
12916             sc->devinfo.pcie_cap_flags |= BXE_PM_CAPABLE_FLAG;
12917             sc->devinfo.pcie_pm_cap_reg = (uint16_t)reg;
12918         }
12919     }
12920
12921     link_status = bxe_pcie_capability_read(sc, PCIR_EXPRESS_LINK_STA, 2);
12922
12923     /* handle PCIe 2.0 workarounds for 57710 */
12924     if (CHIP_IS_E1(sc)) {
12925         /* workaround for 57710 errata E4_57710_27462 */
12926         sc->devinfo.pcie_link_speed =
12927             (REG_RD(sc, 0x3d04) & (1 << 24)) ? 2 : 1;
12928
12929         /* workaround for 57710 errata E4_57710_27488 */
12930         sc->devinfo.pcie_link_width =
12931             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12932         if (sc->devinfo.pcie_link_speed > 1) {
12933             sc->devinfo.pcie_link_width =
12934                 ((link_status & PCIM_LINK_STA_WIDTH) >> 4) >> 1;
12935         }
12936     } else {
12937         sc->devinfo.pcie_link_speed =
12938             (link_status & PCIM_LINK_STA_SPEED);
12939         sc->devinfo.pcie_link_width =
12940             ((link_status & PCIM_LINK_STA_WIDTH) >> 4);
12941     }
12942
12943     BLOGD(sc, DBG_LOAD, "PCIe link speed=%d width=%d\n",
12944           sc->devinfo.pcie_link_speed, sc->devinfo.pcie_link_width);
12945
12946     sc->devinfo.pcie_cap_flags |= BXE_PCIE_CAPABLE_FLAG;
12947     sc->devinfo.pcie_pcie_cap_reg = (uint16_t)reg;
12948
12949     /* check if MSI capability is enabled */
12950     if (pci_find_cap(sc->dev, PCIY_MSI, &reg) == 0) {
12951         if (reg != 0) {
12952             BLOGD(sc, DBG_LOAD, "Found MSI capability at 0x%04x\n", reg);
12953
12954             sc->devinfo.pcie_cap_flags |= BXE_MSI_CAPABLE_FLAG;
12955             sc->devinfo.pcie_msi_cap_reg = (uint16_t)reg;
12956         }
12957     }
12958
12959     /* check if MSI-X capability is enabled */
12960     if (pci_find_cap(sc->dev, PCIY_MSIX, &reg) == 0) {
12961         if (reg != 0) {
12962             BLOGD(sc, DBG_LOAD, "Found MSI-X capability at 0x%04x\n", reg);
12963
12964             sc->devinfo.pcie_cap_flags |= BXE_MSIX_CAPABLE_FLAG;
12965             sc->devinfo.pcie_msix_cap_reg = (uint16_t)reg;
12966         }
12967     }
12968 }
12969
12970 static int
12971 bxe_get_shmem_mf_cfg_info_sd(struct bxe_softc *sc)
12972 {
12973     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
12974     uint32_t val;
12975
12976     /* get the outer vlan if we're in switch-dependent mode */
12977
12978     val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
12979     mf_info->ext_id = (uint16_t)val;
12980
12981     mf_info->multi_vnics_mode = 1;
12982
12983     if (!VALID_OVLAN(mf_info->ext_id)) {
12984         BLOGE(sc, "Invalid VLAN (%d)\n", mf_info->ext_id);
12985         return (1);
12986     }
12987
12988     /* get the capabilities */
12989     if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12990         FUNC_MF_CFG_PROTOCOL_ISCSI) {
12991         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ISCSI;
12992     } else if ((mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_PROTOCOL_MASK) ==
12993                FUNC_MF_CFG_PROTOCOL_FCOE) {
12994         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_FCOE;
12995     } else {
12996         mf_info->mf_protos_supported |= MF_PROTO_SUPPORT_ETHERNET;
12997     }
12998
12999     mf_info->vnics_per_port =
13000         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13001
13002     return (0);
13003 }
13004
13005 static uint32_t
13006 bxe_get_shmem_ext_proto_support_flags(struct bxe_softc *sc)
13007 {
13008     uint32_t retval = 0;
13009     uint32_t val;
13010
13011     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13012
13013     if (val & MACP_FUNC_CFG_FLAGS_ENABLED) {
13014         if (val & MACP_FUNC_CFG_FLAGS_ETHERNET) {
13015             retval |= MF_PROTO_SUPPORT_ETHERNET;
13016         }
13017         if (val & MACP_FUNC_CFG_FLAGS_ISCSI_OFFLOAD) {
13018             retval |= MF_PROTO_SUPPORT_ISCSI;
13019         }
13020         if (val & MACP_FUNC_CFG_FLAGS_FCOE_OFFLOAD) {
13021             retval |= MF_PROTO_SUPPORT_FCOE;
13022         }
13023     }
13024
13025     return (retval);
13026 }
13027
13028 static int
13029 bxe_get_shmem_mf_cfg_info_si(struct bxe_softc *sc)
13030 {
13031     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13032     uint32_t val;
13033
13034     /*
13035      * There is no outer vlan if we're in switch-independent mode.
13036      * If the mac is valid then assume multi-function.
13037      */
13038
13039     val = MFCFG_RD(sc, func_ext_config[SC_ABS_FUNC(sc)].func_cfg);
13040
13041     mf_info->multi_vnics_mode = ((val & MACP_FUNC_CFG_FLAGS_MASK) != 0);
13042
13043     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13044
13045     mf_info->vnics_per_port =
13046         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13047
13048     return (0);
13049 }
13050
13051 static int
13052 bxe_get_shmem_mf_cfg_info_niv(struct bxe_softc *sc)
13053 {
13054     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13055     uint32_t e1hov_tag;
13056     uint32_t func_config;
13057     uint32_t niv_config;
13058
13059     mf_info->multi_vnics_mode = 1;
13060
13061     e1hov_tag   = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13062     func_config = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13063     niv_config  = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].afex_config);
13064
13065     mf_info->ext_id =
13066         (uint16_t)((e1hov_tag & FUNC_MF_CFG_E1HOV_TAG_MASK) >>
13067                    FUNC_MF_CFG_E1HOV_TAG_SHIFT);
13068
13069     mf_info->default_vlan =
13070         (uint16_t)((e1hov_tag & FUNC_MF_CFG_AFEX_VLAN_MASK) >>
13071                    FUNC_MF_CFG_AFEX_VLAN_SHIFT);
13072
13073     mf_info->niv_allowed_priorities =
13074         (uint8_t)((niv_config & FUNC_MF_CFG_AFEX_COS_FILTER_MASK) >>
13075                   FUNC_MF_CFG_AFEX_COS_FILTER_SHIFT);
13076
13077     mf_info->niv_default_cos =
13078         (uint8_t)((func_config & FUNC_MF_CFG_TRANSMIT_PRIORITY_MASK) >>
13079                   FUNC_MF_CFG_TRANSMIT_PRIORITY_SHIFT);
13080
13081     mf_info->afex_vlan_mode =
13082         ((niv_config & FUNC_MF_CFG_AFEX_VLAN_MODE_MASK) >>
13083          FUNC_MF_CFG_AFEX_VLAN_MODE_SHIFT);
13084
13085     mf_info->niv_mba_enabled =
13086         ((niv_config & FUNC_MF_CFG_AFEX_MBA_ENABLED_MASK) >>
13087          FUNC_MF_CFG_AFEX_MBA_ENABLED_SHIFT);
13088
13089     mf_info->mf_protos_supported = bxe_get_shmem_ext_proto_support_flags(sc);
13090
13091     mf_info->vnics_per_port =
13092         (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) ? 2 : 4;
13093
13094     return (0);
13095 }
13096
13097 static int
13098 bxe_check_valid_mf_cfg(struct bxe_softc *sc)
13099 {
13100     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13101     uint32_t mf_cfg1;
13102     uint32_t mf_cfg2;
13103     uint32_t ovlan1;
13104     uint32_t ovlan2;
13105     uint8_t i, j;
13106
13107     BLOGD(sc, DBG_LOAD, "MF config parameters for function %d\n",
13108           SC_PORT(sc));
13109     BLOGD(sc, DBG_LOAD, "\tmf_config=0x%x\n",
13110           mf_info->mf_config[SC_VN(sc)]);
13111     BLOGD(sc, DBG_LOAD, "\tmulti_vnics_mode=%d\n",
13112           mf_info->multi_vnics_mode);
13113     BLOGD(sc, DBG_LOAD, "\tvnics_per_port=%d\n",
13114           mf_info->vnics_per_port);
13115     BLOGD(sc, DBG_LOAD, "\tovlan/vifid=%d\n",
13116           mf_info->ext_id);
13117     BLOGD(sc, DBG_LOAD, "\tmin_bw=%d/%d/%d/%d\n",
13118           mf_info->min_bw[0], mf_info->min_bw[1],
13119           mf_info->min_bw[2], mf_info->min_bw[3]);
13120     BLOGD(sc, DBG_LOAD, "\tmax_bw=%d/%d/%d/%d\n",
13121           mf_info->max_bw[0], mf_info->max_bw[1],
13122           mf_info->max_bw[2], mf_info->max_bw[3]);
13123     BLOGD(sc, DBG_LOAD, "\tmac_addr: %s\n",
13124           sc->mac_addr_str);
13125
13126     /* various MF mode sanity checks... */
13127
13128     if (mf_info->mf_config[SC_VN(sc)] & FUNC_MF_CFG_FUNC_HIDE) {
13129         BLOGE(sc, "Enumerated function %d is marked as hidden\n",
13130               SC_PORT(sc));
13131         return (1);
13132     }
13133
13134     if ((mf_info->vnics_per_port > 1) && !mf_info->multi_vnics_mode) {
13135         BLOGE(sc, "vnics_per_port=%d multi_vnics_mode=%d\n",
13136               mf_info->vnics_per_port, mf_info->multi_vnics_mode);
13137         return (1);
13138     }
13139
13140     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13141         /* vnic id > 0 must have valid ovlan in switch-dependent mode */
13142         if ((SC_VN(sc) > 0) && !VALID_OVLAN(OVLAN(sc))) {
13143             BLOGE(sc, "mf_mode=SD vnic_id=%d ovlan=%d\n",
13144                   SC_VN(sc), OVLAN(sc));
13145             return (1);
13146         }
13147
13148         if (!VALID_OVLAN(OVLAN(sc)) && mf_info->multi_vnics_mode) {
13149             BLOGE(sc, "mf_mode=SD multi_vnics_mode=%d ovlan=%d\n",
13150                   mf_info->multi_vnics_mode, OVLAN(sc));
13151             return (1);
13152         }
13153
13154         /*
13155          * Verify all functions are either MF or SF mode. If MF, make sure
13156          * sure that all non-hidden functions have a valid ovlan. If SF,
13157          * make sure that all non-hidden functions have an invalid ovlan.
13158          */
13159         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13160             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13161             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13162             if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13163                 (((mf_info->multi_vnics_mode) && !VALID_OVLAN(ovlan1)) ||
13164                  ((!mf_info->multi_vnics_mode) && VALID_OVLAN(ovlan1)))) {
13165                 BLOGE(sc, "mf_mode=SD function %d MF config "
13166                           "mismatch, multi_vnics_mode=%d ovlan=%d\n",
13167                       i, mf_info->multi_vnics_mode, ovlan1);
13168                 return (1);
13169             }
13170         }
13171
13172         /* Verify all funcs on the same port each have a different ovlan. */
13173         FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13174             mf_cfg1 = MFCFG_RD(sc, func_mf_config[i].config);
13175             ovlan1  = MFCFG_RD(sc, func_mf_config[i].e1hov_tag);
13176             /* iterate from the next function on the port to the max func */
13177             for (j = i + 2; j < MAX_FUNC_NUM; j += 2) {
13178                 mf_cfg2 = MFCFG_RD(sc, func_mf_config[j].config);
13179                 ovlan2  = MFCFG_RD(sc, func_mf_config[j].e1hov_tag);
13180                 if (!(mf_cfg1 & FUNC_MF_CFG_FUNC_HIDE) &&
13181                     VALID_OVLAN(ovlan1) &&
13182                     !(mf_cfg2 & FUNC_MF_CFG_FUNC_HIDE) &&
13183                     VALID_OVLAN(ovlan2) &&
13184                     (ovlan1 == ovlan2)) {
13185                     BLOGE(sc, "mf_mode=SD functions %d and %d "
13186                               "have the same ovlan (%d)\n",
13187                           i, j, ovlan1);
13188                     return (1);
13189                 }
13190             }
13191         }
13192     } /* MULTI_FUNCTION_SD */
13193
13194     return (0);
13195 }
13196
13197 static int
13198 bxe_get_mf_cfg_info(struct bxe_softc *sc)
13199 {
13200     struct bxe_mf_info *mf_info = &sc->devinfo.mf_info;
13201     uint32_t val, mac_upper;
13202     uint8_t i, vnic;
13203
13204     /* initialize mf_info defaults */
13205     mf_info->vnics_per_port   = 1;
13206     mf_info->multi_vnics_mode = FALSE;
13207     mf_info->path_has_ovlan   = FALSE;
13208     mf_info->mf_mode          = SINGLE_FUNCTION;
13209
13210     if (!CHIP_IS_MF_CAP(sc)) {
13211         return (0);
13212     }
13213
13214     if (sc->devinfo.mf_cfg_base == SHMEM_MF_CFG_ADDR_NONE) {
13215         BLOGE(sc, "Invalid mf_cfg_base!\n");
13216         return (1);
13217     }
13218
13219     /* get the MF mode (switch dependent / independent / single-function) */
13220
13221     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13222
13223     switch (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK)
13224     {
13225     case SHARED_FEAT_CFG_FORCE_SF_MODE_SWITCH_INDEPT:
13226
13227         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13228
13229         /* check for legal upper mac bytes */
13230         if (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT) {
13231             mf_info->mf_mode = MULTI_FUNCTION_SI;
13232         } else {
13233             BLOGE(sc, "Invalid config for Switch Independent mode\n");
13234         }
13235
13236         break;
13237
13238     case SHARED_FEAT_CFG_FORCE_SF_MODE_MF_ALLOWED:
13239     case SHARED_FEAT_CFG_FORCE_SF_MODE_SPIO4:
13240
13241         /* get outer vlan configuration */
13242         val = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].e1hov_tag);
13243
13244         if ((val & FUNC_MF_CFG_E1HOV_TAG_MASK) !=
13245             FUNC_MF_CFG_E1HOV_TAG_DEFAULT) {
13246             mf_info->mf_mode = MULTI_FUNCTION_SD;
13247         } else {
13248             BLOGE(sc, "Invalid config for Switch Dependent mode\n");
13249         }
13250
13251         break;
13252
13253     case SHARED_FEAT_CFG_FORCE_SF_MODE_FORCED_SF:
13254
13255         /* not in MF mode, vnics_per_port=1 and multi_vnics_mode=FALSE */
13256         return (0);
13257
13258     case SHARED_FEAT_CFG_FORCE_SF_MODE_AFEX_MODE:
13259
13260         /*
13261          * Mark MF mode as NIV if MCP version includes NPAR-SD support
13262          * and the MAC address is valid.
13263          */
13264         mac_upper = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13265
13266         if ((SHMEM2_HAS(sc, afex_driver_support)) &&
13267             (mac_upper != FUNC_MF_CFG_UPPERMAC_DEFAULT)) {
13268             mf_info->mf_mode = MULTI_FUNCTION_AFEX;
13269         } else {
13270             BLOGE(sc, "Invalid config for AFEX mode\n");
13271         }
13272
13273         break;
13274
13275     default:
13276
13277         BLOGE(sc, "Unknown MF mode (0x%08x)\n",
13278               (val & SHARED_FEAT_CFG_FORCE_SF_MODE_MASK));
13279
13280         return (1);
13281     }
13282
13283     /* set path mf_mode (which could be different than function mf_mode) */
13284     if (mf_info->mf_mode == MULTI_FUNCTION_SD) {
13285         mf_info->path_has_ovlan = TRUE;
13286     } else if (mf_info->mf_mode == SINGLE_FUNCTION) {
13287         /*
13288          * Decide on path multi vnics mode. If we're not in MF mode and in
13289          * 4-port mode, this is good enough to check vnic-0 of the other port
13290          * on the same path
13291          */
13292         if (CHIP_PORT_MODE(sc) == CHIP_4_PORT_MODE) {
13293             uint8_t other_port = !(PORT_ID(sc) & 1);
13294             uint8_t abs_func_other_port = (SC_PATH(sc) + (2 * other_port));
13295
13296             val = MFCFG_RD(sc, func_mf_config[abs_func_other_port].e1hov_tag);
13297
13298             mf_info->path_has_ovlan = VALID_OVLAN((uint16_t)val) ? 1 : 0;
13299         }
13300     }
13301
13302     if (mf_info->mf_mode == SINGLE_FUNCTION) {
13303         /* invalid MF config */
13304         if (SC_VN(sc) >= 1) {
13305             BLOGE(sc, "VNIC ID >= 1 in SF mode\n");
13306             return (1);
13307         }
13308
13309         return (0);
13310     }
13311
13312     /* get the MF configuration */
13313     mf_info->mf_config[SC_VN(sc)] =
13314         MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].config);
13315
13316     switch(mf_info->mf_mode)
13317     {
13318     case MULTI_FUNCTION_SD:
13319
13320         bxe_get_shmem_mf_cfg_info_sd(sc);
13321         break;
13322
13323     case MULTI_FUNCTION_SI:
13324
13325         bxe_get_shmem_mf_cfg_info_si(sc);
13326         break;
13327
13328     case MULTI_FUNCTION_AFEX:
13329
13330         bxe_get_shmem_mf_cfg_info_niv(sc);
13331         break;
13332
13333     default:
13334
13335         BLOGE(sc, "Get MF config failed (mf_mode=0x%08x)\n",
13336               mf_info->mf_mode);
13337         return (1);
13338     }
13339
13340     /* get the congestion management parameters */
13341
13342     vnic = 0;
13343     FOREACH_ABS_FUNC_IN_PORT(sc, i) {
13344         /* get min/max bw */
13345         val = MFCFG_RD(sc, func_mf_config[i].config);
13346         mf_info->min_bw[vnic] =
13347             ((val & FUNC_MF_CFG_MIN_BW_MASK) >> FUNC_MF_CFG_MIN_BW_SHIFT);
13348         mf_info->max_bw[vnic] =
13349             ((val & FUNC_MF_CFG_MAX_BW_MASK) >> FUNC_MF_CFG_MAX_BW_SHIFT);
13350         vnic++;
13351     }
13352
13353     return (bxe_check_valid_mf_cfg(sc));
13354 }
13355
13356 static int
13357 bxe_get_shmem_info(struct bxe_softc *sc)
13358 {
13359     int port;
13360     uint32_t mac_hi, mac_lo, val;
13361
13362     port = SC_PORT(sc);
13363     mac_hi = mac_lo = 0;
13364
13365     sc->link_params.sc   = sc;
13366     sc->link_params.port = port;
13367
13368     /* get the hardware config info */
13369     sc->devinfo.hw_config =
13370         SHMEM_RD(sc, dev_info.shared_hw_config.config);
13371     sc->devinfo.hw_config2 =
13372         SHMEM_RD(sc, dev_info.shared_hw_config.config2);
13373
13374     sc->link_params.hw_led_mode =
13375         ((sc->devinfo.hw_config & SHARED_HW_CFG_LED_MODE_MASK) >>
13376          SHARED_HW_CFG_LED_MODE_SHIFT);
13377
13378     /* get the port feature config */
13379     sc->port.config =
13380         SHMEM_RD(sc, dev_info.port_feature_config[port].config),
13381
13382     /* get the link params */
13383     sc->link_params.speed_cap_mask[0] =
13384         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask);
13385     sc->link_params.speed_cap_mask[1] =
13386         SHMEM_RD(sc, dev_info.port_hw_config[port].speed_capability_mask2);
13387
13388     /* get the lane config */
13389     sc->link_params.lane_config =
13390         SHMEM_RD(sc, dev_info.port_hw_config[port].lane_config);
13391
13392     /* get the link config */
13393     val = SHMEM_RD(sc, dev_info.port_feature_config[port].link_config);
13394     sc->port.link_config[ELINK_INT_PHY] = val;
13395     sc->link_params.switch_cfg = (val & PORT_FEATURE_CONNECTED_SWITCH_MASK);
13396     sc->port.link_config[ELINK_EXT_PHY1] =
13397         SHMEM_RD(sc, dev_info.port_feature_config[port].link_config2);
13398
13399     /* get the override preemphasis flag and enable it or turn it off */
13400     val = SHMEM_RD(sc, dev_info.shared_feature_config.config);
13401     if (val & SHARED_FEAT_CFG_OVERRIDE_PREEMPHASIS_CFG_ENABLED) {
13402         sc->link_params.feature_config_flags |=
13403             ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13404     } else {
13405         sc->link_params.feature_config_flags &=
13406             ~ELINK_FEATURE_CONFIG_OVERRIDE_PREEMPHASIS_ENABLED;
13407     }
13408
13409     /* get the initial value of the link params */
13410     sc->link_params.multi_phy_config =
13411         SHMEM_RD(sc, dev_info.port_hw_config[port].multi_phy_config);
13412
13413     /* get external phy info */
13414     sc->port.ext_phy_config =
13415         SHMEM_RD(sc, dev_info.port_hw_config[port].external_phy_config);
13416
13417     /* get the multifunction configuration */
13418     bxe_get_mf_cfg_info(sc);
13419
13420     /* get the mac address */
13421     if (IS_MF(sc)) {
13422         mac_hi = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_upper);
13423         mac_lo = MFCFG_RD(sc, func_mf_config[SC_ABS_FUNC(sc)].mac_lower);
13424     } else {
13425         mac_hi = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_upper);
13426         mac_lo = SHMEM_RD(sc, dev_info.port_hw_config[port].mac_lower);
13427     }
13428
13429     if ((mac_lo == 0) && (mac_hi == 0)) {
13430         *sc->mac_addr_str = 0;
13431         BLOGE(sc, "No Ethernet address programmed!\n");
13432     } else {
13433         sc->link_params.mac_addr[0] = (uint8_t)(mac_hi >> 8);
13434         sc->link_params.mac_addr[1] = (uint8_t)(mac_hi);
13435         sc->link_params.mac_addr[2] = (uint8_t)(mac_lo >> 24);
13436         sc->link_params.mac_addr[3] = (uint8_t)(mac_lo >> 16);
13437         sc->link_params.mac_addr[4] = (uint8_t)(mac_lo >> 8);
13438         sc->link_params.mac_addr[5] = (uint8_t)(mac_lo);
13439         snprintf(sc->mac_addr_str, sizeof(sc->mac_addr_str),
13440                  "%02x:%02x:%02x:%02x:%02x:%02x",
13441                  sc->link_params.mac_addr[0], sc->link_params.mac_addr[1],
13442                  sc->link_params.mac_addr[2], sc->link_params.mac_addr[3],
13443                  sc->link_params.mac_addr[4], sc->link_params.mac_addr[5]);
13444         BLOGD(sc, DBG_LOAD, "Ethernet address: %s\n", sc->mac_addr_str);
13445     }
13446
13447     return (0);
13448 }
13449
13450 static void
13451 bxe_get_tunable_params(struct bxe_softc *sc)
13452 {
13453     /* sanity checks */
13454
13455     if ((bxe_interrupt_mode != INTR_MODE_INTX) &&
13456         (bxe_interrupt_mode != INTR_MODE_MSI)  &&
13457         (bxe_interrupt_mode != INTR_MODE_MSIX)) {
13458         BLOGW(sc, "invalid interrupt_mode value (%d)\n", bxe_interrupt_mode);
13459         bxe_interrupt_mode = INTR_MODE_MSIX;
13460     }
13461
13462     if ((bxe_queue_count < 0) || (bxe_queue_count > MAX_RSS_CHAINS)) {
13463         BLOGW(sc, "invalid queue_count value (%d)\n", bxe_queue_count);
13464         bxe_queue_count = 0;
13465     }
13466
13467     if ((bxe_max_rx_bufs < 1) || (bxe_max_rx_bufs > RX_BD_USABLE)) {
13468         if (bxe_max_rx_bufs == 0) {
13469             bxe_max_rx_bufs = RX_BD_USABLE;
13470         } else {
13471             BLOGW(sc, "invalid max_rx_bufs (%d)\n", bxe_max_rx_bufs);
13472             bxe_max_rx_bufs = 2048;
13473         }
13474     }
13475
13476     if ((bxe_hc_rx_ticks < 1) || (bxe_hc_rx_ticks > 100)) {
13477         BLOGW(sc, "invalid hc_rx_ticks (%d)\n", bxe_hc_rx_ticks);
13478         bxe_hc_rx_ticks = 25;
13479     }
13480
13481     if ((bxe_hc_tx_ticks < 1) || (bxe_hc_tx_ticks > 100)) {
13482         BLOGW(sc, "invalid hc_tx_ticks (%d)\n", bxe_hc_tx_ticks);
13483         bxe_hc_tx_ticks = 50;
13484     }
13485
13486     if (bxe_max_aggregation_size == 0) {
13487         bxe_max_aggregation_size = TPA_AGG_SIZE;
13488     }
13489
13490     if (bxe_max_aggregation_size > 0xffff) {
13491         BLOGW(sc, "invalid max_aggregation_size (%d)\n",
13492               bxe_max_aggregation_size);
13493         bxe_max_aggregation_size = TPA_AGG_SIZE;
13494     }
13495
13496     if ((bxe_mrrs < -1) || (bxe_mrrs > 3)) {
13497         BLOGW(sc, "invalid mrrs (%d)\n", bxe_mrrs);
13498         bxe_mrrs = -1;
13499     }
13500
13501     if ((bxe_autogreeen < 0) || (bxe_autogreeen > 2)) {
13502         BLOGW(sc, "invalid autogreeen (%d)\n", bxe_autogreeen);
13503         bxe_autogreeen = 0;
13504     }
13505
13506     if ((bxe_udp_rss < 0) || (bxe_udp_rss > 1)) {
13507         BLOGW(sc, "invalid udp_rss (%d)\n", bxe_udp_rss);
13508         bxe_udp_rss = 0;
13509     }
13510
13511     /* pull in user settings */
13512
13513     sc->interrupt_mode       = bxe_interrupt_mode;
13514     sc->max_rx_bufs          = bxe_max_rx_bufs;
13515     sc->hc_rx_ticks          = bxe_hc_rx_ticks;
13516     sc->hc_tx_ticks          = bxe_hc_tx_ticks;
13517     sc->max_aggregation_size = bxe_max_aggregation_size;
13518     sc->mrrs                 = bxe_mrrs;
13519     sc->autogreeen           = bxe_autogreeen;
13520     sc->udp_rss              = bxe_udp_rss;
13521
13522     if (bxe_interrupt_mode == INTR_MODE_INTX) {
13523         sc->num_queues = 1;
13524     } else { /* INTR_MODE_MSI or INTR_MODE_MSIX */
13525         sc->num_queues =
13526             min((bxe_queue_count ? bxe_queue_count : mp_ncpus),
13527                 MAX_RSS_CHAINS);
13528         if (sc->num_queues > mp_ncpus) {
13529             sc->num_queues = mp_ncpus;
13530         }
13531     }
13532
13533     BLOGD(sc, DBG_LOAD,
13534           "User Config: "
13535           "debug=0x%lx "
13536           "interrupt_mode=%d "
13537           "queue_count=%d "
13538           "hc_rx_ticks=%d "
13539           "hc_tx_ticks=%d "
13540           "rx_budget=%d "
13541           "max_aggregation_size=%d "
13542           "mrrs=%d "
13543           "autogreeen=%d "
13544           "udp_rss=%d\n",
13545           bxe_debug,
13546           sc->interrupt_mode,
13547           sc->num_queues,
13548           sc->hc_rx_ticks,
13549           sc->hc_tx_ticks,
13550           bxe_rx_budget,
13551           sc->max_aggregation_size,
13552           sc->mrrs,
13553           sc->autogreeen,
13554           sc->udp_rss);
13555 }
13556
13557 static int
13558 bxe_media_detect(struct bxe_softc *sc)
13559 {
13560     int port_type;
13561     uint32_t phy_idx = bxe_get_cur_phy_idx(sc);
13562
13563     switch (sc->link_params.phy[phy_idx].media_type) {
13564     case ELINK_ETH_PHY_SFPP_10G_FIBER:
13565     case ELINK_ETH_PHY_XFP_FIBER:
13566         BLOGI(sc, "Found 10Gb Fiber media.\n");
13567         sc->media = IFM_10G_SR;
13568         port_type = PORT_FIBRE;
13569         break;
13570     case ELINK_ETH_PHY_SFP_1G_FIBER:
13571         BLOGI(sc, "Found 1Gb Fiber media.\n");
13572         sc->media = IFM_1000_SX;
13573         port_type = PORT_FIBRE;
13574         break;
13575     case ELINK_ETH_PHY_KR:
13576     case ELINK_ETH_PHY_CX4:
13577         BLOGI(sc, "Found 10GBase-CX4 media.\n");
13578         sc->media = IFM_10G_CX4;
13579         port_type = PORT_FIBRE;
13580         break;
13581     case ELINK_ETH_PHY_DA_TWINAX:
13582         BLOGI(sc, "Found 10Gb Twinax media.\n");
13583         sc->media = IFM_10G_TWINAX;
13584         port_type = PORT_DA;
13585         break;
13586     case ELINK_ETH_PHY_BASE_T:
13587         if (sc->link_params.speed_cap_mask[0] &
13588             PORT_HW_CFG_SPEED_CAPABILITY_D0_10G) {
13589             BLOGI(sc, "Found 10GBase-T media.\n");
13590             sc->media = IFM_10G_T;
13591             port_type = PORT_TP;
13592         } else {
13593             BLOGI(sc, "Found 1000Base-T media.\n");
13594             sc->media = IFM_1000_T;
13595             port_type = PORT_TP;
13596         }
13597         break;
13598     case ELINK_ETH_PHY_NOT_PRESENT:
13599         BLOGI(sc, "Media not present.\n");
13600         sc->media = 0;
13601         port_type = PORT_OTHER;
13602         break;
13603     case ELINK_ETH_PHY_UNSPECIFIED:
13604     default:
13605         BLOGI(sc, "Unknown media!\n");
13606         sc->media = 0;
13607         port_type = PORT_OTHER;
13608         break;
13609     }
13610     return port_type;
13611 }
13612
13613 #define GET_FIELD(value, fname)                     \
13614     (((value) & (fname##_MASK)) >> (fname##_SHIFT))
13615 #define IGU_FID(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_FID)
13616 #define IGU_VEC(val) GET_FIELD((val), IGU_REG_MAPPING_MEMORY_VECTOR)
13617
13618 static int
13619 bxe_get_igu_cam_info(struct bxe_softc *sc)
13620 {
13621     int pfid = SC_FUNC(sc);
13622     int igu_sb_id;
13623     uint32_t val;
13624     uint8_t fid, igu_sb_cnt = 0;
13625
13626     sc->igu_base_sb = 0xff;
13627
13628     if (CHIP_INT_MODE_IS_BC(sc)) {
13629         int vn = SC_VN(sc);
13630         igu_sb_cnt = sc->igu_sb_cnt;
13631         sc->igu_base_sb = ((CHIP_IS_MODE_4_PORT(sc) ? pfid : vn) *
13632                            FP_SB_MAX_E1x);
13633         sc->igu_dsb_id = (E1HVN_MAX * FP_SB_MAX_E1x +
13634                           (CHIP_IS_MODE_4_PORT(sc) ? pfid : vn));
13635         return (0);
13636     }
13637
13638     /* IGU in normal mode - read CAM */
13639     for (igu_sb_id = 0;
13640          igu_sb_id < IGU_REG_MAPPING_MEMORY_SIZE;
13641          igu_sb_id++) {
13642         val = REG_RD(sc, IGU_REG_MAPPING_MEMORY + igu_sb_id * 4);
13643         if (!(val & IGU_REG_MAPPING_MEMORY_VALID)) {
13644             continue;
13645         }
13646         fid = IGU_FID(val);
13647         if ((fid & IGU_FID_ENCODE_IS_PF)) {
13648             if ((fid & IGU_FID_PF_NUM_MASK) != pfid) {
13649                 continue;
13650             }
13651             if (IGU_VEC(val) == 0) {
13652                 /* default status block */
13653                 sc->igu_dsb_id = igu_sb_id;
13654             } else {
13655                 if (sc->igu_base_sb == 0xff) {
13656                     sc->igu_base_sb = igu_sb_id;
13657                 }
13658                 igu_sb_cnt++;
13659             }
13660         }
13661     }
13662
13663     /*
13664      * Due to new PF resource allocation by MFW T7.4 and above, it's optional
13665      * that number of CAM entries will not be equal to the value advertised in
13666      * PCI. Driver should use the minimal value of both as the actual status
13667      * block count
13668      */
13669     sc->igu_sb_cnt = min(sc->igu_sb_cnt, igu_sb_cnt);
13670
13671     if (igu_sb_cnt == 0) {
13672         BLOGE(sc, "CAM configuration error\n");
13673         return (-1);
13674     }
13675
13676     return (0);
13677 }
13678
13679 /*
13680  * Gather various information from the device config space, the device itself,
13681  * shmem, and the user input.
13682  */
13683 static int
13684 bxe_get_device_info(struct bxe_softc *sc)
13685 {
13686     uint32_t val;
13687     int rc;
13688
13689     /* Get the data for the device */
13690     sc->devinfo.vendor_id    = pci_get_vendor(sc->dev);
13691     sc->devinfo.device_id    = pci_get_device(sc->dev);
13692     sc->devinfo.subvendor_id = pci_get_subvendor(sc->dev);
13693     sc->devinfo.subdevice_id = pci_get_subdevice(sc->dev);
13694
13695     /* get the chip revision (chip metal comes from pci config space) */
13696     sc->devinfo.chip_id     =
13697     sc->link_params.chip_id =
13698         (((REG_RD(sc, MISC_REG_CHIP_NUM)                   & 0xffff) << 16) |
13699          ((REG_RD(sc, MISC_REG_CHIP_REV)                   & 0xf)    << 12) |
13700          (((REG_RD(sc, PCICFG_OFFSET + PCI_ID_VAL3) >> 24) & 0xf)    << 4)  |
13701          ((REG_RD(sc, MISC_REG_BOND_ID)                    & 0xf)    << 0));
13702
13703     /* force 57811 according to MISC register */
13704     if (REG_RD(sc, MISC_REG_CHIP_TYPE) & MISC_REG_CHIP_TYPE_57811_MASK) {
13705         if (CHIP_IS_57810(sc)) {
13706             sc->devinfo.chip_id = ((CHIP_NUM_57811 << 16) |
13707                                    (sc->devinfo.chip_id & 0x0000ffff));
13708         } else if (CHIP_IS_57810_MF(sc)) {
13709             sc->devinfo.chip_id = ((CHIP_NUM_57811_MF << 16) |
13710                                    (sc->devinfo.chip_id & 0x0000ffff));
13711         }
13712         sc->devinfo.chip_id |= 0x1;
13713     }
13714
13715     BLOGD(sc, DBG_LOAD,
13716           "chip_id=0x%08x (num=0x%04x rev=0x%01x metal=0x%02x bond=0x%01x)\n",
13717           sc->devinfo.chip_id,
13718           ((sc->devinfo.chip_id >> 16) & 0xffff),
13719           ((sc->devinfo.chip_id >> 12) & 0xf),
13720           ((sc->devinfo.chip_id >>  4) & 0xff),
13721           ((sc->devinfo.chip_id >>  0) & 0xf));
13722
13723     val = (REG_RD(sc, 0x2874) & 0x55);
13724     if ((sc->devinfo.chip_id & 0x1) ||
13725         (CHIP_IS_E1(sc) && val) ||
13726         (CHIP_IS_E1H(sc) && (val == 0x55))) {
13727         sc->flags |= BXE_ONE_PORT_FLAG;
13728         BLOGD(sc, DBG_LOAD, "single port device\n");
13729     }
13730
13731     /* set the doorbell size */
13732     sc->doorbell_size = (1 << BXE_DB_SHIFT);
13733
13734     /* determine whether the device is in 2 port or 4 port mode */
13735     sc->devinfo.chip_port_mode = CHIP_PORT_MODE_NONE; /* E1 & E1h*/
13736     if (CHIP_IS_E2E3(sc)) {
13737         /*
13738          * Read port4mode_en_ovwr[0]:
13739          *   If 1, four port mode is in port4mode_en_ovwr[1].
13740          *   If 0, four port mode is in port4mode_en[0].
13741          */
13742         val = REG_RD(sc, MISC_REG_PORT4MODE_EN_OVWR);
13743         if (val & 1) {
13744             val = ((val >> 1) & 1);
13745         } else {
13746             val = REG_RD(sc, MISC_REG_PORT4MODE_EN);
13747         }
13748
13749         sc->devinfo.chip_port_mode =
13750             (val) ? CHIP_4_PORT_MODE : CHIP_2_PORT_MODE;
13751
13752         BLOGD(sc, DBG_LOAD, "Port mode = %s\n", (val) ? "4" : "2");
13753     }
13754
13755     /* get the function and path info for the device */
13756     bxe_get_function_num(sc);
13757
13758     /* get the shared memory base address */
13759     sc->devinfo.shmem_base     =
13760     sc->link_params.shmem_base =
13761         REG_RD(sc, MISC_REG_SHARED_MEM_ADDR);
13762     sc->devinfo.shmem2_base =
13763         REG_RD(sc, (SC_PATH(sc) ? MISC_REG_GENERIC_CR_1 :
13764                                   MISC_REG_GENERIC_CR_0));
13765
13766     BLOGD(sc, DBG_LOAD, "shmem_base=0x%08x, shmem2_base=0x%08x\n",
13767           sc->devinfo.shmem_base, sc->devinfo.shmem2_base);
13768
13769     if (!sc->devinfo.shmem_base) {
13770         /* this should ONLY prevent upcoming shmem reads */
13771         BLOGI(sc, "MCP not active\n");
13772         sc->flags |= BXE_NO_MCP_FLAG;
13773         return (0);
13774     }
13775
13776     /* make sure the shared memory contents are valid */
13777     val = SHMEM_RD(sc, validity_map[SC_PORT(sc)]);
13778     if ((val & (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) !=
13779         (SHR_MEM_VALIDITY_DEV_INFO | SHR_MEM_VALIDITY_MB)) {
13780         BLOGE(sc, "Invalid SHMEM validity signature: 0x%08x\n", val);
13781         return (0);
13782     }
13783     BLOGD(sc, DBG_LOAD, "Valid SHMEM validity signature: 0x%08x\n", val);
13784
13785     /* get the bootcode version */
13786     sc->devinfo.bc_ver = SHMEM_RD(sc, dev_info.bc_rev);
13787     snprintf(sc->devinfo.bc_ver_str,
13788              sizeof(sc->devinfo.bc_ver_str),
13789              "%d.%d.%d",
13790              ((sc->devinfo.bc_ver >> 24) & 0xff),
13791              ((sc->devinfo.bc_ver >> 16) & 0xff),
13792              ((sc->devinfo.bc_ver >>  8) & 0xff));
13793     BLOGD(sc, DBG_LOAD, "Bootcode version: %s\n", sc->devinfo.bc_ver_str);
13794
13795     /* get the bootcode shmem address */
13796     sc->devinfo.mf_cfg_base = bxe_get_shmem_mf_cfg_base(sc);
13797     BLOGD(sc, DBG_LOAD, "mf_cfg_base=0x08%x \n", sc->devinfo.mf_cfg_base);
13798
13799     /* clean indirect addresses as they're not used */
13800     pci_write_config(sc->dev, PCICFG_GRC_ADDRESS, 0, 4);
13801     if (IS_PF(sc)) {
13802         REG_WR(sc, PXP2_REG_PGL_ADDR_88_F0, 0);
13803         REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F0, 0);
13804         REG_WR(sc, PXP2_REG_PGL_ADDR_90_F0, 0);
13805         REG_WR(sc, PXP2_REG_PGL_ADDR_94_F0, 0);
13806         if (CHIP_IS_E1x(sc)) {
13807             REG_WR(sc, PXP2_REG_PGL_ADDR_88_F1, 0);
13808             REG_WR(sc, PXP2_REG_PGL_ADDR_8C_F1, 0);
13809             REG_WR(sc, PXP2_REG_PGL_ADDR_90_F1, 0);
13810             REG_WR(sc, PXP2_REG_PGL_ADDR_94_F1, 0);
13811         }
13812
13813         /*
13814          * Enable internal target-read (in case we are probed after PF
13815          * FLR). Must be done prior to any BAR read access. Only for
13816          * 57712 and up
13817          */
13818         if (!CHIP_IS_E1x(sc)) {
13819             REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
13820         }
13821     }
13822
13823     /* get the nvram size */
13824     val = REG_RD(sc, MCP_REG_MCPR_NVM_CFG4);
13825     sc->devinfo.flash_size =
13826         (NVRAM_1MB_SIZE << (val & MCPR_NVM_CFG4_FLASH_SIZE));
13827     BLOGD(sc, DBG_LOAD, "nvram flash size: %d\n", sc->devinfo.flash_size);
13828
13829     /* get PCI capabilites */
13830     bxe_probe_pci_caps(sc);
13831
13832     bxe_set_power_state(sc, PCI_PM_D0);
13833
13834     /* get various configuration parameters from shmem */
13835     bxe_get_shmem_info(sc);
13836
13837     if (sc->devinfo.pcie_msix_cap_reg != 0) {
13838         val = pci_read_config(sc->dev,
13839                               (sc->devinfo.pcie_msix_cap_reg +
13840                                PCIR_MSIX_CTRL),
13841                               2);
13842         sc->igu_sb_cnt = (val & PCIM_MSIXCTRL_TABLE_SIZE);
13843     } else {
13844         sc->igu_sb_cnt = 1;
13845     }
13846
13847     sc->igu_base_addr = BAR_IGU_INTMEM;
13848
13849     /* initialize IGU parameters */
13850     if (CHIP_IS_E1x(sc)) {
13851         sc->devinfo.int_block = INT_BLOCK_HC;
13852         sc->igu_dsb_id = DEF_SB_IGU_ID;
13853         sc->igu_base_sb = 0;
13854     } else {
13855         sc->devinfo.int_block = INT_BLOCK_IGU;
13856
13857         /* do not allow device reset during IGU info preocessing */
13858         bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13859
13860         val = REG_RD(sc, IGU_REG_BLOCK_CONFIGURATION);
13861
13862         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13863             int tout = 5000;
13864
13865             BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode\n");
13866
13867             val &= ~(IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN);
13868             REG_WR(sc, IGU_REG_BLOCK_CONFIGURATION, val);
13869             REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x7f);
13870
13871             while (tout && REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13872                 tout--;
13873                 DELAY(1000);
13874             }
13875
13876             if (REG_RD(sc, IGU_REG_RESET_MEMORIES)) {
13877                 BLOGD(sc, DBG_LOAD, "FORCING IGU Normal Mode failed!!!\n");
13878                 bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13879                 return (-1);
13880             }
13881         }
13882
13883         if (val & IGU_BLOCK_CONFIGURATION_REG_BACKWARD_COMP_EN) {
13884             BLOGD(sc, DBG_LOAD, "IGU Backward Compatible Mode\n");
13885             sc->devinfo.int_block |= INT_BLOCK_MODE_BW_COMP;
13886         } else {
13887             BLOGD(sc, DBG_LOAD, "IGU Normal Mode\n");
13888         }
13889
13890         rc = bxe_get_igu_cam_info(sc);
13891
13892         bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
13893
13894         if (rc) {
13895             return (rc);
13896         }
13897     }
13898
13899     /*
13900      * Get base FW non-default (fast path) status block ID. This value is
13901      * used to initialize the fw_sb_id saved on the fp/queue structure to
13902      * determine the id used by the FW.
13903      */
13904     if (CHIP_IS_E1x(sc)) {
13905         sc->base_fw_ndsb = ((SC_PORT(sc) * FP_SB_MAX_E1x) + SC_L_ID(sc));
13906     } else {
13907         /*
13908          * 57712+ - We currently use one FW SB per IGU SB (Rx and Tx of
13909          * the same queue are indicated on the same IGU SB). So we prefer
13910          * FW and IGU SBs to be the same value.
13911          */
13912         sc->base_fw_ndsb = sc->igu_base_sb;
13913     }
13914
13915     BLOGD(sc, DBG_LOAD,
13916           "igu_dsb_id=%d igu_base_sb=%d igu_sb_cnt=%d base_fw_ndsb=%d\n",
13917           sc->igu_dsb_id, sc->igu_base_sb,
13918           sc->igu_sb_cnt, sc->base_fw_ndsb);
13919
13920     elink_phy_probe(&sc->link_params);
13921
13922     return (0);
13923 }
13924
13925 static void
13926 bxe_link_settings_supported(struct bxe_softc *sc,
13927                             uint32_t         switch_cfg)
13928 {
13929     uint32_t cfg_size = 0;
13930     uint32_t idx;
13931     uint8_t port = SC_PORT(sc);
13932
13933     /* aggregation of supported attributes of all external phys */
13934     sc->port.supported[0] = 0;
13935     sc->port.supported[1] = 0;
13936
13937     switch (sc->link_params.num_phys) {
13938     case 1:
13939         sc->port.supported[0] = sc->link_params.phy[ELINK_INT_PHY].supported;
13940         cfg_size = 1;
13941         break;
13942     case 2:
13943         sc->port.supported[0] = sc->link_params.phy[ELINK_EXT_PHY1].supported;
13944         cfg_size = 1;
13945         break;
13946     case 3:
13947         if (sc->link_params.multi_phy_config &
13948             PORT_HW_CFG_PHY_SWAPPED_ENABLED) {
13949             sc->port.supported[1] =
13950                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13951             sc->port.supported[0] =
13952                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13953         } else {
13954             sc->port.supported[0] =
13955                 sc->link_params.phy[ELINK_EXT_PHY1].supported;
13956             sc->port.supported[1] =
13957                 sc->link_params.phy[ELINK_EXT_PHY2].supported;
13958         }
13959         cfg_size = 2;
13960         break;
13961     }
13962
13963     if (!(sc->port.supported[0] || sc->port.supported[1])) {
13964         BLOGE(sc, "Invalid phy config in NVRAM (PHY1=0x%08x PHY2=0x%08x)\n",
13965               SHMEM_RD(sc,
13966                        dev_info.port_hw_config[port].external_phy_config),
13967               SHMEM_RD(sc,
13968                        dev_info.port_hw_config[port].external_phy_config2));
13969         return;
13970     }
13971
13972     if (CHIP_IS_E3(sc))
13973         sc->port.phy_addr = REG_RD(sc, MISC_REG_WC0_CTRL_PHY_ADDR);
13974     else {
13975         switch (switch_cfg) {
13976         case ELINK_SWITCH_CFG_1G:
13977             sc->port.phy_addr =
13978                 REG_RD(sc, NIG_REG_SERDES0_CTRL_PHY_ADDR + port*0x10);
13979             break;
13980         case ELINK_SWITCH_CFG_10G:
13981             sc->port.phy_addr =
13982                 REG_RD(sc, NIG_REG_XGXS0_CTRL_PHY_ADDR + port*0x18);
13983             break;
13984         default:
13985             BLOGE(sc, "Invalid switch config in link_config=0x%08x\n",
13986                   sc->port.link_config[0]);
13987             return;
13988         }
13989     }
13990
13991     BLOGD(sc, DBG_LOAD, "PHY addr 0x%08x\n", sc->port.phy_addr);
13992
13993     /* mask what we support according to speed_cap_mask per configuration */
13994     for (idx = 0; idx < cfg_size; idx++) {
13995         if (!(sc->link_params.speed_cap_mask[idx] &
13996               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_HALF)) {
13997             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Half;
13998         }
13999
14000         if (!(sc->link_params.speed_cap_mask[idx] &
14001               PORT_HW_CFG_SPEED_CAPABILITY_D0_10M_FULL)) {
14002             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10baseT_Full;
14003         }
14004
14005         if (!(sc->link_params.speed_cap_mask[idx] &
14006               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_HALF)) {
14007             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Half;
14008         }
14009
14010         if (!(sc->link_params.speed_cap_mask[idx] &
14011               PORT_HW_CFG_SPEED_CAPABILITY_D0_100M_FULL)) {
14012             sc->port.supported[idx] &= ~ELINK_SUPPORTED_100baseT_Full;
14013         }
14014
14015         if (!(sc->link_params.speed_cap_mask[idx] &
14016               PORT_HW_CFG_SPEED_CAPABILITY_D0_1G)) {
14017             sc->port.supported[idx] &= ~ELINK_SUPPORTED_1000baseT_Full;
14018         }
14019
14020         if (!(sc->link_params.speed_cap_mask[idx] &
14021               PORT_HW_CFG_SPEED_CAPABILITY_D0_2_5G)) {
14022             sc->port.supported[idx] &= ~ELINK_SUPPORTED_2500baseX_Full;
14023         }
14024
14025         if (!(sc->link_params.speed_cap_mask[idx] &
14026               PORT_HW_CFG_SPEED_CAPABILITY_D0_10G)) {
14027             sc->port.supported[idx] &= ~ELINK_SUPPORTED_10000baseT_Full;
14028         }
14029
14030         if (!(sc->link_params.speed_cap_mask[idx] &
14031               PORT_HW_CFG_SPEED_CAPABILITY_D0_20G)) {
14032             sc->port.supported[idx] &= ~ELINK_SUPPORTED_20000baseKR2_Full;
14033         }
14034     }
14035
14036     BLOGD(sc, DBG_LOAD, "PHY supported 0=0x%08x 1=0x%08x\n",
14037           sc->port.supported[0], sc->port.supported[1]);
14038 }
14039
14040 static void
14041 bxe_link_settings_requested(struct bxe_softc *sc)
14042 {
14043     uint32_t link_config;
14044     uint32_t idx;
14045     uint32_t cfg_size = 0;
14046
14047     sc->port.advertising[0] = 0;
14048     sc->port.advertising[1] = 0;
14049
14050     switch (sc->link_params.num_phys) {
14051     case 1:
14052     case 2:
14053         cfg_size = 1;
14054         break;
14055     case 3:
14056         cfg_size = 2;
14057         break;
14058     }
14059
14060     for (idx = 0; idx < cfg_size; idx++) {
14061         sc->link_params.req_duplex[idx] = DUPLEX_FULL;
14062         link_config = sc->port.link_config[idx];
14063
14064         switch (link_config & PORT_FEATURE_LINK_SPEED_MASK) {
14065         case PORT_FEATURE_LINK_SPEED_AUTO:
14066             if (sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg) {
14067                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14068                 sc->port.advertising[idx] |= sc->port.supported[idx];
14069                 if (sc->link_params.phy[ELINK_EXT_PHY1].type ==
14070                     PORT_HW_CFG_XGXS_EXT_PHY_TYPE_BCM84833)
14071                     sc->port.advertising[idx] |=
14072                         (ELINK_SUPPORTED_100baseT_Half |
14073                          ELINK_SUPPORTED_100baseT_Full);
14074             } else {
14075                 /* force 10G, no AN */
14076                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14077                 sc->port.advertising[idx] |=
14078                     (ADVERTISED_10000baseT_Full | ADVERTISED_FIBRE);
14079                 continue;
14080             }
14081             break;
14082
14083         case PORT_FEATURE_LINK_SPEED_10M_FULL:
14084             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Full) {
14085                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14086                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Full |
14087                                               ADVERTISED_TP);
14088             } else {
14089                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14090                           "speed_cap_mask=0x%08x\n",
14091                       link_config, sc->link_params.speed_cap_mask[idx]);
14092                 return;
14093             }
14094             break;
14095
14096         case PORT_FEATURE_LINK_SPEED_10M_HALF:
14097             if (sc->port.supported[idx] & ELINK_SUPPORTED_10baseT_Half) {
14098                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10;
14099                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14100                 sc->port.advertising[idx] |= (ADVERTISED_10baseT_Half |
14101                                               ADVERTISED_TP);
14102             } else {
14103                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14104                           "speed_cap_mask=0x%08x\n",
14105                       link_config, sc->link_params.speed_cap_mask[idx]);
14106                 return;
14107             }
14108             break;
14109
14110         case PORT_FEATURE_LINK_SPEED_100M_FULL:
14111             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Full) {
14112                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14113                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Full |
14114                                               ADVERTISED_TP);
14115             } else {
14116                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14117                           "speed_cap_mask=0x%08x\n",
14118                       link_config, sc->link_params.speed_cap_mask[idx]);
14119                 return;
14120             }
14121             break;
14122
14123         case PORT_FEATURE_LINK_SPEED_100M_HALF:
14124             if (sc->port.supported[idx] & ELINK_SUPPORTED_100baseT_Half) {
14125                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_100;
14126                 sc->link_params.req_duplex[idx] = DUPLEX_HALF;
14127                 sc->port.advertising[idx] |= (ADVERTISED_100baseT_Half |
14128                                               ADVERTISED_TP);
14129             } else {
14130                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14131                           "speed_cap_mask=0x%08x\n",
14132                       link_config, sc->link_params.speed_cap_mask[idx]);
14133                 return;
14134             }
14135             break;
14136
14137         case PORT_FEATURE_LINK_SPEED_1G:
14138             if (sc->port.supported[idx] & ELINK_SUPPORTED_1000baseT_Full) {
14139                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_1000;
14140                 sc->port.advertising[idx] |= (ADVERTISED_1000baseT_Full |
14141                                               ADVERTISED_TP);
14142             } else {
14143                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14144                           "speed_cap_mask=0x%08x\n",
14145                       link_config, sc->link_params.speed_cap_mask[idx]);
14146                 return;
14147             }
14148             break;
14149
14150         case PORT_FEATURE_LINK_SPEED_2_5G:
14151             if (sc->port.supported[idx] & ELINK_SUPPORTED_2500baseX_Full) {
14152                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_2500;
14153                 sc->port.advertising[idx] |= (ADVERTISED_2500baseX_Full |
14154                                               ADVERTISED_TP);
14155             } else {
14156                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14157                           "speed_cap_mask=0x%08x\n",
14158                       link_config, sc->link_params.speed_cap_mask[idx]);
14159                 return;
14160             }
14161             break;
14162
14163         case PORT_FEATURE_LINK_SPEED_10G_CX4:
14164             if (sc->port.supported[idx] & ELINK_SUPPORTED_10000baseT_Full) {
14165                 sc->link_params.req_line_speed[idx] = ELINK_SPEED_10000;
14166                 sc->port.advertising[idx] |= (ADVERTISED_10000baseT_Full |
14167                                               ADVERTISED_FIBRE);
14168             } else {
14169                 BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14170                           "speed_cap_mask=0x%08x\n",
14171                       link_config, sc->link_params.speed_cap_mask[idx]);
14172                 return;
14173             }
14174             break;
14175
14176         case PORT_FEATURE_LINK_SPEED_20G:
14177             sc->link_params.req_line_speed[idx] = ELINK_SPEED_20000;
14178             break;
14179
14180         default:
14181             BLOGE(sc, "Invalid NVRAM config link_config=0x%08x "
14182                       "speed_cap_mask=0x%08x\n",
14183                   link_config, sc->link_params.speed_cap_mask[idx]);
14184             sc->link_params.req_line_speed[idx] = ELINK_SPEED_AUTO_NEG;
14185             sc->port.advertising[idx] = sc->port.supported[idx];
14186             break;
14187         }
14188
14189         sc->link_params.req_flow_ctrl[idx] =
14190             (link_config & PORT_FEATURE_FLOW_CONTROL_MASK);
14191
14192         if (sc->link_params.req_flow_ctrl[idx] == ELINK_FLOW_CTRL_AUTO) {
14193             if (!(sc->port.supported[idx] & ELINK_SUPPORTED_Autoneg)) {
14194                 sc->link_params.req_flow_ctrl[idx] = ELINK_FLOW_CTRL_NONE;
14195             } else {
14196                 bxe_set_requested_fc(sc);
14197             }
14198         }
14199
14200         BLOGD(sc, DBG_LOAD, "req_line_speed=%d req_duplex=%d "
14201                             "req_flow_ctrl=0x%x advertising=0x%x\n",
14202               sc->link_params.req_line_speed[idx],
14203               sc->link_params.req_duplex[idx],
14204               sc->link_params.req_flow_ctrl[idx],
14205               sc->port.advertising[idx]);
14206     }
14207 }
14208
14209 static void
14210 bxe_get_phy_info(struct bxe_softc *sc)
14211 {
14212     uint8_t port = SC_PORT(sc);
14213     uint32_t config = sc->port.config;
14214     uint32_t eee_mode;
14215
14216     /* shmem data already read in bxe_get_shmem_info() */
14217
14218     BLOGD(sc, DBG_LOAD, "lane_config=0x%08x speed_cap_mask0=0x%08x "
14219                         "link_config0=0x%08x\n",
14220                sc->link_params.lane_config,
14221                sc->link_params.speed_cap_mask[0],
14222                sc->port.link_config[0]);
14223
14224     bxe_link_settings_supported(sc, sc->link_params.switch_cfg);
14225     bxe_link_settings_requested(sc);
14226
14227     if (sc->autogreeen == AUTO_GREEN_FORCE_ON) {
14228         sc->link_params.feature_config_flags |=
14229             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14230     } else if (sc->autogreeen == AUTO_GREEN_FORCE_OFF) {
14231         sc->link_params.feature_config_flags &=
14232             ~ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14233     } else if (config & PORT_FEAT_CFG_AUTOGREEEN_ENABLED) {
14234         sc->link_params.feature_config_flags |=
14235             ELINK_FEATURE_CONFIG_AUTOGREEEN_ENABLED;
14236     }
14237
14238     /* configure link feature according to nvram value */
14239     eee_mode =
14240         (((SHMEM_RD(sc, dev_info.port_feature_config[port].eee_power_mode)) &
14241           PORT_FEAT_CFG_EEE_POWER_MODE_MASK) >>
14242          PORT_FEAT_CFG_EEE_POWER_MODE_SHIFT);
14243     if (eee_mode != PORT_FEAT_CFG_EEE_POWER_MODE_DISABLED) {
14244         sc->link_params.eee_mode = (ELINK_EEE_MODE_ADV_LPI |
14245                                     ELINK_EEE_MODE_ENABLE_LPI |
14246                                     ELINK_EEE_MODE_OUTPUT_TIME);
14247     } else {
14248         sc->link_params.eee_mode = 0;
14249     }
14250
14251     /* get the media type */
14252     bxe_media_detect(sc);
14253 }
14254
14255 static void
14256 bxe_get_params(struct bxe_softc *sc)
14257 {
14258     /* get user tunable params */
14259     bxe_get_tunable_params(sc);
14260
14261     /* select the RX and TX ring sizes */
14262     sc->tx_ring_size = TX_BD_USABLE;
14263     sc->rx_ring_size = RX_BD_USABLE;
14264
14265     /* XXX disable WoL */
14266     sc->wol = 0;
14267 }
14268
14269 static void
14270 bxe_set_modes_bitmap(struct bxe_softc *sc)
14271 {
14272     uint32_t flags = 0;
14273
14274     if (CHIP_REV_IS_FPGA(sc)) {
14275         SET_FLAGS(flags, MODE_FPGA);
14276     } else if (CHIP_REV_IS_EMUL(sc)) {
14277         SET_FLAGS(flags, MODE_EMUL);
14278     } else {
14279         SET_FLAGS(flags, MODE_ASIC);
14280     }
14281
14282     if (CHIP_IS_MODE_4_PORT(sc)) {
14283         SET_FLAGS(flags, MODE_PORT4);
14284     } else {
14285         SET_FLAGS(flags, MODE_PORT2);
14286     }
14287
14288     if (CHIP_IS_E2(sc)) {
14289         SET_FLAGS(flags, MODE_E2);
14290     } else if (CHIP_IS_E3(sc)) {
14291         SET_FLAGS(flags, MODE_E3);
14292         if (CHIP_REV(sc) == CHIP_REV_Ax) {
14293             SET_FLAGS(flags, MODE_E3_A0);
14294         } else /*if (CHIP_REV(sc) == CHIP_REV_Bx)*/ {
14295             SET_FLAGS(flags, MODE_E3_B0 | MODE_COS3);
14296         }
14297     }
14298
14299     if (IS_MF(sc)) {
14300         SET_FLAGS(flags, MODE_MF);
14301         switch (sc->devinfo.mf_info.mf_mode) {
14302         case MULTI_FUNCTION_SD:
14303             SET_FLAGS(flags, MODE_MF_SD);
14304             break;
14305         case MULTI_FUNCTION_SI:
14306             SET_FLAGS(flags, MODE_MF_SI);
14307             break;
14308         case MULTI_FUNCTION_AFEX:
14309             SET_FLAGS(flags, MODE_MF_AFEX);
14310             break;
14311         }
14312     } else {
14313         SET_FLAGS(flags, MODE_SF);
14314     }
14315
14316 #if defined(__LITTLE_ENDIAN)
14317     SET_FLAGS(flags, MODE_LITTLE_ENDIAN);
14318 #else /* __BIG_ENDIAN */
14319     SET_FLAGS(flags, MODE_BIG_ENDIAN);
14320 #endif
14321
14322     INIT_MODE_FLAGS(sc) = flags;
14323 }
14324
14325 static int
14326 bxe_alloc_hsi_mem(struct bxe_softc *sc)
14327 {
14328     struct bxe_fastpath *fp;
14329     bus_addr_t busaddr;
14330     int max_agg_queues;
14331     int max_segments;
14332     bus_size_t max_size;
14333     bus_size_t max_seg_size;
14334     char buf[32];
14335     int rc;
14336     int i, j;
14337
14338     /* XXX zero out all vars here and call bxe_alloc_hsi_mem on error */
14339
14340     /* allocate the parent bus DMA tag */
14341     rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), /* parent tag */
14342                             1,                        /* alignment */
14343                             0,                        /* boundary limit */
14344                             BUS_SPACE_MAXADDR,        /* restricted low */
14345                             BUS_SPACE_MAXADDR,        /* restricted hi */
14346                             NULL,                     /* addr filter() */
14347                             NULL,                     /* addr filter() arg */
14348                             BUS_SPACE_MAXSIZE_32BIT,  /* max map size */
14349                             BUS_SPACE_UNRESTRICTED,   /* num discontinuous */
14350                             BUS_SPACE_MAXSIZE_32BIT,  /* max seg size */
14351                             0,                        /* flags */
14352                             NULL,                     /* lock() */
14353                             NULL,                     /* lock() arg */
14354                             &sc->parent_dma_tag);     /* returned dma tag */
14355     if (rc != 0) {
14356         BLOGE(sc, "Failed to alloc parent DMA tag (%d)!\n", rc);
14357         return (1);
14358     }
14359
14360     /************************/
14361     /* DEFAULT STATUS BLOCK */
14362     /************************/
14363
14364     if (bxe_dma_alloc(sc, sizeof(struct host_sp_status_block),
14365                       &sc->def_sb_dma, "default status block") != 0) {
14366         /* XXX */
14367         bus_dma_tag_destroy(sc->parent_dma_tag);
14368         return (1);
14369     }
14370
14371     sc->def_sb = (struct host_sp_status_block *)sc->def_sb_dma.vaddr;
14372
14373     /***************/
14374     /* EVENT QUEUE */
14375     /***************/
14376
14377     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14378                       &sc->eq_dma, "event queue") != 0) {
14379         /* XXX */
14380         bxe_dma_free(sc, &sc->def_sb_dma);
14381         sc->def_sb = NULL;
14382         bus_dma_tag_destroy(sc->parent_dma_tag);
14383         return (1);
14384     }
14385
14386     sc->eq = (union event_ring_elem * )sc->eq_dma.vaddr;
14387
14388     /*************/
14389     /* SLOW PATH */
14390     /*************/
14391
14392     if (bxe_dma_alloc(sc, sizeof(struct bxe_slowpath),
14393                       &sc->sp_dma, "slow path") != 0) {
14394         /* XXX */
14395         bxe_dma_free(sc, &sc->eq_dma);
14396         sc->eq = NULL;
14397         bxe_dma_free(sc, &sc->def_sb_dma);
14398         sc->def_sb = NULL;
14399         bus_dma_tag_destroy(sc->parent_dma_tag);
14400         return (1);
14401     }
14402
14403     sc->sp = (struct bxe_slowpath *)sc->sp_dma.vaddr;
14404
14405     /*******************/
14406     /* SLOW PATH QUEUE */
14407     /*******************/
14408
14409     if (bxe_dma_alloc(sc, BCM_PAGE_SIZE,
14410                       &sc->spq_dma, "slow path queue") != 0) {
14411         /* XXX */
14412         bxe_dma_free(sc, &sc->sp_dma);
14413         sc->sp = NULL;
14414         bxe_dma_free(sc, &sc->eq_dma);
14415         sc->eq = NULL;
14416         bxe_dma_free(sc, &sc->def_sb_dma);
14417         sc->def_sb = NULL;
14418         bus_dma_tag_destroy(sc->parent_dma_tag);
14419         return (1);
14420     }
14421
14422     sc->spq = (struct eth_spe *)sc->spq_dma.vaddr;
14423
14424     /***************************/
14425     /* FW DECOMPRESSION BUFFER */
14426     /***************************/
14427
14428     if (bxe_dma_alloc(sc, FW_BUF_SIZE, &sc->gz_buf_dma,
14429                       "fw decompression buffer") != 0) {
14430         /* XXX */
14431         bxe_dma_free(sc, &sc->spq_dma);
14432         sc->spq = NULL;
14433         bxe_dma_free(sc, &sc->sp_dma);
14434         sc->sp = NULL;
14435         bxe_dma_free(sc, &sc->eq_dma);
14436         sc->eq = NULL;
14437         bxe_dma_free(sc, &sc->def_sb_dma);
14438         sc->def_sb = NULL;
14439         bus_dma_tag_destroy(sc->parent_dma_tag);
14440         return (1);
14441     }
14442
14443     sc->gz_buf = (void *)sc->gz_buf_dma.vaddr;
14444
14445     if ((sc->gz_strm =
14446          malloc(sizeof(*sc->gz_strm), M_DEVBUF, M_NOWAIT)) == NULL) {
14447         /* XXX */
14448         bxe_dma_free(sc, &sc->gz_buf_dma);
14449         sc->gz_buf = NULL;
14450         bxe_dma_free(sc, &sc->spq_dma);
14451         sc->spq = NULL;
14452         bxe_dma_free(sc, &sc->sp_dma);
14453         sc->sp = NULL;
14454         bxe_dma_free(sc, &sc->eq_dma);
14455         sc->eq = NULL;
14456         bxe_dma_free(sc, &sc->def_sb_dma);
14457         sc->def_sb = NULL;
14458         bus_dma_tag_destroy(sc->parent_dma_tag);
14459         return (1);
14460     }
14461
14462     /*************/
14463     /* FASTPATHS */
14464     /*************/
14465
14466     /* allocate DMA memory for each fastpath structure */
14467     for (i = 0; i < sc->num_queues; i++) {
14468         fp = &sc->fp[i];
14469         fp->sc    = sc;
14470         fp->index = i;
14471
14472         /*******************/
14473         /* FP STATUS BLOCK */
14474         /*******************/
14475
14476         snprintf(buf, sizeof(buf), "fp %d status block", i);
14477         if (bxe_dma_alloc(sc, sizeof(union bxe_host_hc_status_block),
14478                           &fp->sb_dma, buf) != 0) {
14479             /* XXX unwind and free previous fastpath allocations */
14480             BLOGE(sc, "Failed to alloc %s\n", buf);
14481             return (1);
14482         } else {
14483             if (CHIP_IS_E2E3(sc)) {
14484                 fp->status_block.e2_sb =
14485                     (struct host_hc_status_block_e2 *)fp->sb_dma.vaddr;
14486             } else {
14487                 fp->status_block.e1x_sb =
14488                     (struct host_hc_status_block_e1x *)fp->sb_dma.vaddr;
14489             }
14490         }
14491
14492         /******************/
14493         /* FP TX BD CHAIN */
14494         /******************/
14495
14496         snprintf(buf, sizeof(buf), "fp %d tx bd chain", i);
14497         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * TX_BD_NUM_PAGES),
14498                           &fp->tx_dma, buf) != 0) {
14499             /* XXX unwind and free previous fastpath allocations */
14500             BLOGE(sc, "Failed to alloc %s\n", buf);
14501             return (1);
14502         } else {
14503             fp->tx_chain = (union eth_tx_bd_types *)fp->tx_dma.vaddr;
14504         }
14505
14506         /* link together the tx bd chain pages */
14507         for (j = 1; j <= TX_BD_NUM_PAGES; j++) {
14508             /* index into the tx bd chain array to last entry per page */
14509             struct eth_tx_next_bd *tx_next_bd =
14510                 &fp->tx_chain[TX_BD_TOTAL_PER_PAGE * j - 1].next_bd;
14511             /* point to the next page and wrap from last page */
14512             busaddr = (fp->tx_dma.paddr +
14513                        (BCM_PAGE_SIZE * (j % TX_BD_NUM_PAGES)));
14514             tx_next_bd->addr_hi = htole32(U64_HI(busaddr));
14515             tx_next_bd->addr_lo = htole32(U64_LO(busaddr));
14516         }
14517
14518         /******************/
14519         /* FP RX BD CHAIN */
14520         /******************/
14521
14522         snprintf(buf, sizeof(buf), "fp %d rx bd chain", i);
14523         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_BD_NUM_PAGES),
14524                           &fp->rx_dma, buf) != 0) {
14525             /* XXX unwind and free previous fastpath allocations */
14526             BLOGE(sc, "Failed to alloc %s\n", buf);
14527             return (1);
14528         } else {
14529             fp->rx_chain = (struct eth_rx_bd *)fp->rx_dma.vaddr;
14530         }
14531
14532         /* link together the rx bd chain pages */
14533         for (j = 1; j <= RX_BD_NUM_PAGES; j++) {
14534             /* index into the rx bd chain array to last entry per page */
14535             struct eth_rx_bd *rx_bd =
14536                 &fp->rx_chain[RX_BD_TOTAL_PER_PAGE * j - 2];
14537             /* point to the next page and wrap from last page */
14538             busaddr = (fp->rx_dma.paddr +
14539                        (BCM_PAGE_SIZE * (j % RX_BD_NUM_PAGES)));
14540             rx_bd->addr_hi = htole32(U64_HI(busaddr));
14541             rx_bd->addr_lo = htole32(U64_LO(busaddr));
14542         }
14543
14544         /*******************/
14545         /* FP RX RCQ CHAIN */
14546         /*******************/
14547
14548         snprintf(buf, sizeof(buf), "fp %d rcq chain", i);
14549         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RCQ_NUM_PAGES),
14550                           &fp->rcq_dma, buf) != 0) {
14551             /* XXX unwind and free previous fastpath allocations */
14552             BLOGE(sc, "Failed to alloc %s\n", buf);
14553             return (1);
14554         } else {
14555             fp->rcq_chain = (union eth_rx_cqe *)fp->rcq_dma.vaddr;
14556         }
14557
14558         /* link together the rcq chain pages */
14559         for (j = 1; j <= RCQ_NUM_PAGES; j++) {
14560             /* index into the rcq chain array to last entry per page */
14561             struct eth_rx_cqe_next_page *rx_cqe_next =
14562                 (struct eth_rx_cqe_next_page *)
14563                 &fp->rcq_chain[RCQ_TOTAL_PER_PAGE * j - 1];
14564             /* point to the next page and wrap from last page */
14565             busaddr = (fp->rcq_dma.paddr +
14566                        (BCM_PAGE_SIZE * (j % RCQ_NUM_PAGES)));
14567             rx_cqe_next->addr_hi = htole32(U64_HI(busaddr));
14568             rx_cqe_next->addr_lo = htole32(U64_LO(busaddr));
14569         }
14570
14571         /*******************/
14572         /* FP RX SGE CHAIN */
14573         /*******************/
14574
14575         snprintf(buf, sizeof(buf), "fp %d sge chain", i);
14576         if (bxe_dma_alloc(sc, (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES),
14577                           &fp->rx_sge_dma, buf) != 0) {
14578             /* XXX unwind and free previous fastpath allocations */
14579             BLOGE(sc, "Failed to alloc %s\n", buf);
14580             return (1);
14581         } else {
14582             fp->rx_sge_chain = (struct eth_rx_sge *)fp->rx_sge_dma.vaddr;
14583         }
14584
14585         /* link together the sge chain pages */
14586         for (j = 1; j <= RX_SGE_NUM_PAGES; j++) {
14587             /* index into the rcq chain array to last entry per page */
14588             struct eth_rx_sge *rx_sge =
14589                 &fp->rx_sge_chain[RX_SGE_TOTAL_PER_PAGE * j - 2];
14590             /* point to the next page and wrap from last page */
14591             busaddr = (fp->rx_sge_dma.paddr +
14592                        (BCM_PAGE_SIZE * (j % RX_SGE_NUM_PAGES)));
14593             rx_sge->addr_hi = htole32(U64_HI(busaddr));
14594             rx_sge->addr_lo = htole32(U64_LO(busaddr));
14595         }
14596
14597         /***********************/
14598         /* FP TX MBUF DMA MAPS */
14599         /***********************/
14600
14601         /* set required sizes before mapping to conserve resources */
14602         if (sc->ifnet->if_capenable & (IFCAP_TSO4 | IFCAP_TSO6)) {
14603             max_size     = BXE_TSO_MAX_SIZE;
14604             max_segments = BXE_TSO_MAX_SEGMENTS;
14605             max_seg_size = BXE_TSO_MAX_SEG_SIZE;
14606         } else {
14607             max_size     = (MCLBYTES * BXE_MAX_SEGMENTS);
14608             max_segments = BXE_MAX_SEGMENTS;
14609             max_seg_size = MCLBYTES;
14610         }
14611
14612         /* create a dma tag for the tx mbufs */
14613         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14614                                 1,                  /* alignment */
14615                                 0,                  /* boundary limit */
14616                                 BUS_SPACE_MAXADDR,  /* restricted low */
14617                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14618                                 NULL,               /* addr filter() */
14619                                 NULL,               /* addr filter() arg */
14620                                 max_size,           /* max map size */
14621                                 max_segments,       /* num discontinuous */
14622                                 max_seg_size,       /* max seg size */
14623                                 0,                  /* flags */
14624                                 NULL,               /* lock() */
14625                                 NULL,               /* lock() arg */
14626                                 &fp->tx_mbuf_tag);  /* returned dma tag */
14627         if (rc != 0) {
14628             /* XXX unwind and free previous fastpath allocations */
14629             BLOGE(sc, "Failed to create dma tag for "
14630                       "'fp %d tx mbufs' (%d)\n", i, rc);
14631             return (1);
14632         }
14633
14634         /* create dma maps for each of the tx mbuf clusters */
14635         for (j = 0; j < TX_BD_TOTAL; j++) {
14636             if (bus_dmamap_create(fp->tx_mbuf_tag,
14637                                   BUS_DMA_NOWAIT,
14638                                   &fp->tx_mbuf_chain[j].m_map)) {
14639                 /* XXX unwind and free previous fastpath allocations */
14640                 BLOGE(sc, "Failed to create dma map for "
14641                           "'fp %d tx mbuf %d' (%d)\n", i, j, rc);
14642                 return (1);
14643             }
14644         }
14645
14646         /***********************/
14647         /* FP RX MBUF DMA MAPS */
14648         /***********************/
14649
14650         /* create a dma tag for the rx mbufs */
14651         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14652                                 1,                  /* alignment */
14653                                 0,                  /* boundary limit */
14654                                 BUS_SPACE_MAXADDR,  /* restricted low */
14655                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14656                                 NULL,               /* addr filter() */
14657                                 NULL,               /* addr filter() arg */
14658                                 MJUM9BYTES,         /* max map size */
14659                                 1,                  /* num discontinuous */
14660                                 MJUM9BYTES,         /* max seg size */
14661                                 0,                  /* flags */
14662                                 NULL,               /* lock() */
14663                                 NULL,               /* lock() arg */
14664                                 &fp->rx_mbuf_tag);  /* returned dma tag */
14665         if (rc != 0) {
14666             /* XXX unwind and free previous fastpath allocations */
14667             BLOGE(sc, "Failed to create dma tag for "
14668                       "'fp %d rx mbufs' (%d)\n", i, rc);
14669             return (1);
14670         }
14671
14672         /* create dma maps for each of the rx mbuf clusters */
14673         for (j = 0; j < RX_BD_TOTAL; j++) {
14674             if (bus_dmamap_create(fp->rx_mbuf_tag,
14675                                   BUS_DMA_NOWAIT,
14676                                   &fp->rx_mbuf_chain[j].m_map)) {
14677                 /* XXX unwind and free previous fastpath allocations */
14678                 BLOGE(sc, "Failed to create dma map for "
14679                           "'fp %d rx mbuf %d' (%d)\n", i, j, rc);
14680                 return (1);
14681             }
14682         }
14683
14684         /* create dma map for the spare rx mbuf cluster */
14685         if (bus_dmamap_create(fp->rx_mbuf_tag,
14686                               BUS_DMA_NOWAIT,
14687                               &fp->rx_mbuf_spare_map)) {
14688             /* XXX unwind and free previous fastpath allocations */
14689             BLOGE(sc, "Failed to create dma map for "
14690                       "'fp %d spare rx mbuf' (%d)\n", i, rc);
14691             return (1);
14692         }
14693
14694         /***************************/
14695         /* FP RX SGE MBUF DMA MAPS */
14696         /***************************/
14697
14698         /* create a dma tag for the rx sge mbufs */
14699         rc = bus_dma_tag_create(sc->parent_dma_tag, /* parent tag */
14700                                 1,                  /* alignment */
14701                                 0,                  /* boundary limit */
14702                                 BUS_SPACE_MAXADDR,  /* restricted low */
14703                                 BUS_SPACE_MAXADDR,  /* restricted hi */
14704                                 NULL,               /* addr filter() */
14705                                 NULL,               /* addr filter() arg */
14706                                 BCM_PAGE_SIZE,      /* max map size */
14707                                 1,                  /* num discontinuous */
14708                                 BCM_PAGE_SIZE,      /* max seg size */
14709                                 0,                  /* flags */
14710                                 NULL,               /* lock() */
14711                                 NULL,               /* lock() arg */
14712                                 &fp->rx_sge_mbuf_tag); /* returned dma tag */
14713         if (rc != 0) {
14714             /* XXX unwind and free previous fastpath allocations */
14715             BLOGE(sc, "Failed to create dma tag for "
14716                       "'fp %d rx sge mbufs' (%d)\n", i, rc);
14717             return (1);
14718         }
14719
14720         /* create dma maps for the rx sge mbuf clusters */
14721         for (j = 0; j < RX_SGE_TOTAL; j++) {
14722             if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14723                                   BUS_DMA_NOWAIT,
14724                                   &fp->rx_sge_mbuf_chain[j].m_map)) {
14725                 /* XXX unwind and free previous fastpath allocations */
14726                 BLOGE(sc, "Failed to create dma map for "
14727                           "'fp %d rx sge mbuf %d' (%d)\n", i, j, rc);
14728                 return (1);
14729             }
14730         }
14731
14732         /* create dma map for the spare rx sge mbuf cluster */
14733         if (bus_dmamap_create(fp->rx_sge_mbuf_tag,
14734                               BUS_DMA_NOWAIT,
14735                               &fp->rx_sge_mbuf_spare_map)) {
14736             /* XXX unwind and free previous fastpath allocations */
14737             BLOGE(sc, "Failed to create dma map for "
14738                       "'fp %d spare rx sge mbuf' (%d)\n", i, rc);
14739             return (1);
14740         }
14741
14742         /***************************/
14743         /* FP RX TPA MBUF DMA MAPS */
14744         /***************************/
14745
14746         /* create dma maps for the rx tpa mbuf clusters */
14747         max_agg_queues = MAX_AGG_QS(sc);
14748
14749         for (j = 0; j < max_agg_queues; j++) {
14750             if (bus_dmamap_create(fp->rx_mbuf_tag,
14751                                   BUS_DMA_NOWAIT,
14752                                   &fp->rx_tpa_info[j].bd.m_map)) {
14753                 /* XXX unwind and free previous fastpath allocations */
14754                 BLOGE(sc, "Failed to create dma map for "
14755                           "'fp %d rx tpa mbuf %d' (%d)\n", i, j, rc);
14756                 return (1);
14757             }
14758         }
14759
14760         /* create dma map for the spare rx tpa mbuf cluster */
14761         if (bus_dmamap_create(fp->rx_mbuf_tag,
14762                               BUS_DMA_NOWAIT,
14763                               &fp->rx_tpa_info_mbuf_spare_map)) {
14764             /* XXX unwind and free previous fastpath allocations */
14765             BLOGE(sc, "Failed to create dma map for "
14766                       "'fp %d spare rx tpa mbuf' (%d)\n", i, rc);
14767             return (1);
14768         }
14769
14770         bxe_init_sge_ring_bit_mask(fp);
14771     }
14772
14773     return (0);
14774 }
14775
14776 static void
14777 bxe_free_hsi_mem(struct bxe_softc *sc)
14778 {
14779     struct bxe_fastpath *fp;
14780     int max_agg_queues;
14781     int i, j;
14782
14783     if (sc->parent_dma_tag == NULL) {
14784         return; /* assume nothing was allocated */
14785     }
14786
14787     for (i = 0; i < sc->num_queues; i++) {
14788         fp = &sc->fp[i];
14789
14790         /*******************/
14791         /* FP STATUS BLOCK */
14792         /*******************/
14793
14794         bxe_dma_free(sc, &fp->sb_dma);
14795         memset(&fp->status_block, 0, sizeof(fp->status_block));
14796
14797         /******************/
14798         /* FP TX BD CHAIN */
14799         /******************/
14800
14801         bxe_dma_free(sc, &fp->tx_dma);
14802         fp->tx_chain = NULL;
14803
14804         /******************/
14805         /* FP RX BD CHAIN */
14806         /******************/
14807
14808         bxe_dma_free(sc, &fp->rx_dma);
14809         fp->rx_chain = NULL;
14810
14811         /*******************/
14812         /* FP RX RCQ CHAIN */
14813         /*******************/
14814
14815         bxe_dma_free(sc, &fp->rcq_dma);
14816         fp->rcq_chain = NULL;
14817
14818         /*******************/
14819         /* FP RX SGE CHAIN */
14820         /*******************/
14821
14822         bxe_dma_free(sc, &fp->rx_sge_dma);
14823         fp->rx_sge_chain = NULL;
14824
14825         /***********************/
14826         /* FP TX MBUF DMA MAPS */
14827         /***********************/
14828
14829         if (fp->tx_mbuf_tag != NULL) {
14830             for (j = 0; j < TX_BD_TOTAL; j++) {
14831                 if (fp->tx_mbuf_chain[j].m_map != NULL) {
14832                     bus_dmamap_unload(fp->tx_mbuf_tag,
14833                                       fp->tx_mbuf_chain[j].m_map);
14834                     bus_dmamap_destroy(fp->tx_mbuf_tag,
14835                                        fp->tx_mbuf_chain[j].m_map);
14836                 }
14837             }
14838
14839             bus_dma_tag_destroy(fp->tx_mbuf_tag);
14840             fp->tx_mbuf_tag = NULL;
14841         }
14842
14843         /***********************/
14844         /* FP RX MBUF DMA MAPS */
14845         /***********************/
14846
14847         if (fp->rx_mbuf_tag != NULL) {
14848             for (j = 0; j < RX_BD_TOTAL; j++) {
14849                 if (fp->rx_mbuf_chain[j].m_map != NULL) {
14850                     bus_dmamap_unload(fp->rx_mbuf_tag,
14851                                       fp->rx_mbuf_chain[j].m_map);
14852                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14853                                        fp->rx_mbuf_chain[j].m_map);
14854                 }
14855             }
14856
14857             if (fp->rx_mbuf_spare_map != NULL) {
14858                 bus_dmamap_unload(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14859                 bus_dmamap_destroy(fp->rx_mbuf_tag, fp->rx_mbuf_spare_map);
14860             }
14861
14862             /***************************/
14863             /* FP RX TPA MBUF DMA MAPS */
14864             /***************************/
14865
14866             max_agg_queues = MAX_AGG_QS(sc);
14867
14868             for (j = 0; j < max_agg_queues; j++) {
14869                 if (fp->rx_tpa_info[j].bd.m_map != NULL) {
14870                     bus_dmamap_unload(fp->rx_mbuf_tag,
14871                                       fp->rx_tpa_info[j].bd.m_map);
14872                     bus_dmamap_destroy(fp->rx_mbuf_tag,
14873                                        fp->rx_tpa_info[j].bd.m_map);
14874                 }
14875             }
14876
14877             if (fp->rx_tpa_info_mbuf_spare_map != NULL) {
14878                 bus_dmamap_unload(fp->rx_mbuf_tag,
14879                                   fp->rx_tpa_info_mbuf_spare_map);
14880                 bus_dmamap_destroy(fp->rx_mbuf_tag,
14881                                    fp->rx_tpa_info_mbuf_spare_map);
14882             }
14883
14884             bus_dma_tag_destroy(fp->rx_mbuf_tag);
14885             fp->rx_mbuf_tag = NULL;
14886         }
14887
14888         /***************************/
14889         /* FP RX SGE MBUF DMA MAPS */
14890         /***************************/
14891
14892         if (fp->rx_sge_mbuf_tag != NULL) {
14893             for (j = 0; j < RX_SGE_TOTAL; j++) {
14894                 if (fp->rx_sge_mbuf_chain[j].m_map != NULL) {
14895                     bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14896                                       fp->rx_sge_mbuf_chain[j].m_map);
14897                     bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14898                                        fp->rx_sge_mbuf_chain[j].m_map);
14899                 }
14900             }
14901
14902             if (fp->rx_sge_mbuf_spare_map != NULL) {
14903                 bus_dmamap_unload(fp->rx_sge_mbuf_tag,
14904                                   fp->rx_sge_mbuf_spare_map);
14905                 bus_dmamap_destroy(fp->rx_sge_mbuf_tag,
14906                                    fp->rx_sge_mbuf_spare_map);
14907             }
14908
14909             bus_dma_tag_destroy(fp->rx_sge_mbuf_tag);
14910             fp->rx_sge_mbuf_tag = NULL;
14911         }
14912     }
14913
14914     /***************************/
14915     /* FW DECOMPRESSION BUFFER */
14916     /***************************/
14917
14918     bxe_dma_free(sc, &sc->gz_buf_dma);
14919     sc->gz_buf = NULL;
14920     free(sc->gz_strm, M_DEVBUF);
14921     sc->gz_strm = NULL;
14922
14923     /*******************/
14924     /* SLOW PATH QUEUE */
14925     /*******************/
14926
14927     bxe_dma_free(sc, &sc->spq_dma);
14928     sc->spq = NULL;
14929
14930     /*************/
14931     /* SLOW PATH */
14932     /*************/
14933
14934     bxe_dma_free(sc, &sc->sp_dma);
14935     sc->sp = NULL;
14936
14937     /***************/
14938     /* EVENT QUEUE */
14939     /***************/
14940
14941     bxe_dma_free(sc, &sc->eq_dma);
14942     sc->eq = NULL;
14943
14944     /************************/
14945     /* DEFAULT STATUS BLOCK */
14946     /************************/
14947
14948     bxe_dma_free(sc, &sc->def_sb_dma);
14949     sc->def_sb = NULL;
14950
14951     bus_dma_tag_destroy(sc->parent_dma_tag);
14952     sc->parent_dma_tag = NULL;
14953 }
14954
14955 /*
14956  * Previous driver DMAE transaction may have occurred when pre-boot stage
14957  * ended and boot began. This would invalidate the addresses of the
14958  * transaction, resulting in was-error bit set in the PCI causing all
14959  * hw-to-host PCIe transactions to timeout. If this happened we want to clear
14960  * the interrupt which detected this from the pglueb and the was-done bit
14961  */
14962 static void
14963 bxe_prev_interrupted_dmae(struct bxe_softc *sc)
14964 {
14965     uint32_t val;
14966
14967     if (!CHIP_IS_E1x(sc)) {
14968         val = REG_RD(sc, PGLUE_B_REG_PGLUE_B_INT_STS);
14969         if (val & PGLUE_B_PGLUE_B_INT_STS_REG_WAS_ERROR_ATTN) {
14970             BLOGD(sc, DBG_LOAD,
14971                   "Clearing 'was-error' bit that was set in pglueb");
14972             REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, 1 << SC_FUNC(sc));
14973         }
14974     }
14975 }
14976
14977 static int
14978 bxe_prev_mcp_done(struct bxe_softc *sc)
14979 {
14980     uint32_t rc = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_DONE,
14981                                  DRV_MSG_CODE_UNLOAD_SKIP_LINK_RESET);
14982     if (!rc) {
14983         BLOGE(sc, "MCP response failure, aborting\n");
14984         return (-1);
14985     }
14986
14987     return (0);
14988 }
14989
14990 static struct bxe_prev_list_node *
14991 bxe_prev_path_get_entry(struct bxe_softc *sc)
14992 {
14993     struct bxe_prev_list_node *tmp;
14994
14995     LIST_FOREACH(tmp, &bxe_prev_list, node) {
14996         if ((sc->pcie_bus == tmp->bus) &&
14997             (sc->pcie_device == tmp->slot) &&
14998             (SC_PATH(sc) == tmp->path)) {
14999             return (tmp);
15000         }
15001     }
15002
15003     return (NULL);
15004 }
15005
15006 static uint8_t
15007 bxe_prev_is_path_marked(struct bxe_softc *sc)
15008 {
15009     struct bxe_prev_list_node *tmp;
15010     int rc = FALSE;
15011
15012     mtx_lock(&bxe_prev_mtx);
15013
15014     tmp = bxe_prev_path_get_entry(sc);
15015     if (tmp) {
15016         if (tmp->aer) {
15017             BLOGD(sc, DBG_LOAD,
15018                   "Path %d/%d/%d was marked by AER\n",
15019                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15020         } else {
15021             rc = TRUE;
15022             BLOGD(sc, DBG_LOAD,
15023                   "Path %d/%d/%d was already cleaned from previous drivers\n",
15024                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15025         }
15026     }
15027
15028     mtx_unlock(&bxe_prev_mtx);
15029
15030     return (rc);
15031 }
15032
15033 static int
15034 bxe_prev_mark_path(struct bxe_softc *sc,
15035                    uint8_t          after_undi)
15036 {
15037     struct bxe_prev_list_node *tmp;
15038
15039     mtx_lock(&bxe_prev_mtx);
15040
15041     /* Check whether the entry for this path already exists */
15042     tmp = bxe_prev_path_get_entry(sc);
15043     if (tmp) {
15044         if (!tmp->aer) {
15045             BLOGD(sc, DBG_LOAD,
15046                   "Re-marking AER in path %d/%d/%d\n",
15047                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15048         } else {
15049             BLOGD(sc, DBG_LOAD,
15050                   "Removing AER indication from path %d/%d/%d\n",
15051                   sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15052             tmp->aer = 0;
15053         }
15054
15055         mtx_unlock(&bxe_prev_mtx);
15056         return (0);
15057     }
15058
15059     mtx_unlock(&bxe_prev_mtx);
15060
15061     /* Create an entry for this path and add it */
15062     tmp = malloc(sizeof(struct bxe_prev_list_node), M_DEVBUF,
15063                  (M_NOWAIT | M_ZERO));
15064     if (!tmp) {
15065         BLOGE(sc, "Failed to allocate 'bxe_prev_list_node'\n");
15066         return (-1);
15067     }
15068
15069     tmp->bus  = sc->pcie_bus;
15070     tmp->slot = sc->pcie_device;
15071     tmp->path = SC_PATH(sc);
15072     tmp->aer  = 0;
15073     tmp->undi = after_undi ? (1 << SC_PORT(sc)) : 0;
15074
15075     mtx_lock(&bxe_prev_mtx);
15076
15077     BLOGD(sc, DBG_LOAD,
15078           "Marked path %d/%d/%d - finished previous unload\n",
15079           sc->pcie_bus, sc->pcie_device, SC_PATH(sc));
15080     LIST_INSERT_HEAD(&bxe_prev_list, tmp, node);
15081
15082     mtx_unlock(&bxe_prev_mtx);
15083
15084     return (0);
15085 }
15086
15087 static int
15088 bxe_do_flr(struct bxe_softc *sc)
15089 {
15090     int i;
15091
15092     /* only E2 and onwards support FLR */
15093     if (CHIP_IS_E1x(sc)) {
15094         BLOGD(sc, DBG_LOAD, "FLR not supported in E1/E1H\n");
15095         return (-1);
15096     }
15097
15098     /* only bootcode REQ_BC_VER_4_INITIATE_FLR and onwards support flr */
15099     if (sc->devinfo.bc_ver < REQ_BC_VER_4_INITIATE_FLR) {
15100         BLOGD(sc, DBG_LOAD, "FLR not supported by BC_VER: 0x%08x\n",
15101               sc->devinfo.bc_ver);
15102         return (-1);
15103     }
15104
15105     /* Wait for Transaction Pending bit clean */
15106     for (i = 0; i < 4; i++) {
15107         if (i) {
15108             DELAY(((1 << (i - 1)) * 100) * 1000);
15109         }
15110
15111         if (!bxe_is_pcie_pending(sc)) {
15112             goto clear;
15113         }
15114     }
15115
15116     BLOGE(sc, "PCIE transaction is not cleared, "
15117               "proceeding with reset anyway\n");
15118
15119 clear:
15120
15121     BLOGD(sc, DBG_LOAD, "Initiating FLR\n");
15122     bxe_fw_command(sc, DRV_MSG_CODE_INITIATE_FLR, 0);
15123
15124     return (0);
15125 }
15126
15127 struct bxe_mac_vals {
15128     uint32_t xmac_addr;
15129     uint32_t xmac_val;
15130     uint32_t emac_addr;
15131     uint32_t emac_val;
15132     uint32_t umac_addr;
15133     uint32_t umac_val;
15134     uint32_t bmac_addr;
15135     uint32_t bmac_val[2];
15136 };
15137
15138 static void
15139 bxe_prev_unload_close_mac(struct bxe_softc *sc,
15140                           struct bxe_mac_vals *vals)
15141 {
15142     uint32_t val, base_addr, offset, mask, reset_reg;
15143     uint8_t mac_stopped = FALSE;
15144     uint8_t port = SC_PORT(sc);
15145     uint32_t wb_data[2];
15146
15147     /* reset addresses as they also mark which values were changed */
15148     vals->bmac_addr = 0;
15149     vals->umac_addr = 0;
15150     vals->xmac_addr = 0;
15151     vals->emac_addr = 0;
15152
15153     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_2);
15154
15155     if (!CHIP_IS_E3(sc)) {
15156         val = REG_RD(sc, NIG_REG_BMAC0_REGS_OUT_EN + port * 4);
15157         mask = MISC_REGISTERS_RESET_REG_2_RST_BMAC0 << port;
15158         if ((mask & reset_reg) && val) {
15159             BLOGD(sc, DBG_LOAD, "Disable BMAC Rx\n");
15160             base_addr = SC_PORT(sc) ? NIG_REG_INGRESS_BMAC1_MEM
15161                                     : NIG_REG_INGRESS_BMAC0_MEM;
15162             offset = CHIP_IS_E2(sc) ? BIGMAC2_REGISTER_BMAC_CONTROL
15163                                     : BIGMAC_REGISTER_BMAC_CONTROL;
15164
15165             /*
15166              * use rd/wr since we cannot use dmae. This is safe
15167              * since MCP won't access the bus due to the request
15168              * to unload, and no function on the path can be
15169              * loaded at this time.
15170              */
15171             wb_data[0] = REG_RD(sc, base_addr + offset);
15172             wb_data[1] = REG_RD(sc, base_addr + offset + 0x4);
15173             vals->bmac_addr = base_addr + offset;
15174             vals->bmac_val[0] = wb_data[0];
15175             vals->bmac_val[1] = wb_data[1];
15176             wb_data[0] &= ~ELINK_BMAC_CONTROL_RX_ENABLE;
15177             REG_WR(sc, vals->bmac_addr, wb_data[0]);
15178             REG_WR(sc, vals->bmac_addr + 0x4, wb_data[1]);
15179         }
15180
15181         BLOGD(sc, DBG_LOAD, "Disable EMAC Rx\n");
15182         vals->emac_addr = NIG_REG_NIG_EMAC0_EN + SC_PORT(sc)*4;
15183         vals->emac_val = REG_RD(sc, vals->emac_addr);
15184         REG_WR(sc, vals->emac_addr, 0);
15185         mac_stopped = TRUE;
15186     } else {
15187         if (reset_reg & MISC_REGISTERS_RESET_REG_2_XMAC) {
15188             BLOGD(sc, DBG_LOAD, "Disable XMAC Rx\n");
15189             base_addr = SC_PORT(sc) ? GRCBASE_XMAC1 : GRCBASE_XMAC0;
15190             val = REG_RD(sc, base_addr + XMAC_REG_PFC_CTRL_HI);
15191             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val & ~(1 << 1));
15192             REG_WR(sc, base_addr + XMAC_REG_PFC_CTRL_HI, val | (1 << 1));
15193             vals->xmac_addr = base_addr + XMAC_REG_CTRL;
15194             vals->xmac_val = REG_RD(sc, vals->xmac_addr);
15195             REG_WR(sc, vals->xmac_addr, 0);
15196             mac_stopped = TRUE;
15197         }
15198
15199         mask = MISC_REGISTERS_RESET_REG_2_UMAC0 << port;
15200         if (mask & reset_reg) {
15201             BLOGD(sc, DBG_LOAD, "Disable UMAC Rx\n");
15202             base_addr = SC_PORT(sc) ? GRCBASE_UMAC1 : GRCBASE_UMAC0;
15203             vals->umac_addr = base_addr + UMAC_REG_COMMAND_CONFIG;
15204             vals->umac_val = REG_RD(sc, vals->umac_addr);
15205             REG_WR(sc, vals->umac_addr, 0);
15206             mac_stopped = TRUE;
15207         }
15208     }
15209
15210     if (mac_stopped) {
15211         DELAY(20000);
15212     }
15213 }
15214
15215 #define BXE_PREV_UNDI_PROD_ADDR(p)  (BAR_TSTRORM_INTMEM + 0x1508 + ((p) << 4))
15216 #define BXE_PREV_UNDI_RCQ(val)      ((val) & 0xffff)
15217 #define BXE_PREV_UNDI_BD(val)       ((val) >> 16 & 0xffff)
15218 #define BXE_PREV_UNDI_PROD(rcq, bd) ((bd) << 16 | (rcq))
15219
15220 static void
15221 bxe_prev_unload_undi_inc(struct bxe_softc *sc,
15222                          uint8_t          port,
15223                          uint8_t          inc)
15224 {
15225     uint16_t rcq, bd;
15226     uint32_t tmp_reg = REG_RD(sc, BXE_PREV_UNDI_PROD_ADDR(port));
15227
15228     rcq = BXE_PREV_UNDI_RCQ(tmp_reg) + inc;
15229     bd = BXE_PREV_UNDI_BD(tmp_reg) + inc;
15230
15231     tmp_reg = BXE_PREV_UNDI_PROD(rcq, bd);
15232     REG_WR(sc, BXE_PREV_UNDI_PROD_ADDR(port), tmp_reg);
15233
15234     BLOGD(sc, DBG_LOAD,
15235           "UNDI producer [%d] rings bd -> 0x%04x, rcq -> 0x%04x\n",
15236           port, bd, rcq);
15237 }
15238
15239 static int
15240 bxe_prev_unload_common(struct bxe_softc *sc)
15241 {
15242     uint32_t reset_reg, tmp_reg = 0, rc;
15243     uint8_t prev_undi = FALSE;
15244     struct bxe_mac_vals mac_vals;
15245     uint32_t timer_count = 1000;
15246     uint32_t prev_brb;
15247
15248     /*
15249      * It is possible a previous function received 'common' answer,
15250      * but hasn't loaded yet, therefore creating a scenario of
15251      * multiple functions receiving 'common' on the same path.
15252      */
15253     BLOGD(sc, DBG_LOAD, "Common unload Flow\n");
15254
15255     memset(&mac_vals, 0, sizeof(mac_vals));
15256
15257     if (bxe_prev_is_path_marked(sc)) {
15258         return (bxe_prev_mcp_done(sc));
15259     }
15260
15261     reset_reg = REG_RD(sc, MISC_REG_RESET_REG_1);
15262
15263     /* Reset should be performed after BRB is emptied */
15264     if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_BRB1) {
15265         /* Close the MAC Rx to prevent BRB from filling up */
15266         bxe_prev_unload_close_mac(sc, &mac_vals);
15267
15268         /* close LLH filters towards the BRB */
15269         elink_set_rx_filter(&sc->link_params, 0);
15270
15271         /*
15272          * Check if the UNDI driver was previously loaded.
15273          * UNDI driver initializes CID offset for normal bell to 0x7
15274          */
15275         if (reset_reg & MISC_REGISTERS_RESET_REG_1_RST_DORQ) {
15276             tmp_reg = REG_RD(sc, DORQ_REG_NORM_CID_OFST);
15277             if (tmp_reg == 0x7) {
15278                 BLOGD(sc, DBG_LOAD, "UNDI previously loaded\n");
15279                 prev_undi = TRUE;
15280                 /* clear the UNDI indication */
15281                 REG_WR(sc, DORQ_REG_NORM_CID_OFST, 0);
15282                 /* clear possible idle check errors */
15283                 REG_RD(sc, NIG_REG_NIG_INT_STS_CLR_0);
15284             }
15285         }
15286
15287         /* wait until BRB is empty */
15288         tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15289         while (timer_count) {
15290             prev_brb = tmp_reg;
15291
15292             tmp_reg = REG_RD(sc, BRB1_REG_NUM_OF_FULL_BLOCKS);
15293             if (!tmp_reg) {
15294                 break;
15295             }
15296
15297             BLOGD(sc, DBG_LOAD, "BRB still has 0x%08x\n", tmp_reg);
15298
15299             /* reset timer as long as BRB actually gets emptied */
15300             if (prev_brb > tmp_reg) {
15301                 timer_count = 1000;
15302             } else {
15303                 timer_count--;
15304             }
15305
15306             /* If UNDI resides in memory, manually increment it */
15307             if (prev_undi) {
15308                 bxe_prev_unload_undi_inc(sc, SC_PORT(sc), 1);
15309             }
15310
15311             DELAY(10);
15312         }
15313
15314         if (!timer_count) {
15315             BLOGE(sc, "Failed to empty BRB\n");
15316         }
15317     }
15318
15319     /* No packets are in the pipeline, path is ready for reset */
15320     bxe_reset_common(sc);
15321
15322     if (mac_vals.xmac_addr) {
15323         REG_WR(sc, mac_vals.xmac_addr, mac_vals.xmac_val);
15324     }
15325     if (mac_vals.umac_addr) {
15326         REG_WR(sc, mac_vals.umac_addr, mac_vals.umac_val);
15327     }
15328     if (mac_vals.emac_addr) {
15329         REG_WR(sc, mac_vals.emac_addr, mac_vals.emac_val);
15330     }
15331     if (mac_vals.bmac_addr) {
15332         REG_WR(sc, mac_vals.bmac_addr, mac_vals.bmac_val[0]);
15333         REG_WR(sc, mac_vals.bmac_addr + 4, mac_vals.bmac_val[1]);
15334     }
15335
15336     rc = bxe_prev_mark_path(sc, prev_undi);
15337     if (rc) {
15338         bxe_prev_mcp_done(sc);
15339         return (rc);
15340     }
15341
15342     return (bxe_prev_mcp_done(sc));
15343 }
15344
15345 static int
15346 bxe_prev_unload_uncommon(struct bxe_softc *sc)
15347 {
15348     int rc;
15349
15350     BLOGD(sc, DBG_LOAD, "Uncommon unload Flow\n");
15351
15352     /* Test if previous unload process was already finished for this path */
15353     if (bxe_prev_is_path_marked(sc)) {
15354         return (bxe_prev_mcp_done(sc));
15355     }
15356
15357     BLOGD(sc, DBG_LOAD, "Path is unmarked\n");
15358
15359     /*
15360      * If function has FLR capabilities, and existing FW version matches
15361      * the one required, then FLR will be sufficient to clean any residue
15362      * left by previous driver
15363      */
15364     rc = bxe_nic_load_analyze_req(sc, FW_MSG_CODE_DRV_LOAD_FUNCTION);
15365     if (!rc) {
15366         /* fw version is good */
15367         BLOGD(sc, DBG_LOAD, "FW version matches our own, attempting FLR\n");
15368         rc = bxe_do_flr(sc);
15369     }
15370
15371     if (!rc) {
15372         /* FLR was performed */
15373         BLOGD(sc, DBG_LOAD, "FLR successful\n");
15374         return (0);
15375     }
15376
15377     BLOGD(sc, DBG_LOAD, "Could not FLR\n");
15378
15379     /* Close the MCP request, return failure*/
15380     rc = bxe_prev_mcp_done(sc);
15381     if (!rc) {
15382         rc = BXE_PREV_WAIT_NEEDED;
15383     }
15384
15385     return (rc);
15386 }
15387
15388 static int
15389 bxe_prev_unload(struct bxe_softc *sc)
15390 {
15391     int time_counter = 10;
15392     uint32_t fw, hw_lock_reg, hw_lock_val;
15393     uint32_t rc = 0;
15394
15395     /*
15396      * Clear HW from errors which may have resulted from an interrupted
15397      * DMAE transaction.
15398      */
15399     bxe_prev_interrupted_dmae(sc);
15400
15401     /* Release previously held locks */
15402     hw_lock_reg =
15403         (SC_FUNC(sc) <= 5) ?
15404             (MISC_REG_DRIVER_CONTROL_1 + SC_FUNC(sc) * 8) :
15405             (MISC_REG_DRIVER_CONTROL_7 + (SC_FUNC(sc) - 6) * 8);
15406
15407     hw_lock_val = (REG_RD(sc, hw_lock_reg));
15408     if (hw_lock_val) {
15409         if (hw_lock_val & HW_LOCK_RESOURCE_NVRAM) {
15410             BLOGD(sc, DBG_LOAD, "Releasing previously held NVRAM lock\n");
15411             REG_WR(sc, MCP_REG_MCPR_NVM_SW_ARB,
15412                    (MCPR_NVM_SW_ARB_ARB_REQ_CLR1 << SC_PORT(sc)));
15413         }
15414         BLOGD(sc, DBG_LOAD, "Releasing previously held HW lock\n");
15415         REG_WR(sc, hw_lock_reg, 0xffffffff);
15416     } else {
15417         BLOGD(sc, DBG_LOAD, "No need to release HW/NVRAM locks\n");
15418     }
15419
15420     if (MCPR_ACCESS_LOCK_LOCK & REG_RD(sc, MCP_REG_MCPR_ACCESS_LOCK)) {
15421         BLOGD(sc, DBG_LOAD, "Releasing previously held ALR\n");
15422         REG_WR(sc, MCP_REG_MCPR_ACCESS_LOCK, 0);
15423     }
15424
15425     do {
15426         /* Lock MCP using an unload request */
15427         fw = bxe_fw_command(sc, DRV_MSG_CODE_UNLOAD_REQ_WOL_DIS, 0);
15428         if (!fw) {
15429             BLOGE(sc, "MCP response failure, aborting\n");
15430             rc = -1;
15431             break;
15432         }
15433
15434         if (fw == FW_MSG_CODE_DRV_UNLOAD_COMMON) {
15435             rc = bxe_prev_unload_common(sc);
15436             break;
15437         }
15438
15439         /* non-common reply from MCP night require looping */
15440         rc = bxe_prev_unload_uncommon(sc);
15441         if (rc != BXE_PREV_WAIT_NEEDED) {
15442             break;
15443         }
15444
15445         DELAY(20000);
15446     } while (--time_counter);
15447
15448     if (!time_counter || rc) {
15449         BLOGE(sc, "Failed to unload previous driver!"
15450             " time_counter %d rc %d\n", time_counter, rc);
15451         rc = -1;
15452     }
15453
15454     return (rc);
15455 }
15456
15457 void
15458 bxe_dcbx_set_state(struct bxe_softc *sc,
15459                    uint8_t          dcb_on,
15460                    uint32_t         dcbx_enabled)
15461 {
15462     if (!CHIP_IS_E1x(sc)) {
15463         sc->dcb_state = dcb_on;
15464         sc->dcbx_enabled = dcbx_enabled;
15465     } else {
15466         sc->dcb_state = FALSE;
15467         sc->dcbx_enabled = BXE_DCBX_ENABLED_INVALID;
15468     }
15469     BLOGD(sc, DBG_LOAD,
15470           "DCB state [%s:%s]\n",
15471           dcb_on ? "ON" : "OFF",
15472           (dcbx_enabled == BXE_DCBX_ENABLED_OFF) ? "user-mode" :
15473           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_OFF) ? "on-chip static" :
15474           (dcbx_enabled == BXE_DCBX_ENABLED_ON_NEG_ON) ?
15475           "on-chip with negotiation" : "invalid");
15476 }
15477
15478 /* must be called after sriov-enable */
15479 static int
15480 bxe_set_qm_cid_count(struct bxe_softc *sc)
15481 {
15482     int cid_count = BXE_L2_MAX_CID(sc);
15483
15484     if (IS_SRIOV(sc)) {
15485         cid_count += BXE_VF_CIDS;
15486     }
15487
15488     if (CNIC_SUPPORT(sc)) {
15489         cid_count += CNIC_CID_MAX;
15490     }
15491
15492     return (roundup(cid_count, QM_CID_ROUND));
15493 }
15494
15495 static void
15496 bxe_init_multi_cos(struct bxe_softc *sc)
15497 {
15498     int pri, cos;
15499
15500     uint32_t pri_map = 0; /* XXX change to user config */
15501
15502     for (pri = 0; pri < BXE_MAX_PRIORITY; pri++) {
15503         cos = ((pri_map & (0xf << (pri * 4))) >> (pri * 4));
15504         if (cos < sc->max_cos) {
15505             sc->prio_to_cos[pri] = cos;
15506         } else {
15507             BLOGW(sc, "Invalid COS %d for priority %d "
15508                       "(max COS is %d), setting to 0\n",
15509                   cos, pri, (sc->max_cos - 1));
15510             sc->prio_to_cos[pri] = 0;
15511         }
15512     }
15513 }
15514
15515 static int
15516 bxe_sysctl_state(SYSCTL_HANDLER_ARGS)
15517 {
15518     struct bxe_softc *sc;
15519     int error, result;
15520
15521     result = 0;
15522     error = sysctl_handle_int(oidp, &result, 0, req);
15523
15524     if (error || !req->newptr) {
15525         return (error);
15526     }
15527
15528     if (result == 1) {
15529         uint32_t  temp;
15530         sc = (struct bxe_softc *)arg1;
15531
15532         BLOGI(sc, "... dumping driver state ...\n");
15533         temp = SHMEM2_RD(sc, temperature_in_half_celsius);
15534         BLOGI(sc, "\t Device Temperature = %d Celsius\n", (temp/2));
15535     }
15536
15537     return (error);
15538 }
15539
15540 static int
15541 bxe_sysctl_eth_stat(SYSCTL_HANDLER_ARGS)
15542 {
15543     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15544     uint32_t *eth_stats = (uint32_t *)&sc->eth_stats;
15545     uint32_t *offset;
15546     uint64_t value = 0;
15547     int index = (int)arg2;
15548
15549     if (index >= BXE_NUM_ETH_STATS) {
15550         BLOGE(sc, "bxe_eth_stats index out of range (%d)\n", index);
15551         return (-1);
15552     }
15553
15554     offset = (eth_stats + bxe_eth_stats_arr[index].offset);
15555
15556     switch (bxe_eth_stats_arr[index].size) {
15557     case 4:
15558         value = (uint64_t)*offset;
15559         break;
15560     case 8:
15561         value = HILO_U64(*offset, *(offset + 1));
15562         break;
15563     default:
15564         BLOGE(sc, "Invalid bxe_eth_stats size (index=%d size=%d)\n",
15565               index, bxe_eth_stats_arr[index].size);
15566         return (-1);
15567     }
15568
15569     return (sysctl_handle_64(oidp, &value, 0, req));
15570 }
15571
15572 static int
15573 bxe_sysctl_eth_q_stat(SYSCTL_HANDLER_ARGS)
15574 {
15575     struct bxe_softc *sc = (struct bxe_softc *)arg1;
15576     uint32_t *eth_stats;
15577     uint32_t *offset;
15578     uint64_t value = 0;
15579     uint32_t q_stat = (uint32_t)arg2;
15580     uint32_t fp_index = ((q_stat >> 16) & 0xffff);
15581     uint32_t index = (q_stat & 0xffff);
15582
15583     eth_stats = (uint32_t *)&sc->fp[fp_index].eth_q_stats;
15584
15585     if (index >= BXE_NUM_ETH_Q_STATS) {
15586         BLOGE(sc, "bxe_eth_q_stats index out of range (%d)\n", index);
15587         return (-1);
15588     }
15589
15590     offset = (eth_stats + bxe_eth_q_stats_arr[index].offset);
15591
15592     switch (bxe_eth_q_stats_arr[index].size) {
15593     case 4:
15594         value = (uint64_t)*offset;
15595         break;
15596     case 8:
15597         value = HILO_U64(*offset, *(offset + 1));
15598         break;
15599     default:
15600         BLOGE(sc, "Invalid bxe_eth_q_stats size (index=%d size=%d)\n",
15601               index, bxe_eth_q_stats_arr[index].size);
15602         return (-1);
15603     }
15604
15605     return (sysctl_handle_64(oidp, &value, 0, req));
15606 }
15607
15608 static void
15609 bxe_add_sysctls(struct bxe_softc *sc)
15610 {
15611     struct sysctl_ctx_list *ctx;
15612     struct sysctl_oid_list *children;
15613     struct sysctl_oid *queue_top, *queue;
15614     struct sysctl_oid_list *queue_top_children, *queue_children;
15615     char queue_num_buf[32];
15616     uint32_t q_stat;
15617     int i, j;
15618
15619     ctx = device_get_sysctl_ctx(sc->dev);
15620     children = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev));
15621
15622     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "version",
15623                       CTLFLAG_RD, BXE_DRIVER_VERSION, 0,
15624                       "version");
15625
15626     snprintf(sc->fw_ver_str, sizeof(sc->fw_ver_str), "%d.%d.%d.%d",
15627              BCM_5710_FW_MAJOR_VERSION,
15628              BCM_5710_FW_MINOR_VERSION,
15629              BCM_5710_FW_REVISION_VERSION,
15630              BCM_5710_FW_ENGINEERING_VERSION);
15631
15632     snprintf(sc->mf_mode_str, sizeof(sc->mf_mode_str), "%s",
15633         ((sc->devinfo.mf_info.mf_mode == SINGLE_FUNCTION)     ? "Single"  :
15634          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SD)   ? "MF-SD"   :
15635          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_SI)   ? "MF-SI"   :
15636          (sc->devinfo.mf_info.mf_mode == MULTI_FUNCTION_AFEX) ? "MF-AFEX" :
15637                                                                 "Unknown"));
15638     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "mf_vnics",
15639                     CTLFLAG_RD, &sc->devinfo.mf_info.vnics_per_port, 0,
15640                     "multifunction vnics per port");
15641
15642     snprintf(sc->pci_link_str, sizeof(sc->pci_link_str), "%s x%d",
15643         ((sc->devinfo.pcie_link_speed == 1) ? "2.5GT/s" :
15644          (sc->devinfo.pcie_link_speed == 2) ? "5.0GT/s" :
15645          (sc->devinfo.pcie_link_speed == 4) ? "8.0GT/s" :
15646                                               "???GT/s"),
15647         sc->devinfo.pcie_link_width);
15648
15649     sc->debug = bxe_debug;
15650
15651 #if __FreeBSD_version >= 900000
15652     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15653                       CTLFLAG_RD, sc->devinfo.bc_ver_str, 0,
15654                       "bootcode version");
15655     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15656                       CTLFLAG_RD, sc->fw_ver_str, 0,
15657                       "firmware version");
15658     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15659                       CTLFLAG_RD, sc->mf_mode_str, 0,
15660                       "multifunction mode");
15661     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15662                       CTLFLAG_RD, sc->mac_addr_str, 0,
15663                       "mac address");
15664     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15665                       CTLFLAG_RD, sc->pci_link_str, 0,
15666                       "pci link status");
15667     SYSCTL_ADD_ULONG(ctx, children, OID_AUTO, "debug",
15668                     CTLFLAG_RW, &sc->debug,
15669                     "debug logging mode");
15670 #else
15671     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bc_version",
15672                       CTLFLAG_RD, &sc->devinfo.bc_ver_str, 0,
15673                       "bootcode version");
15674     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "fw_version",
15675                       CTLFLAG_RD, &sc->fw_ver_str, 0,
15676                       "firmware version");
15677     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mf_mode",
15678                       CTLFLAG_RD, &sc->mf_mode_str, 0,
15679                       "multifunction mode");
15680     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "mac_addr",
15681                       CTLFLAG_RD, &sc->mac_addr_str, 0,
15682                       "mac address");
15683     SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pci_link",
15684                       CTLFLAG_RD, &sc->pci_link_str, 0,
15685                       "pci link status");
15686     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "debug",
15687                     CTLFLAG_RW, &sc->debug, 0,
15688                     "debug logging mode");
15689 #endif /* #if __FreeBSD_version >= 900000 */
15690
15691     sc->trigger_grcdump = 0;
15692     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "trigger_grcdump",
15693                    CTLFLAG_RW, &sc->trigger_grcdump, 0,
15694                    "trigger grcdump should be invoked"
15695                    "  before collecting grcdump");
15696
15697     sc->grcdump_started = 0;
15698     sc->grcdump_done = 0;
15699     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "grcdump_done",
15700                    CTLFLAG_RD, &sc->grcdump_done, 0,
15701                    "set by driver when grcdump is done");
15702
15703     sc->rx_budget = bxe_rx_budget;
15704     SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_budget",
15705                     CTLFLAG_RW, &sc->rx_budget, 0,
15706                     "rx processing budget");
15707
15708     SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "state",
15709                     CTLTYPE_UINT | CTLFLAG_RW, sc, 0,
15710                     bxe_sysctl_state, "IU", "dump driver state");
15711
15712     for (i = 0; i < BXE_NUM_ETH_STATS; i++) {
15713         SYSCTL_ADD_PROC(ctx, children, OID_AUTO,
15714                         bxe_eth_stats_arr[i].string,
15715                         CTLTYPE_U64 | CTLFLAG_RD, sc, i,
15716                         bxe_sysctl_eth_stat, "LU",
15717                         bxe_eth_stats_arr[i].string);
15718     }
15719
15720     /* add a new parent node for all queues "dev.bxe.#.queue" */
15721     queue_top = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "queue",
15722                                 CTLFLAG_RD, NULL, "queue");
15723     queue_top_children = SYSCTL_CHILDREN(queue_top);
15724
15725     for (i = 0; i < sc->num_queues; i++) {
15726         /* add a new parent node for a single queue "dev.bxe.#.queue.#" */
15727         snprintf(queue_num_buf, sizeof(queue_num_buf), "%d", i);
15728         queue = SYSCTL_ADD_NODE(ctx, queue_top_children, OID_AUTO,
15729                                 queue_num_buf, CTLFLAG_RD, NULL,
15730                                 "single queue");
15731         queue_children = SYSCTL_CHILDREN(queue);
15732
15733         for (j = 0; j < BXE_NUM_ETH_Q_STATS; j++) {
15734             q_stat = ((i << 16) | j);
15735             SYSCTL_ADD_PROC(ctx, queue_children, OID_AUTO,
15736                             bxe_eth_q_stats_arr[j].string,
15737                             CTLTYPE_U64 | CTLFLAG_RD, sc, q_stat,
15738                             bxe_sysctl_eth_q_stat, "LU",
15739                             bxe_eth_q_stats_arr[j].string);
15740         }
15741     }
15742 }
15743
15744 static int
15745 bxe_alloc_buf_rings(struct bxe_softc *sc)
15746 {
15747 #if __FreeBSD_version >= 901504
15748
15749     int i;
15750     struct bxe_fastpath *fp;
15751
15752     for (i = 0; i < sc->num_queues; i++) {
15753
15754         fp = &sc->fp[i];
15755
15756         fp->tx_br = buf_ring_alloc(BXE_BR_SIZE, M_DEVBUF,
15757                                    M_NOWAIT, &fp->tx_mtx);
15758         if (fp->tx_br == NULL)
15759             return (-1);
15760     }
15761 #endif
15762     return (0);
15763 }
15764
15765 static void
15766 bxe_free_buf_rings(struct bxe_softc *sc)
15767 {
15768 #if __FreeBSD_version >= 901504
15769
15770     int i;
15771     struct bxe_fastpath *fp;
15772
15773     for (i = 0; i < sc->num_queues; i++) {
15774
15775         fp = &sc->fp[i];
15776
15777         if (fp->tx_br) {
15778             buf_ring_free(fp->tx_br, M_DEVBUF);
15779             fp->tx_br = NULL;
15780         }
15781     }
15782
15783 #endif
15784 }
15785
15786 static void
15787 bxe_init_fp_mutexs(struct bxe_softc *sc)
15788 {
15789     int i;
15790     struct bxe_fastpath *fp;
15791
15792     for (i = 0; i < sc->num_queues; i++) {
15793
15794         fp = &sc->fp[i];
15795
15796         snprintf(fp->tx_mtx_name, sizeof(fp->tx_mtx_name),
15797             "bxe%d_fp%d_tx_lock", sc->unit, i);
15798         mtx_init(&fp->tx_mtx, fp->tx_mtx_name, NULL, MTX_DEF);
15799
15800         snprintf(fp->rx_mtx_name, sizeof(fp->rx_mtx_name),
15801             "bxe%d_fp%d_rx_lock", sc->unit, i);
15802         mtx_init(&fp->rx_mtx, fp->rx_mtx_name, NULL, MTX_DEF);
15803     }
15804 }
15805
15806 static void
15807 bxe_destroy_fp_mutexs(struct bxe_softc *sc)
15808 {
15809     int i;
15810     struct bxe_fastpath *fp;
15811
15812     for (i = 0; i < sc->num_queues; i++) {
15813
15814         fp = &sc->fp[i];
15815
15816         if (mtx_initialized(&fp->tx_mtx)) {
15817             mtx_destroy(&fp->tx_mtx);
15818         }
15819
15820         if (mtx_initialized(&fp->rx_mtx)) {
15821             mtx_destroy(&fp->rx_mtx);
15822         }
15823     }
15824 }
15825
15826
15827 /*
15828  * Device attach function.
15829  *
15830  * Allocates device resources, performs secondary chip identification, and
15831  * initializes driver instance variables. This function is called from driver
15832  * load after a successful probe.
15833  *
15834  * Returns:
15835  *   0 = Success, >0 = Failure
15836  */
15837 static int
15838 bxe_attach(device_t dev)
15839 {
15840     struct bxe_softc *sc;
15841
15842     sc = device_get_softc(dev);
15843
15844     BLOGD(sc, DBG_LOAD, "Starting attach...\n");
15845
15846     sc->state = BXE_STATE_CLOSED;
15847
15848     sc->dev  = dev;
15849     sc->unit = device_get_unit(dev);
15850
15851     BLOGD(sc, DBG_LOAD, "softc = %p\n", sc);
15852
15853     sc->pcie_bus    = pci_get_bus(dev);
15854     sc->pcie_device = pci_get_slot(dev);
15855     sc->pcie_func   = pci_get_function(dev);
15856
15857     /* enable bus master capability */
15858     pci_enable_busmaster(dev);
15859
15860     /* get the BARs */
15861     if (bxe_allocate_bars(sc) != 0) {
15862         return (ENXIO);
15863     }
15864
15865     /* initialize the mutexes */
15866     bxe_init_mutexes(sc);
15867
15868     /* prepare the periodic callout */
15869     callout_init(&sc->periodic_callout, 0);
15870
15871     /* prepare the chip taskqueue */
15872     sc->chip_tq_flags = CHIP_TQ_NONE;
15873     snprintf(sc->chip_tq_name, sizeof(sc->chip_tq_name),
15874              "bxe%d_chip_tq", sc->unit);
15875     TASK_INIT(&sc->chip_tq_task, 0, bxe_handle_chip_tq, sc);
15876     sc->chip_tq = taskqueue_create(sc->chip_tq_name, M_NOWAIT,
15877                                    taskqueue_thread_enqueue,
15878                                    &sc->chip_tq);
15879     taskqueue_start_threads(&sc->chip_tq, 1, PWAIT, /* lower priority */
15880                             "%s", sc->chip_tq_name);
15881
15882     /* get device info and set params */
15883     if (bxe_get_device_info(sc) != 0) {
15884         BLOGE(sc, "getting device info\n");
15885         bxe_deallocate_bars(sc);
15886         pci_disable_busmaster(dev);
15887         return (ENXIO);
15888     }
15889
15890     /* get final misc params */
15891     bxe_get_params(sc);
15892
15893     /* set the default MTU (changed via ifconfig) */
15894     sc->mtu = ETHERMTU;
15895
15896     bxe_set_modes_bitmap(sc);
15897
15898     /* XXX
15899      * If in AFEX mode and the function is configured for FCoE
15900      * then bail... no L2 allowed.
15901      */
15902
15903     /* get phy settings from shmem and 'and' against admin settings */
15904     bxe_get_phy_info(sc);
15905
15906     /* initialize the FreeBSD ifnet interface */
15907     if (bxe_init_ifnet(sc) != 0) {
15908         bxe_release_mutexes(sc);
15909         bxe_deallocate_bars(sc);
15910         pci_disable_busmaster(dev);
15911         return (ENXIO);
15912     }
15913
15914     if (bxe_add_cdev(sc) != 0) {
15915         if (sc->ifnet != NULL) {
15916             ether_ifdetach(sc->ifnet);
15917         }
15918         ifmedia_removeall(&sc->ifmedia);
15919         bxe_release_mutexes(sc);
15920         bxe_deallocate_bars(sc);
15921         pci_disable_busmaster(dev);
15922         return (ENXIO);
15923     }
15924
15925     /* allocate device interrupts */
15926     if (bxe_interrupt_alloc(sc) != 0) {
15927         bxe_del_cdev(sc);
15928         if (sc->ifnet != NULL) {
15929             ether_ifdetach(sc->ifnet);
15930         }
15931         ifmedia_removeall(&sc->ifmedia);
15932         bxe_release_mutexes(sc);
15933         bxe_deallocate_bars(sc);
15934         pci_disable_busmaster(dev);
15935         return (ENXIO);
15936     }
15937
15938     bxe_init_fp_mutexs(sc);
15939
15940     if (bxe_alloc_buf_rings(sc) != 0) {
15941         bxe_free_buf_rings(sc);
15942         bxe_interrupt_free(sc);
15943         bxe_del_cdev(sc);
15944         if (sc->ifnet != NULL) {
15945             ether_ifdetach(sc->ifnet);
15946         }
15947         ifmedia_removeall(&sc->ifmedia);
15948         bxe_release_mutexes(sc);
15949         bxe_deallocate_bars(sc);
15950         pci_disable_busmaster(dev);
15951         return (ENXIO);
15952     }
15953
15954     /* allocate ilt */
15955     if (bxe_alloc_ilt_mem(sc) != 0) {
15956         bxe_free_buf_rings(sc);
15957         bxe_interrupt_free(sc);
15958         bxe_del_cdev(sc);
15959         if (sc->ifnet != NULL) {
15960             ether_ifdetach(sc->ifnet);
15961         }
15962         ifmedia_removeall(&sc->ifmedia);
15963         bxe_release_mutexes(sc);
15964         bxe_deallocate_bars(sc);
15965         pci_disable_busmaster(dev);
15966         return (ENXIO);
15967     }
15968
15969     /* allocate the host hardware/software hsi structures */
15970     if (bxe_alloc_hsi_mem(sc) != 0) {
15971         bxe_free_ilt_mem(sc);
15972         bxe_free_buf_rings(sc);
15973         bxe_interrupt_free(sc);
15974         bxe_del_cdev(sc);
15975         if (sc->ifnet != NULL) {
15976             ether_ifdetach(sc->ifnet);
15977         }
15978         ifmedia_removeall(&sc->ifmedia);
15979         bxe_release_mutexes(sc);
15980         bxe_deallocate_bars(sc);
15981         pci_disable_busmaster(dev);
15982         return (ENXIO);
15983     }
15984
15985     /* need to reset chip if UNDI was active */
15986     if (IS_PF(sc) && !BXE_NOMCP(sc)) {
15987         /* init fw_seq */
15988         sc->fw_seq =
15989             (SHMEM_RD(sc, func_mb[SC_FW_MB_IDX(sc)].drv_mb_header) &
15990              DRV_MSG_SEQ_NUMBER_MASK);
15991         BLOGD(sc, DBG_LOAD, "prev unload fw_seq 0x%04x\n", sc->fw_seq);
15992         bxe_prev_unload(sc);
15993     }
15994
15995 #if 1
15996     /* XXX */
15997     bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
15998 #else
15999     if (SHMEM2_HAS(sc, dcbx_lldp_params_offset) &&
16000         SHMEM2_HAS(sc, dcbx_lldp_dcbx_stat_offset) &&
16001         SHMEM2_RD(sc, dcbx_lldp_params_offset) &&
16002         SHMEM2_RD(sc, dcbx_lldp_dcbx_stat_offset)) {
16003         bxe_dcbx_set_state(sc, TRUE, BXE_DCBX_ENABLED_ON_NEG_ON);
16004         bxe_dcbx_init_params(sc);
16005     } else {
16006         bxe_dcbx_set_state(sc, FALSE, BXE_DCBX_ENABLED_OFF);
16007     }
16008 #endif
16009
16010     /* calculate qm_cid_count */
16011     sc->qm_cid_count = bxe_set_qm_cid_count(sc);
16012     BLOGD(sc, DBG_LOAD, "qm_cid_count=%d\n", sc->qm_cid_count);
16013
16014     sc->max_cos = 1;
16015     bxe_init_multi_cos(sc);
16016
16017     bxe_add_sysctls(sc);
16018
16019     return (0);
16020 }
16021
16022 /*
16023  * Device detach function.
16024  *
16025  * Stops the controller, resets the controller, and releases resources.
16026  *
16027  * Returns:
16028  *   0 = Success, >0 = Failure
16029  */
16030 static int
16031 bxe_detach(device_t dev)
16032 {
16033     struct bxe_softc *sc;
16034     struct ifnet *ifp;
16035
16036     sc = device_get_softc(dev);
16037
16038     BLOGD(sc, DBG_LOAD, "Starting detach...\n");
16039
16040     ifp = sc->ifnet;
16041     if (ifp != NULL && ifp->if_vlantrunk != NULL) {
16042         BLOGE(sc, "Cannot detach while VLANs are in use.\n");
16043         return(EBUSY);
16044     }
16045
16046     bxe_del_cdev(sc);
16047
16048     /* stop the periodic callout */
16049     bxe_periodic_stop(sc);
16050
16051     /* stop the chip taskqueue */
16052     atomic_store_rel_long(&sc->chip_tq_flags, CHIP_TQ_NONE);
16053     if (sc->chip_tq) {
16054         taskqueue_drain(sc->chip_tq, &sc->chip_tq_task);
16055         taskqueue_free(sc->chip_tq);
16056         sc->chip_tq = NULL;
16057     }
16058
16059     /* stop and reset the controller if it was open */
16060     if (sc->state != BXE_STATE_CLOSED) {
16061         BXE_CORE_LOCK(sc);
16062         bxe_nic_unload(sc, UNLOAD_CLOSE, TRUE);
16063         sc->state = BXE_STATE_DISABLED;
16064         BXE_CORE_UNLOCK(sc);
16065     }
16066
16067     /* release the network interface */
16068     if (ifp != NULL) {
16069         ether_ifdetach(ifp);
16070     }
16071     ifmedia_removeall(&sc->ifmedia);
16072
16073     /* XXX do the following based on driver state... */
16074
16075     /* free the host hardware/software hsi structures */
16076     bxe_free_hsi_mem(sc);
16077
16078     /* free ilt */
16079     bxe_free_ilt_mem(sc);
16080
16081     bxe_free_buf_rings(sc);
16082
16083     /* release the interrupts */
16084     bxe_interrupt_free(sc);
16085
16086     /* Release the mutexes*/
16087     bxe_destroy_fp_mutexs(sc);
16088     bxe_release_mutexes(sc);
16089
16090
16091     /* Release the PCIe BAR mapped memory */
16092     bxe_deallocate_bars(sc);
16093
16094     /* Release the FreeBSD interface. */
16095     if (sc->ifnet != NULL) {
16096         if_free(sc->ifnet);
16097     }
16098
16099     pci_disable_busmaster(dev);
16100
16101     return (0);
16102 }
16103
16104 /*
16105  * Device shutdown function.
16106  *
16107  * Stops and resets the controller.
16108  *
16109  * Returns:
16110  *   Nothing
16111  */
16112 static int
16113 bxe_shutdown(device_t dev)
16114 {
16115     struct bxe_softc *sc;
16116
16117     sc = device_get_softc(dev);
16118
16119     BLOGD(sc, DBG_LOAD, "Starting shutdown...\n");
16120
16121     /* stop the periodic callout */
16122     bxe_periodic_stop(sc);
16123
16124     BXE_CORE_LOCK(sc);
16125     bxe_nic_unload(sc, UNLOAD_NORMAL, FALSE);
16126     BXE_CORE_UNLOCK(sc);
16127
16128     return (0);
16129 }
16130
16131 void
16132 bxe_igu_ack_sb(struct bxe_softc *sc,
16133                uint8_t          igu_sb_id,
16134                uint8_t          segment,
16135                uint16_t         index,
16136                uint8_t          op,
16137                uint8_t          update)
16138 {
16139     uint32_t igu_addr = sc->igu_base_addr;
16140     igu_addr += (IGU_CMD_INT_ACK_BASE + igu_sb_id)*8;
16141     bxe_igu_ack_sb_gen(sc, igu_sb_id, segment, index, op, update, igu_addr);
16142 }
16143
16144 static void
16145 bxe_igu_clear_sb_gen(struct bxe_softc *sc,
16146                      uint8_t          func,
16147                      uint8_t          idu_sb_id,
16148                      uint8_t          is_pf)
16149 {
16150     uint32_t data, ctl, cnt = 100;
16151     uint32_t igu_addr_data = IGU_REG_COMMAND_REG_32LSB_DATA;
16152     uint32_t igu_addr_ctl = IGU_REG_COMMAND_REG_CTRL;
16153     uint32_t igu_addr_ack = IGU_REG_CSTORM_TYPE_0_SB_CLEANUP + (idu_sb_id/32)*4;
16154     uint32_t sb_bit =  1 << (idu_sb_id%32);
16155     uint32_t func_encode = func | (is_pf ? 1 : 0) << IGU_FID_ENCODE_IS_PF_SHIFT;
16156     uint32_t addr_encode = IGU_CMD_E2_PROD_UPD_BASE + idu_sb_id;
16157
16158     /* Not supported in BC mode */
16159     if (CHIP_INT_MODE_IS_BC(sc)) {
16160         return;
16161     }
16162
16163     data = ((IGU_USE_REGISTER_cstorm_type_0_sb_cleanup <<
16164              IGU_REGULAR_CLEANUP_TYPE_SHIFT) |
16165             IGU_REGULAR_CLEANUP_SET |
16166             IGU_REGULAR_BCLEANUP);
16167
16168     ctl = ((addr_encode << IGU_CTRL_REG_ADDRESS_SHIFT) |
16169            (func_encode << IGU_CTRL_REG_FID_SHIFT) |
16170            (IGU_CTRL_CMD_TYPE_WR << IGU_CTRL_REG_TYPE_SHIFT));
16171
16172     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16173             data, igu_addr_data);
16174     REG_WR(sc, igu_addr_data, data);
16175
16176     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16177                       BUS_SPACE_BARRIER_WRITE);
16178     mb();
16179
16180     BLOGD(sc, DBG_LOAD, "write 0x%08x to IGU(via GRC) addr 0x%x\n",
16181             ctl, igu_addr_ctl);
16182     REG_WR(sc, igu_addr_ctl, ctl);
16183
16184     bus_space_barrier(sc->bar[BAR0].tag, sc->bar[BAR0].handle, 0, 0,
16185                       BUS_SPACE_BARRIER_WRITE);
16186     mb();
16187
16188     /* wait for clean up to finish */
16189     while (!(REG_RD(sc, igu_addr_ack) & sb_bit) && --cnt) {
16190         DELAY(20000);
16191     }
16192
16193     if (!(REG_RD(sc, igu_addr_ack) & sb_bit)) {
16194         BLOGD(sc, DBG_LOAD,
16195               "Unable to finish IGU cleanup: "
16196               "idu_sb_id %d offset %d bit %d (cnt %d)\n",
16197               idu_sb_id, idu_sb_id/32, idu_sb_id%32, cnt);
16198     }
16199 }
16200
16201 static void
16202 bxe_igu_clear_sb(struct bxe_softc *sc,
16203                  uint8_t          idu_sb_id)
16204 {
16205     bxe_igu_clear_sb_gen(sc, SC_FUNC(sc), idu_sb_id, TRUE /*PF*/);
16206 }
16207
16208
16209
16210
16211
16212
16213
16214 /*******************/
16215 /* ECORE CALLBACKS */
16216 /*******************/
16217
16218 static void
16219 bxe_reset_common(struct bxe_softc *sc)
16220 {
16221     uint32_t val = 0x1400;
16222
16223     /* reset_common */
16224     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR), 0xd3ffff7f);
16225
16226     if (CHIP_IS_E3(sc)) {
16227         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16228         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16229     }
16230
16231     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_CLEAR), val);
16232 }
16233
16234 static void
16235 bxe_common_init_phy(struct bxe_softc *sc)
16236 {
16237     uint32_t shmem_base[2];
16238     uint32_t shmem2_base[2];
16239
16240     /* Avoid common init in case MFW supports LFA */
16241     if (SHMEM2_RD(sc, size) >
16242         (uint32_t)offsetof(struct shmem2_region,
16243                            lfa_host_addr[SC_PORT(sc)])) {
16244         return;
16245     }
16246
16247     shmem_base[0]  = sc->devinfo.shmem_base;
16248     shmem2_base[0] = sc->devinfo.shmem2_base;
16249
16250     if (!CHIP_IS_E1x(sc)) {
16251         shmem_base[1]  = SHMEM2_RD(sc, other_shmem_base_addr);
16252         shmem2_base[1] = SHMEM2_RD(sc, other_shmem2_base_addr);
16253     }
16254
16255     bxe_acquire_phy_lock(sc);
16256     elink_common_init_phy(sc, shmem_base, shmem2_base,
16257                           sc->devinfo.chip_id, 0);
16258     bxe_release_phy_lock(sc);
16259 }
16260
16261 static void
16262 bxe_pf_disable(struct bxe_softc *sc)
16263 {
16264     uint32_t val = REG_RD(sc, IGU_REG_PF_CONFIGURATION);
16265
16266     val &= ~IGU_PF_CONF_FUNC_EN;
16267
16268     REG_WR(sc, IGU_REG_PF_CONFIGURATION, val);
16269     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16270     REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 0);
16271 }
16272
16273 static void
16274 bxe_init_pxp(struct bxe_softc *sc)
16275 {
16276     uint16_t devctl;
16277     int r_order, w_order;
16278
16279     devctl = bxe_pcie_capability_read(sc, PCIR_EXPRESS_DEVICE_CTL, 2);
16280
16281     BLOGD(sc, DBG_LOAD, "read 0x%08x from devctl\n", devctl);
16282
16283     w_order = ((devctl & PCIM_EXP_CTL_MAX_PAYLOAD) >> 5);
16284
16285     if (sc->mrrs == -1) {
16286         r_order = ((devctl & PCIM_EXP_CTL_MAX_READ_REQUEST) >> 12);
16287     } else {
16288         BLOGD(sc, DBG_LOAD, "forcing read order to %d\n", sc->mrrs);
16289         r_order = sc->mrrs;
16290     }
16291
16292     ecore_init_pxp_arb(sc, r_order, w_order);
16293 }
16294
16295 static uint32_t
16296 bxe_get_pretend_reg(struct bxe_softc *sc)
16297 {
16298     uint32_t base = PXP2_REG_PGL_PRETEND_FUNC_F0;
16299     uint32_t stride = (PXP2_REG_PGL_PRETEND_FUNC_F1 - base);
16300     return (base + (SC_ABS_FUNC(sc)) * stride);
16301 }
16302
16303 /*
16304  * Called only on E1H or E2.
16305  * When pretending to be PF, the pretend value is the function number 0..7.
16306  * When pretending to be VF, the pretend val is the PF-num:VF-valid:ABS-VFID
16307  * combination.
16308  */
16309 static int
16310 bxe_pretend_func(struct bxe_softc *sc,
16311                  uint16_t         pretend_func_val)
16312 {
16313     uint32_t pretend_reg;
16314
16315     if (CHIP_IS_E1H(sc) && (pretend_func_val > E1H_FUNC_MAX)) {
16316         return (-1);
16317     }
16318
16319     /* get my own pretend register */
16320     pretend_reg = bxe_get_pretend_reg(sc);
16321     REG_WR(sc, pretend_reg, pretend_func_val);
16322     REG_RD(sc, pretend_reg);
16323     return (0);
16324 }
16325
16326 static void
16327 bxe_iov_init_dmae(struct bxe_softc *sc)
16328 {
16329     return;
16330 }
16331
16332 static void
16333 bxe_iov_init_dq(struct bxe_softc *sc)
16334 {
16335     return;
16336 }
16337
16338 /* send a NIG loopback debug packet */
16339 static void
16340 bxe_lb_pckt(struct bxe_softc *sc)
16341 {
16342     uint32_t wb_write[3];
16343
16344     /* Ethernet source and destination addresses */
16345     wb_write[0] = 0x55555555;
16346     wb_write[1] = 0x55555555;
16347     wb_write[2] = 0x20;     /* SOP */
16348     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16349
16350     /* NON-IP protocol */
16351     wb_write[0] = 0x09000000;
16352     wb_write[1] = 0x55555555;
16353     wb_write[2] = 0x10;     /* EOP, eop_bvalid = 0 */
16354     REG_WR_DMAE(sc, NIG_REG_DEBUG_PACKET_LB, wb_write, 3);
16355 }
16356
16357 /*
16358  * Some of the internal memories are not directly readable from the driver.
16359  * To test them we send debug packets.
16360  */
16361 static int
16362 bxe_int_mem_test(struct bxe_softc *sc)
16363 {
16364     int factor;
16365     int count, i;
16366     uint32_t val = 0;
16367
16368     if (CHIP_REV_IS_FPGA(sc)) {
16369         factor = 120;
16370     } else if (CHIP_REV_IS_EMUL(sc)) {
16371         factor = 200;
16372     } else {
16373         factor = 1;
16374     }
16375
16376     /* disable inputs of parser neighbor blocks */
16377     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16378     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16379     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16380     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16381
16382     /*  write 0 to parser credits for CFC search request */
16383     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16384
16385     /* send Ethernet packet */
16386     bxe_lb_pckt(sc);
16387
16388     /* TODO do i reset NIG statistic? */
16389     /* Wait until NIG register shows 1 packet of size 0x10 */
16390     count = 1000 * factor;
16391     while (count) {
16392         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16393         val = *BXE_SP(sc, wb_data[0]);
16394         if (val == 0x10) {
16395             break;
16396         }
16397
16398         DELAY(10000);
16399         count--;
16400     }
16401
16402     if (val != 0x10) {
16403         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16404         return (-1);
16405     }
16406
16407     /* wait until PRS register shows 1 packet */
16408     count = (1000 * factor);
16409     while (count) {
16410         val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16411         if (val == 1) {
16412             break;
16413         }
16414
16415         DELAY(10000);
16416         count--;
16417     }
16418
16419     if (val != 0x1) {
16420         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16421         return (-2);
16422     }
16423
16424     /* Reset and init BRB, PRS */
16425     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16426     DELAY(50000);
16427     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16428     DELAY(50000);
16429     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16430     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16431
16432     /* Disable inputs of parser neighbor blocks */
16433     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x0);
16434     REG_WR(sc, TCM_REG_PRS_IFEN, 0x0);
16435     REG_WR(sc, CFC_REG_DEBUG0, 0x1);
16436     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x0);
16437
16438     /* Write 0 to parser credits for CFC search request */
16439     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x0);
16440
16441     /* send 10 Ethernet packets */
16442     for (i = 0; i < 10; i++) {
16443         bxe_lb_pckt(sc);
16444     }
16445
16446     /* Wait until NIG register shows 10+1 packets of size 11*0x10 = 0xb0 */
16447     count = (1000 * factor);
16448     while (count) {
16449         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
16450         val = *BXE_SP(sc, wb_data[0]);
16451         if (val == 0xb0) {
16452             break;
16453         }
16454
16455         DELAY(10000);
16456         count--;
16457     }
16458
16459     if (val != 0xb0) {
16460         BLOGE(sc, "NIG timeout val=0x%x\n", val);
16461         return (-3);
16462     }
16463
16464     /* Wait until PRS register shows 2 packets */
16465     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16466     if (val != 2) {
16467         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16468     }
16469
16470     /* Write 1 to parser credits for CFC search request */
16471     REG_WR(sc, PRS_REG_CFC_SEARCH_INITIAL_CREDIT, 0x1);
16472
16473     /* Wait until PRS register shows 3 packets */
16474     DELAY(10000 * factor);
16475
16476     /* Wait until NIG register shows 1 packet of size 0x10 */
16477     val = REG_RD(sc, PRS_REG_NUM_OF_PACKETS);
16478     if (val != 3) {
16479         BLOGE(sc, "PRS timeout val=0x%x\n", val);
16480     }
16481
16482     /* clear NIG EOP FIFO */
16483     for (i = 0; i < 11; i++) {
16484         REG_RD(sc, NIG_REG_INGRESS_EOP_LB_FIFO);
16485     }
16486
16487     val = REG_RD(sc, NIG_REG_INGRESS_EOP_LB_EMPTY);
16488     if (val != 1) {
16489         BLOGE(sc, "clear of NIG failed val=0x%x\n", val);
16490         return (-4);
16491     }
16492
16493     /* Reset and init BRB, PRS, NIG */
16494     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR, 0x03);
16495     DELAY(50000);
16496     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET, 0x03);
16497     DELAY(50000);
16498     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16499     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16500     if (!CNIC_SUPPORT(sc)) {
16501         /* set NIC mode */
16502         REG_WR(sc, PRS_REG_NIC_MODE, 1);
16503     }
16504
16505     /* Enable inputs of parser neighbor blocks */
16506     REG_WR(sc, TSDM_REG_ENABLE_IN1, 0x7fffffff);
16507     REG_WR(sc, TCM_REG_PRS_IFEN, 0x1);
16508     REG_WR(sc, CFC_REG_DEBUG0, 0x0);
16509     REG_WR(sc, NIG_REG_PRS_REQ_IN_EN, 0x1);
16510
16511     return (0);
16512 }
16513
16514 static void
16515 bxe_setup_fan_failure_detection(struct bxe_softc *sc)
16516 {
16517     int is_required;
16518     uint32_t val;
16519     int port;
16520
16521     is_required = 0;
16522     val = (SHMEM_RD(sc, dev_info.shared_hw_config.config2) &
16523            SHARED_HW_CFG_FAN_FAILURE_MASK);
16524
16525     if (val == SHARED_HW_CFG_FAN_FAILURE_ENABLED) {
16526         is_required = 1;
16527     }
16528     /*
16529      * The fan failure mechanism is usually related to the PHY type since
16530      * the power consumption of the board is affected by the PHY. Currently,
16531      * fan is required for most designs with SFX7101, BCM8727 and BCM8481.
16532      */
16533     else if (val == SHARED_HW_CFG_FAN_FAILURE_PHY_TYPE) {
16534         for (port = PORT_0; port < PORT_MAX; port++) {
16535             is_required |= elink_fan_failure_det_req(sc,
16536                                                      sc->devinfo.shmem_base,
16537                                                      sc->devinfo.shmem2_base,
16538                                                      port);
16539         }
16540     }
16541
16542     BLOGD(sc, DBG_LOAD, "fan detection setting: %d\n", is_required);
16543
16544     if (is_required == 0) {
16545         return;
16546     }
16547
16548     /* Fan failure is indicated by SPIO 5 */
16549     bxe_set_spio(sc, MISC_SPIO_SPIO5, MISC_SPIO_INPUT_HI_Z);
16550
16551     /* set to active low mode */
16552     val = REG_RD(sc, MISC_REG_SPIO_INT);
16553     val |= (MISC_SPIO_SPIO5 << MISC_SPIO_INT_OLD_SET_POS);
16554     REG_WR(sc, MISC_REG_SPIO_INT, val);
16555
16556     /* enable interrupt to signal the IGU */
16557     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
16558     val |= MISC_SPIO_SPIO5;
16559     REG_WR(sc, MISC_REG_SPIO_EVENT_EN, val);
16560 }
16561
16562 static void
16563 bxe_enable_blocks_attention(struct bxe_softc *sc)
16564 {
16565     uint32_t val;
16566
16567     REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16568     if (!CHIP_IS_E1x(sc)) {
16569         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0x40);
16570     } else {
16571         REG_WR(sc, PXP_REG_PXP_INT_MASK_1, 0);
16572     }
16573     REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16574     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
16575     /*
16576      * mask read length error interrupts in brb for parser
16577      * (parsing unit and 'checksum and crc' unit)
16578      * these errors are legal (PU reads fixed length and CAC can cause
16579      * read length error on truncated packets)
16580      */
16581     REG_WR(sc, BRB1_REG_BRB1_INT_MASK, 0xFC00);
16582     REG_WR(sc, QM_REG_QM_INT_MASK, 0);
16583     REG_WR(sc, TM_REG_TM_INT_MASK, 0);
16584     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_0, 0);
16585     REG_WR(sc, XSDM_REG_XSDM_INT_MASK_1, 0);
16586     REG_WR(sc, XCM_REG_XCM_INT_MASK, 0);
16587 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_0, 0); */
16588 /*      REG_WR(sc, XSEM_REG_XSEM_INT_MASK_1, 0); */
16589     REG_WR(sc, USDM_REG_USDM_INT_MASK_0, 0);
16590     REG_WR(sc, USDM_REG_USDM_INT_MASK_1, 0);
16591     REG_WR(sc, UCM_REG_UCM_INT_MASK, 0);
16592 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_0, 0); */
16593 /*      REG_WR(sc, USEM_REG_USEM_INT_MASK_1, 0); */
16594     REG_WR(sc, GRCBASE_UPB + PB_REG_PB_INT_MASK, 0);
16595     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_0, 0);
16596     REG_WR(sc, CSDM_REG_CSDM_INT_MASK_1, 0);
16597     REG_WR(sc, CCM_REG_CCM_INT_MASK, 0);
16598 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_0, 0); */
16599 /*      REG_WR(sc, CSEM_REG_CSEM_INT_MASK_1, 0); */
16600
16601     val = (PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_AFT |
16602            PXP2_PXP2_INT_MASK_0_REG_PGL_CPL_OF |
16603            PXP2_PXP2_INT_MASK_0_REG_PGL_PCIE_ATTN);
16604     if (!CHIP_IS_E1x(sc)) {
16605         val |= (PXP2_PXP2_INT_MASK_0_REG_PGL_READ_BLOCKED |
16606                 PXP2_PXP2_INT_MASK_0_REG_PGL_WRITE_BLOCKED);
16607     }
16608     REG_WR(sc, PXP2_REG_PXP2_INT_MASK_0, val);
16609
16610     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_0, 0);
16611     REG_WR(sc, TSDM_REG_TSDM_INT_MASK_1, 0);
16612     REG_WR(sc, TCM_REG_TCM_INT_MASK, 0);
16613 /*      REG_WR(sc, TSEM_REG_TSEM_INT_MASK_0, 0); */
16614
16615     if (!CHIP_IS_E1x(sc)) {
16616         /* enable VFC attentions: bits 11 and 12, bits 31:13 reserved */
16617         REG_WR(sc, TSEM_REG_TSEM_INT_MASK_1, 0x07ff);
16618     }
16619
16620     REG_WR(sc, CDU_REG_CDU_INT_MASK, 0);
16621     REG_WR(sc, DMAE_REG_DMAE_INT_MASK, 0);
16622 /*      REG_WR(sc, MISC_REG_MISC_INT_MASK, 0); */
16623     REG_WR(sc, PBF_REG_PBF_INT_MASK, 0x18);     /* bit 3,4 masked */
16624 }
16625
16626 /**
16627  * bxe_init_hw_common - initialize the HW at the COMMON phase.
16628  *
16629  * @sc:     driver handle
16630  */
16631 static int
16632 bxe_init_hw_common(struct bxe_softc *sc)
16633 {
16634     uint8_t abs_func_id;
16635     uint32_t val;
16636
16637     BLOGD(sc, DBG_LOAD, "starting common init for func %d\n",
16638           SC_ABS_FUNC(sc));
16639
16640     /*
16641      * take the RESET lock to protect undi_unload flow from accessing
16642      * registers while we are resetting the chip
16643      */
16644     bxe_acquire_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16645
16646     bxe_reset_common(sc);
16647
16648     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET), 0xffffffff);
16649
16650     val = 0xfffc;
16651     if (CHIP_IS_E3(sc)) {
16652         val |= MISC_REGISTERS_RESET_REG_2_MSTAT0;
16653         val |= MISC_REGISTERS_RESET_REG_2_MSTAT1;
16654     }
16655
16656     REG_WR(sc, (GRCBASE_MISC + MISC_REGISTERS_RESET_REG_2_SET), val);
16657
16658     bxe_release_hw_lock(sc, HW_LOCK_RESOURCE_RESET);
16659
16660     ecore_init_block(sc, BLOCK_MISC, PHASE_COMMON);
16661     BLOGD(sc, DBG_LOAD, "after misc block init\n");
16662
16663     if (!CHIP_IS_E1x(sc)) {
16664         /*
16665          * 4-port mode or 2-port mode we need to turn off master-enable for
16666          * everyone. After that we turn it back on for self. So, we disregard
16667          * multi-function, and always disable all functions on the given path,
16668          * this means 0,2,4,6 for path 0 and 1,3,5,7 for path 1
16669          */
16670         for (abs_func_id = SC_PATH(sc);
16671              abs_func_id < (E2_FUNC_MAX * 2);
16672              abs_func_id += 2) {
16673             if (abs_func_id == SC_ABS_FUNC(sc)) {
16674                 REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
16675                 continue;
16676             }
16677
16678             bxe_pretend_func(sc, abs_func_id);
16679
16680             /* clear pf enable */
16681             bxe_pf_disable(sc);
16682
16683             bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16684         }
16685     }
16686
16687     BLOGD(sc, DBG_LOAD, "after pf disable\n");
16688
16689     ecore_init_block(sc, BLOCK_PXP, PHASE_COMMON);
16690
16691     if (CHIP_IS_E1(sc)) {
16692         /*
16693          * enable HW interrupt from PXP on USDM overflow
16694          * bit 16 on INT_MASK_0
16695          */
16696         REG_WR(sc, PXP_REG_PXP_INT_MASK_0, 0);
16697     }
16698
16699     ecore_init_block(sc, BLOCK_PXP2, PHASE_COMMON);
16700     bxe_init_pxp(sc);
16701
16702 #ifdef __BIG_ENDIAN
16703     REG_WR(sc, PXP2_REG_RQ_QM_ENDIAN_M, 1);
16704     REG_WR(sc, PXP2_REG_RQ_TM_ENDIAN_M, 1);
16705     REG_WR(sc, PXP2_REG_RQ_SRC_ENDIAN_M, 1);
16706     REG_WR(sc, PXP2_REG_RQ_CDU_ENDIAN_M, 1);
16707     REG_WR(sc, PXP2_REG_RQ_DBG_ENDIAN_M, 1);
16708     /* make sure this value is 0 */
16709     REG_WR(sc, PXP2_REG_RQ_HC_ENDIAN_M, 0);
16710
16711     //REG_WR(sc, PXP2_REG_RD_PBF_SWAP_MODE, 1);
16712     REG_WR(sc, PXP2_REG_RD_QM_SWAP_MODE, 1);
16713     REG_WR(sc, PXP2_REG_RD_TM_SWAP_MODE, 1);
16714     REG_WR(sc, PXP2_REG_RD_SRC_SWAP_MODE, 1);
16715     REG_WR(sc, PXP2_REG_RD_CDURD_SWAP_MODE, 1);
16716 #endif
16717
16718     ecore_ilt_init_page_size(sc, INITOP_SET);
16719
16720     if (CHIP_REV_IS_FPGA(sc) && CHIP_IS_E1H(sc)) {
16721         REG_WR(sc, PXP2_REG_PGL_TAGS_LIMIT, 0x1);
16722     }
16723
16724     /* let the HW do it's magic... */
16725     DELAY(100000);
16726
16727     /* finish PXP init */
16728     val = REG_RD(sc, PXP2_REG_RQ_CFG_DONE);
16729     if (val != 1) {
16730         BLOGE(sc, "PXP2 CFG failed PXP2_REG_RQ_CFG_DONE val = 0x%x\n",
16731             val);
16732         return (-1);
16733     }
16734     val = REG_RD(sc, PXP2_REG_RD_INIT_DONE);
16735     if (val != 1) {
16736         BLOGE(sc, "PXP2 RD_INIT failed val = 0x%x\n", val);
16737         return (-1);
16738     }
16739
16740     BLOGD(sc, DBG_LOAD, "after pxp init\n");
16741
16742     /*
16743      * Timer bug workaround for E2 only. We need to set the entire ILT to have
16744      * entries with value "0" and valid bit on. This needs to be done by the
16745      * first PF that is loaded in a path (i.e. common phase)
16746      */
16747     if (!CHIP_IS_E1x(sc)) {
16748 /*
16749  * In E2 there is a bug in the timers block that can cause function 6 / 7
16750  * (i.e. vnic3) to start even if it is marked as "scan-off".
16751  * This occurs when a different function (func2,3) is being marked
16752  * as "scan-off". Real-life scenario for example: if a driver is being
16753  * load-unloaded while func6,7 are down. This will cause the timer to access
16754  * the ilt, translate to a logical address and send a request to read/write.
16755  * Since the ilt for the function that is down is not valid, this will cause
16756  * a translation error which is unrecoverable.
16757  * The Workaround is intended to make sure that when this happens nothing
16758  * fatal will occur. The workaround:
16759  *  1.  First PF driver which loads on a path will:
16760  *      a.  After taking the chip out of reset, by using pretend,
16761  *          it will write "0" to the following registers of
16762  *          the other vnics.
16763  *          REG_WR(pdev, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 0);
16764  *          REG_WR(pdev, CFC_REG_WEAK_ENABLE_PF,0);
16765  *          REG_WR(pdev, CFC_REG_STRONG_ENABLE_PF,0);
16766  *          And for itself it will write '1' to
16767  *          PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER to enable
16768  *          dmae-operations (writing to pram for example.)
16769  *          note: can be done for only function 6,7 but cleaner this
16770  *            way.
16771  *      b.  Write zero+valid to the entire ILT.
16772  *      c.  Init the first_timers_ilt_entry, last_timers_ilt_entry of
16773  *          VNIC3 (of that port). The range allocated will be the
16774  *          entire ILT. This is needed to prevent  ILT range error.
16775  *  2.  Any PF driver load flow:
16776  *      a.  ILT update with the physical addresses of the allocated
16777  *          logical pages.
16778  *      b.  Wait 20msec. - note that this timeout is needed to make
16779  *          sure there are no requests in one of the PXP internal
16780  *          queues with "old" ILT addresses.
16781  *      c.  PF enable in the PGLC.
16782  *      d.  Clear the was_error of the PF in the PGLC. (could have
16783  *          occurred while driver was down)
16784  *      e.  PF enable in the CFC (WEAK + STRONG)
16785  *      f.  Timers scan enable
16786  *  3.  PF driver unload flow:
16787  *      a.  Clear the Timers scan_en.
16788  *      b.  Polling for scan_on=0 for that PF.
16789  *      c.  Clear the PF enable bit in the PXP.
16790  *      d.  Clear the PF enable in the CFC (WEAK + STRONG)
16791  *      e.  Write zero+valid to all ILT entries (The valid bit must
16792  *          stay set)
16793  *      f.  If this is VNIC 3 of a port then also init
16794  *          first_timers_ilt_entry to zero and last_timers_ilt_entry
16795  *          to the last enrty in the ILT.
16796  *
16797  *      Notes:
16798  *      Currently the PF error in the PGLC is non recoverable.
16799  *      In the future the there will be a recovery routine for this error.
16800  *      Currently attention is masked.
16801  *      Having an MCP lock on the load/unload process does not guarantee that
16802  *      there is no Timer disable during Func6/7 enable. This is because the
16803  *      Timers scan is currently being cleared by the MCP on FLR.
16804  *      Step 2.d can be done only for PF6/7 and the driver can also check if
16805  *      there is error before clearing it. But the flow above is simpler and
16806  *      more general.
16807  *      All ILT entries are written by zero+valid and not just PF6/7
16808  *      ILT entries since in the future the ILT entries allocation for
16809  *      PF-s might be dynamic.
16810  */
16811         struct ilt_client_info ilt_cli;
16812         struct ecore_ilt ilt;
16813
16814         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
16815         memset(&ilt, 0, sizeof(struct ecore_ilt));
16816
16817         /* initialize dummy TM client */
16818         ilt_cli.start      = 0;
16819         ilt_cli.end        = ILT_NUM_PAGE_ENTRIES - 1;
16820         ilt_cli.client_num = ILT_CLIENT_TM;
16821
16822         /*
16823          * Step 1: set zeroes to all ilt page entries with valid bit on
16824          * Step 2: set the timers first/last ilt entry to point
16825          * to the entire range to prevent ILT range error for 3rd/4th
16826          * vnic (this code assumes existence of the vnic)
16827          *
16828          * both steps performed by call to ecore_ilt_client_init_op()
16829          * with dummy TM client
16830          *
16831          * we must use pretend since PXP2_REG_RQ_##blk##_FIRST_ILT
16832          * and his brother are split registers
16833          */
16834
16835         bxe_pretend_func(sc, (SC_PATH(sc) + 6));
16836         ecore_ilt_client_init_op_ilt(sc, &ilt, &ilt_cli, INITOP_CLEAR);
16837         bxe_pretend_func(sc, SC_ABS_FUNC(sc));
16838
16839         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN, BXE_PXP_DRAM_ALIGN);
16840         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_RD, BXE_PXP_DRAM_ALIGN);
16841         REG_WR(sc, PXP2_REG_RQ_DRAM_ALIGN_SEL, 1);
16842     }
16843
16844     REG_WR(sc, PXP2_REG_RQ_DISABLE_INPUTS, 0);
16845     REG_WR(sc, PXP2_REG_RD_DISABLE_INPUTS, 0);
16846
16847     if (!CHIP_IS_E1x(sc)) {
16848         int factor = CHIP_REV_IS_EMUL(sc) ? 1000 :
16849                      (CHIP_REV_IS_FPGA(sc) ? 400 : 0);
16850
16851         ecore_init_block(sc, BLOCK_PGLUE_B, PHASE_COMMON);
16852         ecore_init_block(sc, BLOCK_ATC, PHASE_COMMON);
16853
16854         /* let the HW do it's magic... */
16855         do {
16856             DELAY(200000);
16857             val = REG_RD(sc, ATC_REG_ATC_INIT_DONE);
16858         } while (factor-- && (val != 1));
16859
16860         if (val != 1) {
16861             BLOGE(sc, "ATC_INIT failed val = 0x%x\n", val);
16862             return (-1);
16863         }
16864     }
16865
16866     BLOGD(sc, DBG_LOAD, "after pglue and atc init\n");
16867
16868     ecore_init_block(sc, BLOCK_DMAE, PHASE_COMMON);
16869
16870     bxe_iov_init_dmae(sc);
16871
16872     /* clean the DMAE memory */
16873     sc->dmae_ready = 1;
16874     ecore_init_fill(sc, TSEM_REG_PRAM, 0, 8, 1);
16875
16876     ecore_init_block(sc, BLOCK_TCM, PHASE_COMMON);
16877
16878     ecore_init_block(sc, BLOCK_UCM, PHASE_COMMON);
16879
16880     ecore_init_block(sc, BLOCK_CCM, PHASE_COMMON);
16881
16882     ecore_init_block(sc, BLOCK_XCM, PHASE_COMMON);
16883
16884     bxe_read_dmae(sc, XSEM_REG_PASSIVE_BUFFER, 3);
16885     bxe_read_dmae(sc, CSEM_REG_PASSIVE_BUFFER, 3);
16886     bxe_read_dmae(sc, TSEM_REG_PASSIVE_BUFFER, 3);
16887     bxe_read_dmae(sc, USEM_REG_PASSIVE_BUFFER, 3);
16888
16889     ecore_init_block(sc, BLOCK_QM, PHASE_COMMON);
16890
16891     /* QM queues pointers table */
16892     ecore_qm_init_ptr_table(sc, sc->qm_cid_count, INITOP_SET);
16893
16894     /* soft reset pulse */
16895     REG_WR(sc, QM_REG_SOFT_RESET, 1);
16896     REG_WR(sc, QM_REG_SOFT_RESET, 0);
16897
16898     if (CNIC_SUPPORT(sc))
16899         ecore_init_block(sc, BLOCK_TM, PHASE_COMMON);
16900
16901     ecore_init_block(sc, BLOCK_DORQ, PHASE_COMMON);
16902     REG_WR(sc, DORQ_REG_DPM_CID_OFST, BXE_DB_SHIFT);
16903     if (!CHIP_REV_IS_SLOW(sc)) {
16904         /* enable hw interrupt from doorbell Q */
16905         REG_WR(sc, DORQ_REG_DORQ_INT_MASK, 0);
16906     }
16907
16908     ecore_init_block(sc, BLOCK_BRB1, PHASE_COMMON);
16909
16910     ecore_init_block(sc, BLOCK_PRS, PHASE_COMMON);
16911     REG_WR(sc, PRS_REG_A_PRSU_20, 0xf);
16912
16913     if (!CHIP_IS_E1(sc)) {
16914         REG_WR(sc, PRS_REG_E1HOV_MODE, sc->devinfo.mf_info.path_has_ovlan);
16915     }
16916
16917     if (!CHIP_IS_E1x(sc) && !CHIP_IS_E3B0(sc)) {
16918         if (IS_MF_AFEX(sc)) {
16919             /*
16920              * configure that AFEX and VLAN headers must be
16921              * received in AFEX mode
16922              */
16923             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC, 0xE);
16924             REG_WR(sc, PRS_REG_MUST_HAVE_HDRS, 0xA);
16925             REG_WR(sc, PRS_REG_HDRS_AFTER_TAG_0, 0x6);
16926             REG_WR(sc, PRS_REG_TAG_ETHERTYPE_0, 0x8926);
16927             REG_WR(sc, PRS_REG_TAG_LEN_0, 0x4);
16928         } else {
16929             /*
16930              * Bit-map indicating which L2 hdrs may appear
16931              * after the basic Ethernet header
16932              */
16933             REG_WR(sc, PRS_REG_HDRS_AFTER_BASIC,
16934                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16935         }
16936     }
16937
16938     ecore_init_block(sc, BLOCK_TSDM, PHASE_COMMON);
16939     ecore_init_block(sc, BLOCK_CSDM, PHASE_COMMON);
16940     ecore_init_block(sc, BLOCK_USDM, PHASE_COMMON);
16941     ecore_init_block(sc, BLOCK_XSDM, PHASE_COMMON);
16942
16943     if (!CHIP_IS_E1x(sc)) {
16944         /* reset VFC memories */
16945         REG_WR(sc, TSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16946                VFC_MEMORIES_RST_REG_CAM_RST |
16947                VFC_MEMORIES_RST_REG_RAM_RST);
16948         REG_WR(sc, XSEM_REG_FAST_MEMORY + VFC_REG_MEMORIES_RST,
16949                VFC_MEMORIES_RST_REG_CAM_RST |
16950                VFC_MEMORIES_RST_REG_RAM_RST);
16951
16952         DELAY(20000);
16953     }
16954
16955     ecore_init_block(sc, BLOCK_TSEM, PHASE_COMMON);
16956     ecore_init_block(sc, BLOCK_USEM, PHASE_COMMON);
16957     ecore_init_block(sc, BLOCK_CSEM, PHASE_COMMON);
16958     ecore_init_block(sc, BLOCK_XSEM, PHASE_COMMON);
16959
16960     /* sync semi rtc */
16961     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_CLEAR,
16962            0x80000000);
16963     REG_WR(sc, GRCBASE_MISC + MISC_REGISTERS_RESET_REG_1_SET,
16964            0x80000000);
16965
16966     ecore_init_block(sc, BLOCK_UPB, PHASE_COMMON);
16967     ecore_init_block(sc, BLOCK_XPB, PHASE_COMMON);
16968     ecore_init_block(sc, BLOCK_PBF, PHASE_COMMON);
16969
16970     if (!CHIP_IS_E1x(sc)) {
16971         if (IS_MF_AFEX(sc)) {
16972             /*
16973              * configure that AFEX and VLAN headers must be
16974              * sent in AFEX mode
16975              */
16976             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC, 0xE);
16977             REG_WR(sc, PBF_REG_MUST_HAVE_HDRS, 0xA);
16978             REG_WR(sc, PBF_REG_HDRS_AFTER_TAG_0, 0x6);
16979             REG_WR(sc, PBF_REG_TAG_ETHERTYPE_0, 0x8926);
16980             REG_WR(sc, PBF_REG_TAG_LEN_0, 0x4);
16981         } else {
16982             REG_WR(sc, PBF_REG_HDRS_AFTER_BASIC,
16983                    sc->devinfo.mf_info.path_has_ovlan ? 7 : 6);
16984         }
16985     }
16986
16987     REG_WR(sc, SRC_REG_SOFT_RST, 1);
16988
16989     ecore_init_block(sc, BLOCK_SRC, PHASE_COMMON);
16990
16991     if (CNIC_SUPPORT(sc)) {
16992         REG_WR(sc, SRC_REG_KEYSEARCH_0, 0x63285672);
16993         REG_WR(sc, SRC_REG_KEYSEARCH_1, 0x24b8f2cc);
16994         REG_WR(sc, SRC_REG_KEYSEARCH_2, 0x223aef9b);
16995         REG_WR(sc, SRC_REG_KEYSEARCH_3, 0x26001e3a);
16996         REG_WR(sc, SRC_REG_KEYSEARCH_4, 0x7ae91116);
16997         REG_WR(sc, SRC_REG_KEYSEARCH_5, 0x5ce5230b);
16998         REG_WR(sc, SRC_REG_KEYSEARCH_6, 0x298d8adf);
16999         REG_WR(sc, SRC_REG_KEYSEARCH_7, 0x6eb0ff09);
17000         REG_WR(sc, SRC_REG_KEYSEARCH_8, 0x1830f82f);
17001         REG_WR(sc, SRC_REG_KEYSEARCH_9, 0x01e46be7);
17002     }
17003     REG_WR(sc, SRC_REG_SOFT_RST, 0);
17004
17005     if (sizeof(union cdu_context) != 1024) {
17006         /* we currently assume that a context is 1024 bytes */
17007         BLOGE(sc, "please adjust the size of cdu_context(%ld)\n",
17008               (long)sizeof(union cdu_context));
17009     }
17010
17011     ecore_init_block(sc, BLOCK_CDU, PHASE_COMMON);
17012     val = (4 << 24) + (0 << 12) + 1024;
17013     REG_WR(sc, CDU_REG_CDU_GLOBAL_PARAMS, val);
17014
17015     ecore_init_block(sc, BLOCK_CFC, PHASE_COMMON);
17016
17017     REG_WR(sc, CFC_REG_INIT_REG, 0x7FF);
17018     /* enable context validation interrupt from CFC */
17019     REG_WR(sc, CFC_REG_CFC_INT_MASK, 0);
17020
17021     /* set the thresholds to prevent CFC/CDU race */
17022     REG_WR(sc, CFC_REG_DEBUG0, 0x20020000);
17023     ecore_init_block(sc, BLOCK_HC, PHASE_COMMON);
17024
17025     if (!CHIP_IS_E1x(sc) && BXE_NOMCP(sc)) {
17026         REG_WR(sc, IGU_REG_RESET_MEMORIES, 0x36);
17027     }
17028
17029     ecore_init_block(sc, BLOCK_IGU, PHASE_COMMON);
17030     ecore_init_block(sc, BLOCK_MISC_AEU, PHASE_COMMON);
17031
17032     /* Reset PCIE errors for debug */
17033     REG_WR(sc, 0x2814, 0xffffffff);
17034     REG_WR(sc, 0x3820, 0xffffffff);
17035
17036     if (!CHIP_IS_E1x(sc)) {
17037         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_CONTROL_5,
17038                (PXPCS_TL_CONTROL_5_ERR_UNSPPORT1 |
17039                 PXPCS_TL_CONTROL_5_ERR_UNSPPORT));
17040         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC345_STAT,
17041                (PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT4 |
17042                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT3 |
17043                 PXPCS_TL_FUNC345_STAT_ERR_UNSPPORT2));
17044         REG_WR(sc, PCICFG_OFFSET + PXPCS_TL_FUNC678_STAT,
17045                (PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT7 |
17046                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT6 |
17047                 PXPCS_TL_FUNC678_STAT_ERR_UNSPPORT5));
17048     }
17049
17050     ecore_init_block(sc, BLOCK_NIG, PHASE_COMMON);
17051
17052     if (!CHIP_IS_E1(sc)) {
17053         /* in E3 this done in per-port section */
17054         if (!CHIP_IS_E3(sc))
17055             REG_WR(sc, NIG_REG_LLH_MF_MODE, IS_MF(sc));
17056     }
17057
17058     if (CHIP_IS_E1H(sc)) {
17059         /* not applicable for E2 (and above ...) */
17060         REG_WR(sc, NIG_REG_LLH_E1HOV_MODE, IS_MF_SD(sc));
17061     }
17062
17063     if (CHIP_REV_IS_SLOW(sc)) {
17064         DELAY(200000);
17065     }
17066
17067     /* finish CFC init */
17068     val = reg_poll(sc, CFC_REG_LL_INIT_DONE, 1, 100, 10);
17069     if (val != 1) {
17070         BLOGE(sc, "CFC LL_INIT failed val=0x%x\n", val);
17071         return (-1);
17072     }
17073     val = reg_poll(sc, CFC_REG_AC_INIT_DONE, 1, 100, 10);
17074     if (val != 1) {
17075         BLOGE(sc, "CFC AC_INIT failed val=0x%x\n", val);
17076         return (-1);
17077     }
17078     val = reg_poll(sc, CFC_REG_CAM_INIT_DONE, 1, 100, 10);
17079     if (val != 1) {
17080         BLOGE(sc, "CFC CAM_INIT failed val=0x%x\n", val);
17081         return (-1);
17082     }
17083     REG_WR(sc, CFC_REG_DEBUG0, 0);
17084
17085     if (CHIP_IS_E1(sc)) {
17086         /* read NIG statistic to see if this is our first up since powerup */
17087         bxe_read_dmae(sc, NIG_REG_STAT2_BRB_OCTET, 2);
17088         val = *BXE_SP(sc, wb_data[0]);
17089
17090         /* do internal memory self test */
17091         if ((val == 0) && bxe_int_mem_test(sc)) {
17092             BLOGE(sc, "internal mem self test failed val=0x%x\n", val);
17093             return (-1);
17094         }
17095     }
17096
17097     bxe_setup_fan_failure_detection(sc);
17098
17099     /* clear PXP2 attentions */
17100     REG_RD(sc, PXP2_REG_PXP2_INT_STS_CLR_0);
17101
17102     bxe_enable_blocks_attention(sc);
17103
17104     if (!CHIP_REV_IS_SLOW(sc)) {
17105         ecore_enable_blocks_parity(sc);
17106     }
17107
17108     if (!BXE_NOMCP(sc)) {
17109         if (CHIP_IS_E1x(sc)) {
17110             bxe_common_init_phy(sc);
17111         }
17112     }
17113
17114     return (0);
17115 }
17116
17117 /**
17118  * bxe_init_hw_common_chip - init HW at the COMMON_CHIP phase.
17119  *
17120  * @sc:     driver handle
17121  */
17122 static int
17123 bxe_init_hw_common_chip(struct bxe_softc *sc)
17124 {
17125     int rc = bxe_init_hw_common(sc);
17126
17127     if (rc) {
17128         BLOGE(sc, "bxe_init_hw_common failed rc=%d\n", rc);
17129         return (rc);
17130     }
17131
17132     /* In E2 2-PORT mode, same ext phy is used for the two paths */
17133     if (!BXE_NOMCP(sc)) {
17134         bxe_common_init_phy(sc);
17135     }
17136
17137     return (0);
17138 }
17139
17140 static int
17141 bxe_init_hw_port(struct bxe_softc *sc)
17142 {
17143     int port = SC_PORT(sc);
17144     int init_phase = port ? PHASE_PORT1 : PHASE_PORT0;
17145     uint32_t low, high;
17146     uint32_t val;
17147
17148     BLOGD(sc, DBG_LOAD, "starting port init for port %d\n", port);
17149
17150     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
17151
17152     ecore_init_block(sc, BLOCK_MISC, init_phase);
17153     ecore_init_block(sc, BLOCK_PXP, init_phase);
17154     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17155
17156     /*
17157      * Timers bug workaround: disables the pf_master bit in pglue at
17158      * common phase, we need to enable it here before any dmae access are
17159      * attempted. Therefore we manually added the enable-master to the
17160      * port phase (it also happens in the function phase)
17161      */
17162     if (!CHIP_IS_E1x(sc)) {
17163         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17164     }
17165
17166     ecore_init_block(sc, BLOCK_ATC, init_phase);
17167     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17168     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17169     ecore_init_block(sc, BLOCK_QM, init_phase);
17170
17171     ecore_init_block(sc, BLOCK_TCM, init_phase);
17172     ecore_init_block(sc, BLOCK_UCM, init_phase);
17173     ecore_init_block(sc, BLOCK_CCM, init_phase);
17174     ecore_init_block(sc, BLOCK_XCM, init_phase);
17175
17176     /* QM cid (connection) count */
17177     ecore_qm_init_cid_count(sc, sc->qm_cid_count, INITOP_SET);
17178
17179     if (CNIC_SUPPORT(sc)) {
17180         ecore_init_block(sc, BLOCK_TM, init_phase);
17181         REG_WR(sc, TM_REG_LIN0_SCAN_TIME + port*4, 20);
17182         REG_WR(sc, TM_REG_LIN0_MAX_ACTIVE_CID + port*4, 31);
17183     }
17184
17185     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17186
17187     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17188
17189     if (CHIP_IS_E1(sc) || CHIP_IS_E1H(sc)) {
17190         if (IS_MF(sc)) {
17191             low = (BXE_ONE_PORT(sc) ? 160 : 246);
17192         } else if (sc->mtu > 4096) {
17193             if (BXE_ONE_PORT(sc)) {
17194                 low = 160;
17195             } else {
17196                 val = sc->mtu;
17197                 /* (24*1024 + val*4)/256 */
17198                 low = (96 + (val / 64) + ((val % 64) ? 1 : 0));
17199             }
17200         } else {
17201             low = (BXE_ONE_PORT(sc) ? 80 : 160);
17202         }
17203         high = (low + 56); /* 14*1024/256 */
17204         REG_WR(sc, BRB1_REG_PAUSE_LOW_THRESHOLD_0 + port*4, low);
17205         REG_WR(sc, BRB1_REG_PAUSE_HIGH_THRESHOLD_0 + port*4, high);
17206     }
17207
17208     if (CHIP_IS_MODE_4_PORT(sc)) {
17209         REG_WR(sc, SC_PORT(sc) ?
17210                BRB1_REG_MAC_GUARANTIED_1 :
17211                BRB1_REG_MAC_GUARANTIED_0, 40);
17212     }
17213
17214     ecore_init_block(sc, BLOCK_PRS, init_phase);
17215     if (CHIP_IS_E3B0(sc)) {
17216         if (IS_MF_AFEX(sc)) {
17217             /* configure headers for AFEX mode */
17218             REG_WR(sc, SC_PORT(sc) ?
17219                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17220                    PRS_REG_HDRS_AFTER_BASIC_PORT_0, 0xE);
17221             REG_WR(sc, SC_PORT(sc) ?
17222                    PRS_REG_HDRS_AFTER_TAG_0_PORT_1 :
17223                    PRS_REG_HDRS_AFTER_TAG_0_PORT_0, 0x6);
17224             REG_WR(sc, SC_PORT(sc) ?
17225                    PRS_REG_MUST_HAVE_HDRS_PORT_1 :
17226                    PRS_REG_MUST_HAVE_HDRS_PORT_0, 0xA);
17227         } else {
17228             /* Ovlan exists only if we are in multi-function +
17229              * switch-dependent mode, in switch-independent there
17230              * is no ovlan headers
17231              */
17232             REG_WR(sc, SC_PORT(sc) ?
17233                    PRS_REG_HDRS_AFTER_BASIC_PORT_1 :
17234                    PRS_REG_HDRS_AFTER_BASIC_PORT_0,
17235                    (sc->devinfo.mf_info.path_has_ovlan ? 7 : 6));
17236         }
17237     }
17238
17239     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17240     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17241     ecore_init_block(sc, BLOCK_USDM, init_phase);
17242     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17243
17244     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17245     ecore_init_block(sc, BLOCK_USEM, init_phase);
17246     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17247     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17248
17249     ecore_init_block(sc, BLOCK_UPB, init_phase);
17250     ecore_init_block(sc, BLOCK_XPB, init_phase);
17251
17252     ecore_init_block(sc, BLOCK_PBF, init_phase);
17253
17254     if (CHIP_IS_E1x(sc)) {
17255         /* configure PBF to work without PAUSE mtu 9000 */
17256         REG_WR(sc, PBF_REG_P0_PAUSE_ENABLE + port*4, 0);
17257
17258         /* update threshold */
17259         REG_WR(sc, PBF_REG_P0_ARB_THRSH + port*4, (9040/16));
17260         /* update init credit */
17261         REG_WR(sc, PBF_REG_P0_INIT_CRD + port*4, (9040/16) + 553 - 22);
17262
17263         /* probe changes */
17264         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 1);
17265         DELAY(50);
17266         REG_WR(sc, PBF_REG_INIT_P0 + port*4, 0);
17267     }
17268
17269     if (CNIC_SUPPORT(sc)) {
17270         ecore_init_block(sc, BLOCK_SRC, init_phase);
17271     }
17272
17273     ecore_init_block(sc, BLOCK_CDU, init_phase);
17274     ecore_init_block(sc, BLOCK_CFC, init_phase);
17275
17276     if (CHIP_IS_E1(sc)) {
17277         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17278         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17279     }
17280     ecore_init_block(sc, BLOCK_HC, init_phase);
17281
17282     ecore_init_block(sc, BLOCK_IGU, init_phase);
17283
17284     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17285     /* init aeu_mask_attn_func_0/1:
17286      *  - SF mode: bits 3-7 are masked. only bits 0-2 are in use
17287      *  - MF mode: bit 3 is masked. bits 0-2 are in use as in SF
17288      *             bits 4-7 are used for "per vn group attention" */
17289     val = IS_MF(sc) ? 0xF7 : 0x7;
17290     /* Enable DCBX attention for all but E1 */
17291     val |= CHIP_IS_E1(sc) ? 0 : 0x10;
17292     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, val);
17293
17294     ecore_init_block(sc, BLOCK_NIG, init_phase);
17295
17296     if (!CHIP_IS_E1x(sc)) {
17297         /* Bit-map indicating which L2 hdrs may appear after the
17298          * basic Ethernet header
17299          */
17300         if (IS_MF_AFEX(sc)) {
17301             REG_WR(sc, SC_PORT(sc) ?
17302                    NIG_REG_P1_HDRS_AFTER_BASIC :
17303                    NIG_REG_P0_HDRS_AFTER_BASIC, 0xE);
17304         } else {
17305             REG_WR(sc, SC_PORT(sc) ?
17306                    NIG_REG_P1_HDRS_AFTER_BASIC :
17307                    NIG_REG_P0_HDRS_AFTER_BASIC,
17308                    IS_MF_SD(sc) ? 7 : 6);
17309         }
17310
17311         if (CHIP_IS_E3(sc)) {
17312             REG_WR(sc, SC_PORT(sc) ?
17313                    NIG_REG_LLH1_MF_MODE :
17314                    NIG_REG_LLH_MF_MODE, IS_MF(sc));
17315         }
17316     }
17317     if (!CHIP_IS_E3(sc)) {
17318         REG_WR(sc, NIG_REG_XGXS_SERDES0_MODE_SEL + port*4, 1);
17319     }
17320
17321     if (!CHIP_IS_E1(sc)) {
17322         /* 0x2 disable mf_ov, 0x1 enable */
17323         REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK_MF + port*4,
17324                (IS_MF_SD(sc) ? 0x1 : 0x2));
17325
17326         if (!CHIP_IS_E1x(sc)) {
17327             val = 0;
17328             switch (sc->devinfo.mf_info.mf_mode) {
17329             case MULTI_FUNCTION_SD:
17330                 val = 1;
17331                 break;
17332             case MULTI_FUNCTION_SI:
17333             case MULTI_FUNCTION_AFEX:
17334                 val = 2;
17335                 break;
17336             }
17337
17338             REG_WR(sc, (SC_PORT(sc) ? NIG_REG_LLH1_CLS_TYPE :
17339                         NIG_REG_LLH0_CLS_TYPE), val);
17340         }
17341         REG_WR(sc, NIG_REG_LLFC_ENABLE_0 + port*4, 0);
17342         REG_WR(sc, NIG_REG_LLFC_OUT_EN_0 + port*4, 0);
17343         REG_WR(sc, NIG_REG_PAUSE_ENABLE_0 + port*4, 1);
17344     }
17345
17346     /* If SPIO5 is set to generate interrupts, enable it for this port */
17347     val = REG_RD(sc, MISC_REG_SPIO_EVENT_EN);
17348     if (val & MISC_SPIO_SPIO5) {
17349         uint32_t reg_addr = (port ? MISC_REG_AEU_ENABLE1_FUNC_1_OUT_0 :
17350                                     MISC_REG_AEU_ENABLE1_FUNC_0_OUT_0);
17351         val = REG_RD(sc, reg_addr);
17352         val |= AEU_INPUTS_ATTN_BITS_SPIO5;
17353         REG_WR(sc, reg_addr, val);
17354     }
17355
17356     return (0);
17357 }
17358
17359 static uint32_t
17360 bxe_flr_clnup_reg_poll(struct bxe_softc *sc,
17361                        uint32_t         reg,
17362                        uint32_t         expected,
17363                        uint32_t         poll_count)
17364 {
17365     uint32_t cur_cnt = poll_count;
17366     uint32_t val;
17367
17368     while ((val = REG_RD(sc, reg)) != expected && cur_cnt--) {
17369         DELAY(FLR_WAIT_INTERVAL);
17370     }
17371
17372     return (val);
17373 }
17374
17375 static int
17376 bxe_flr_clnup_poll_hw_counter(struct bxe_softc *sc,
17377                               uint32_t         reg,
17378                               char             *msg,
17379                               uint32_t         poll_cnt)
17380 {
17381     uint32_t val = bxe_flr_clnup_reg_poll(sc, reg, 0, poll_cnt);
17382
17383     if (val != 0) {
17384         BLOGE(sc, "%s usage count=%d\n", msg, val);
17385         return (1);
17386     }
17387
17388     return (0);
17389 }
17390
17391 /* Common routines with VF FLR cleanup */
17392 static uint32_t
17393 bxe_flr_clnup_poll_count(struct bxe_softc *sc)
17394 {
17395     /* adjust polling timeout */
17396     if (CHIP_REV_IS_EMUL(sc)) {
17397         return (FLR_POLL_CNT * 2000);
17398     }
17399
17400     if (CHIP_REV_IS_FPGA(sc)) {
17401         return (FLR_POLL_CNT * 120);
17402     }
17403
17404     return (FLR_POLL_CNT);
17405 }
17406
17407 static int
17408 bxe_poll_hw_usage_counters(struct bxe_softc *sc,
17409                            uint32_t         poll_cnt)
17410 {
17411     /* wait for CFC PF usage-counter to zero (includes all the VFs) */
17412     if (bxe_flr_clnup_poll_hw_counter(sc,
17413                                       CFC_REG_NUM_LCIDS_INSIDE_PF,
17414                                       "CFC PF usage counter timed out",
17415                                       poll_cnt)) {
17416         return (1);
17417     }
17418
17419     /* Wait for DQ PF usage-counter to zero (until DQ cleanup) */
17420     if (bxe_flr_clnup_poll_hw_counter(sc,
17421                                       DORQ_REG_PF_USAGE_CNT,
17422                                       "DQ PF usage counter timed out",
17423                                       poll_cnt)) {
17424         return (1);
17425     }
17426
17427     /* Wait for QM PF usage-counter to zero (until DQ cleanup) */
17428     if (bxe_flr_clnup_poll_hw_counter(sc,
17429                                       QM_REG_PF_USG_CNT_0 + 4*SC_FUNC(sc),
17430                                       "QM PF usage counter timed out",
17431                                       poll_cnt)) {
17432         return (1);
17433     }
17434
17435     /* Wait for Timer PF usage-counters to zero (until DQ cleanup) */
17436     if (bxe_flr_clnup_poll_hw_counter(sc,
17437                                       TM_REG_LIN0_VNIC_UC + 4*SC_PORT(sc),
17438                                       "Timers VNIC usage counter timed out",
17439                                       poll_cnt)) {
17440         return (1);
17441     }
17442
17443     if (bxe_flr_clnup_poll_hw_counter(sc,
17444                                       TM_REG_LIN0_NUM_SCANS + 4*SC_PORT(sc),
17445                                       "Timers NUM_SCANS usage counter timed out",
17446                                       poll_cnt)) {
17447         return (1);
17448     }
17449
17450     /* Wait DMAE PF usage counter to zero */
17451     if (bxe_flr_clnup_poll_hw_counter(sc,
17452                                       dmae_reg_go_c[INIT_DMAE_C(sc)],
17453                                       "DMAE dommand register timed out",
17454                                       poll_cnt)) {
17455         return (1);
17456     }
17457
17458     return (0);
17459 }
17460
17461 #define OP_GEN_PARAM(param)                                            \
17462     (((param) << SDM_OP_GEN_COMP_PARAM_SHIFT) & SDM_OP_GEN_COMP_PARAM)
17463 #define OP_GEN_TYPE(type)                                           \
17464     (((type) << SDM_OP_GEN_COMP_TYPE_SHIFT) & SDM_OP_GEN_COMP_TYPE)
17465 #define OP_GEN_AGG_VECT(index)                                             \
17466     (((index) << SDM_OP_GEN_AGG_VECT_IDX_SHIFT) & SDM_OP_GEN_AGG_VECT_IDX)
17467
17468 static int
17469 bxe_send_final_clnup(struct bxe_softc *sc,
17470                      uint8_t          clnup_func,
17471                      uint32_t         poll_cnt)
17472 {
17473     uint32_t op_gen_command = 0;
17474     uint32_t comp_addr = (BAR_CSTRORM_INTMEM +
17475                           CSTORM_FINAL_CLEANUP_COMPLETE_OFFSET(clnup_func));
17476     int ret = 0;
17477
17478     if (REG_RD(sc, comp_addr)) {
17479         BLOGE(sc, "Cleanup complete was not 0 before sending\n");
17480         return (1);
17481     }
17482
17483     op_gen_command |= OP_GEN_PARAM(XSTORM_AGG_INT_FINAL_CLEANUP_INDEX);
17484     op_gen_command |= OP_GEN_TYPE(XSTORM_AGG_INT_FINAL_CLEANUP_COMP_TYPE);
17485     op_gen_command |= OP_GEN_AGG_VECT(clnup_func);
17486     op_gen_command |= 1 << SDM_OP_GEN_AGG_VECT_IDX_VALID_SHIFT;
17487
17488     BLOGD(sc, DBG_LOAD, "sending FW Final cleanup\n");
17489     REG_WR(sc, XSDM_REG_OPERATION_GEN, op_gen_command);
17490
17491     if (bxe_flr_clnup_reg_poll(sc, comp_addr, 1, poll_cnt) != 1) {
17492         BLOGE(sc, "FW final cleanup did not succeed\n");
17493         BLOGD(sc, DBG_LOAD, "At timeout completion address contained %x\n",
17494               (REG_RD(sc, comp_addr)));
17495         bxe_panic(sc, ("FLR cleanup failed\n"));
17496         return (1);
17497     }
17498
17499     /* Zero completion for nxt FLR */
17500     REG_WR(sc, comp_addr, 0);
17501
17502     return (ret);
17503 }
17504
17505 static void
17506 bxe_pbf_pN_buf_flushed(struct bxe_softc       *sc,
17507                        struct pbf_pN_buf_regs *regs,
17508                        uint32_t               poll_count)
17509 {
17510     uint32_t init_crd, crd, crd_start, crd_freed, crd_freed_start;
17511     uint32_t cur_cnt = poll_count;
17512
17513     crd_freed = crd_freed_start = REG_RD(sc, regs->crd_freed);
17514     crd = crd_start = REG_RD(sc, regs->crd);
17515     init_crd = REG_RD(sc, regs->init_crd);
17516
17517     BLOGD(sc, DBG_LOAD, "INIT CREDIT[%d] : %x\n", regs->pN, init_crd);
17518     BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : s:%x\n", regs->pN, crd);
17519     BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: s:%x\n", regs->pN, crd_freed);
17520
17521     while ((crd != init_crd) &&
17522            ((uint32_t)((int32_t)crd_freed - (int32_t)crd_freed_start) <
17523             (init_crd - crd_start))) {
17524         if (cur_cnt--) {
17525             DELAY(FLR_WAIT_INTERVAL);
17526             crd = REG_RD(sc, regs->crd);
17527             crd_freed = REG_RD(sc, regs->crd_freed);
17528         } else {
17529             BLOGD(sc, DBG_LOAD, "PBF tx buffer[%d] timed out\n", regs->pN);
17530             BLOGD(sc, DBG_LOAD, "CREDIT[%d]      : c:%x\n", regs->pN, crd);
17531             BLOGD(sc, DBG_LOAD, "CREDIT_FREED[%d]: c:%x\n", regs->pN, crd_freed);
17532             break;
17533         }
17534     }
17535
17536     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF tx buffer[%d]\n",
17537           poll_count-cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17538 }
17539
17540 static void
17541 bxe_pbf_pN_cmd_flushed(struct bxe_softc       *sc,
17542                        struct pbf_pN_cmd_regs *regs,
17543                        uint32_t               poll_count)
17544 {
17545     uint32_t occup, to_free, freed, freed_start;
17546     uint32_t cur_cnt = poll_count;
17547
17548     occup = to_free = REG_RD(sc, regs->lines_occup);
17549     freed = freed_start = REG_RD(sc, regs->lines_freed);
17550
17551     BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17552     BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17553
17554     while (occup &&
17555            ((uint32_t)((int32_t)freed - (int32_t)freed_start) < to_free)) {
17556         if (cur_cnt--) {
17557             DELAY(FLR_WAIT_INTERVAL);
17558             occup = REG_RD(sc, regs->lines_occup);
17559             freed = REG_RD(sc, regs->lines_freed);
17560         } else {
17561             BLOGD(sc, DBG_LOAD, "PBF cmd queue[%d] timed out\n", regs->pN);
17562             BLOGD(sc, DBG_LOAD, "OCCUPANCY[%d]   : s:%x\n", regs->pN, occup);
17563             BLOGD(sc, DBG_LOAD, "LINES_FREED[%d] : s:%x\n", regs->pN, freed);
17564             break;
17565         }
17566     }
17567
17568     BLOGD(sc, DBG_LOAD, "Waited %d*%d usec for PBF cmd queue[%d]\n",
17569           poll_count - cur_cnt, FLR_WAIT_INTERVAL, regs->pN);
17570 }
17571
17572 static void
17573 bxe_tx_hw_flushed(struct bxe_softc *sc, uint32_t poll_count)
17574 {
17575     struct pbf_pN_cmd_regs cmd_regs[] = {
17576         {0, (CHIP_IS_E3B0(sc)) ?
17577             PBF_REG_TQ_OCCUPANCY_Q0 :
17578             PBF_REG_P0_TQ_OCCUPANCY,
17579             (CHIP_IS_E3B0(sc)) ?
17580             PBF_REG_TQ_LINES_FREED_CNT_Q0 :
17581             PBF_REG_P0_TQ_LINES_FREED_CNT},
17582         {1, (CHIP_IS_E3B0(sc)) ?
17583             PBF_REG_TQ_OCCUPANCY_Q1 :
17584             PBF_REG_P1_TQ_OCCUPANCY,
17585             (CHIP_IS_E3B0(sc)) ?
17586             PBF_REG_TQ_LINES_FREED_CNT_Q1 :
17587             PBF_REG_P1_TQ_LINES_FREED_CNT},
17588         {4, (CHIP_IS_E3B0(sc)) ?
17589             PBF_REG_TQ_OCCUPANCY_LB_Q :
17590             PBF_REG_P4_TQ_OCCUPANCY,
17591             (CHIP_IS_E3B0(sc)) ?
17592             PBF_REG_TQ_LINES_FREED_CNT_LB_Q :
17593             PBF_REG_P4_TQ_LINES_FREED_CNT}
17594     };
17595
17596     struct pbf_pN_buf_regs buf_regs[] = {
17597         {0, (CHIP_IS_E3B0(sc)) ?
17598             PBF_REG_INIT_CRD_Q0 :
17599             PBF_REG_P0_INIT_CRD ,
17600             (CHIP_IS_E3B0(sc)) ?
17601             PBF_REG_CREDIT_Q0 :
17602             PBF_REG_P0_CREDIT,
17603             (CHIP_IS_E3B0(sc)) ?
17604             PBF_REG_INTERNAL_CRD_FREED_CNT_Q0 :
17605             PBF_REG_P0_INTERNAL_CRD_FREED_CNT},
17606         {1, (CHIP_IS_E3B0(sc)) ?
17607             PBF_REG_INIT_CRD_Q1 :
17608             PBF_REG_P1_INIT_CRD,
17609             (CHIP_IS_E3B0(sc)) ?
17610             PBF_REG_CREDIT_Q1 :
17611             PBF_REG_P1_CREDIT,
17612             (CHIP_IS_E3B0(sc)) ?
17613             PBF_REG_INTERNAL_CRD_FREED_CNT_Q1 :
17614             PBF_REG_P1_INTERNAL_CRD_FREED_CNT},
17615         {4, (CHIP_IS_E3B0(sc)) ?
17616             PBF_REG_INIT_CRD_LB_Q :
17617             PBF_REG_P4_INIT_CRD,
17618             (CHIP_IS_E3B0(sc)) ?
17619             PBF_REG_CREDIT_LB_Q :
17620             PBF_REG_P4_CREDIT,
17621             (CHIP_IS_E3B0(sc)) ?
17622             PBF_REG_INTERNAL_CRD_FREED_CNT_LB_Q :
17623             PBF_REG_P4_INTERNAL_CRD_FREED_CNT},
17624     };
17625
17626     int i;
17627
17628     /* Verify the command queues are flushed P0, P1, P4 */
17629     for (i = 0; i < ARRAY_SIZE(cmd_regs); i++) {
17630         bxe_pbf_pN_cmd_flushed(sc, &cmd_regs[i], poll_count);
17631     }
17632
17633     /* Verify the transmission buffers are flushed P0, P1, P4 */
17634     for (i = 0; i < ARRAY_SIZE(buf_regs); i++) {
17635         bxe_pbf_pN_buf_flushed(sc, &buf_regs[i], poll_count);
17636     }
17637 }
17638
17639 static void
17640 bxe_hw_enable_status(struct bxe_softc *sc)
17641 {
17642     uint32_t val;
17643
17644     val = REG_RD(sc, CFC_REG_WEAK_ENABLE_PF);
17645     BLOGD(sc, DBG_LOAD, "CFC_REG_WEAK_ENABLE_PF is 0x%x\n", val);
17646
17647     val = REG_RD(sc, PBF_REG_DISABLE_PF);
17648     BLOGD(sc, DBG_LOAD, "PBF_REG_DISABLE_PF is 0x%x\n", val);
17649
17650     val = REG_RD(sc, IGU_REG_PCI_PF_MSI_EN);
17651     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSI_EN is 0x%x\n", val);
17652
17653     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_EN);
17654     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_EN is 0x%x\n", val);
17655
17656     val = REG_RD(sc, IGU_REG_PCI_PF_MSIX_FUNC_MASK);
17657     BLOGD(sc, DBG_LOAD, "IGU_REG_PCI_PF_MSIX_FUNC_MASK is 0x%x\n", val);
17658
17659     val = REG_RD(sc, PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR);
17660     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_SHADOW_BME_PF_7_0_CLR is 0x%x\n", val);
17661
17662     val = REG_RD(sc, PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR);
17663     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_FLR_REQUEST_PF_7_0_CLR is 0x%x\n", val);
17664
17665     val = REG_RD(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER);
17666     BLOGD(sc, DBG_LOAD, "PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER is 0x%x\n", val);
17667 }
17668
17669 static int
17670 bxe_pf_flr_clnup(struct bxe_softc *sc)
17671 {
17672     uint32_t poll_cnt = bxe_flr_clnup_poll_count(sc);
17673
17674     BLOGD(sc, DBG_LOAD, "Cleanup after FLR PF[%d]\n", SC_ABS_FUNC(sc));
17675
17676     /* Re-enable PF target read access */
17677     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_TARGET_READ, 1);
17678
17679     /* Poll HW usage counters */
17680     BLOGD(sc, DBG_LOAD, "Polling usage counters\n");
17681     if (bxe_poll_hw_usage_counters(sc, poll_cnt)) {
17682         return (-1);
17683     }
17684
17685     /* Zero the igu 'trailing edge' and 'leading edge' */
17686
17687     /* Send the FW cleanup command */
17688     if (bxe_send_final_clnup(sc, (uint8_t)SC_FUNC(sc), poll_cnt)) {
17689         return (-1);
17690     }
17691
17692     /* ATC cleanup */
17693
17694     /* Verify TX hw is flushed */
17695     bxe_tx_hw_flushed(sc, poll_cnt);
17696
17697     /* Wait 100ms (not adjusted according to platform) */
17698     DELAY(100000);
17699
17700     /* Verify no pending pci transactions */
17701     if (bxe_is_pcie_pending(sc)) {
17702         BLOGE(sc, "PCIE Transactions still pending\n");
17703     }
17704
17705     /* Debug */
17706     bxe_hw_enable_status(sc);
17707
17708     /*
17709      * Master enable - Due to WB DMAE writes performed before this
17710      * register is re-initialized as part of the regular function init
17711      */
17712     REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17713
17714     return (0);
17715 }
17716
17717 static int
17718 bxe_init_hw_func(struct bxe_softc *sc)
17719 {
17720     int port = SC_PORT(sc);
17721     int func = SC_FUNC(sc);
17722     int init_phase = PHASE_PF0 + func;
17723     struct ecore_ilt *ilt = sc->ilt;
17724     uint16_t cdu_ilt_start;
17725     uint32_t addr, val;
17726     uint32_t main_mem_base, main_mem_size, main_mem_prty_clr;
17727     int i, main_mem_width, rc;
17728
17729     BLOGD(sc, DBG_LOAD, "starting func init for func %d\n", func);
17730
17731     /* FLR cleanup */
17732     if (!CHIP_IS_E1x(sc)) {
17733         rc = bxe_pf_flr_clnup(sc);
17734         if (rc) {
17735             BLOGE(sc, "FLR cleanup failed!\n");
17736             // XXX bxe_fw_dump(sc);
17737             // XXX bxe_idle_chk(sc);
17738             return (rc);
17739         }
17740     }
17741
17742     /* set MSI reconfigure capability */
17743     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17744         addr = (port ? HC_REG_CONFIG_1 : HC_REG_CONFIG_0);
17745         val = REG_RD(sc, addr);
17746         val |= HC_CONFIG_0_REG_MSI_ATTN_EN_0;
17747         REG_WR(sc, addr, val);
17748     }
17749
17750     ecore_init_block(sc, BLOCK_PXP, init_phase);
17751     ecore_init_block(sc, BLOCK_PXP2, init_phase);
17752
17753     ilt = sc->ilt;
17754     cdu_ilt_start = ilt->clients[ILT_CLIENT_CDU].start;
17755
17756     for (i = 0; i < L2_ILT_LINES(sc); i++) {
17757         ilt->lines[cdu_ilt_start + i].page = sc->context[i].vcxt;
17758         ilt->lines[cdu_ilt_start + i].page_mapping =
17759             sc->context[i].vcxt_dma.paddr;
17760         ilt->lines[cdu_ilt_start + i].size = sc->context[i].size;
17761     }
17762     ecore_ilt_init_op(sc, INITOP_SET);
17763
17764     /* Set NIC mode */
17765     REG_WR(sc, PRS_REG_NIC_MODE, 1);
17766     BLOGD(sc, DBG_LOAD, "NIC MODE configured\n");
17767
17768     if (!CHIP_IS_E1x(sc)) {
17769         uint32_t pf_conf = IGU_PF_CONF_FUNC_EN;
17770
17771         /* Turn on a single ISR mode in IGU if driver is going to use
17772          * INT#x or MSI
17773          */
17774         if (sc->interrupt_mode != INTR_MODE_MSIX) {
17775             pf_conf |= IGU_PF_CONF_SINGLE_ISR_EN;
17776         }
17777
17778         /*
17779          * Timers workaround bug: function init part.
17780          * Need to wait 20msec after initializing ILT,
17781          * needed to make sure there are no requests in
17782          * one of the PXP internal queues with "old" ILT addresses
17783          */
17784         DELAY(20000);
17785
17786         /*
17787          * Master enable - Due to WB DMAE writes performed before this
17788          * register is re-initialized as part of the regular function
17789          * init
17790          */
17791         REG_WR(sc, PGLUE_B_REG_INTERNAL_PFID_ENABLE_MASTER, 1);
17792         /* Enable the function in IGU */
17793         REG_WR(sc, IGU_REG_PF_CONFIGURATION, pf_conf);
17794     }
17795
17796     sc->dmae_ready = 1;
17797
17798     ecore_init_block(sc, BLOCK_PGLUE_B, init_phase);
17799
17800     if (!CHIP_IS_E1x(sc))
17801         REG_WR(sc, PGLUE_B_REG_WAS_ERROR_PF_7_0_CLR, func);
17802
17803     ecore_init_block(sc, BLOCK_ATC, init_phase);
17804     ecore_init_block(sc, BLOCK_DMAE, init_phase);
17805     ecore_init_block(sc, BLOCK_NIG, init_phase);
17806     ecore_init_block(sc, BLOCK_SRC, init_phase);
17807     ecore_init_block(sc, BLOCK_MISC, init_phase);
17808     ecore_init_block(sc, BLOCK_TCM, init_phase);
17809     ecore_init_block(sc, BLOCK_UCM, init_phase);
17810     ecore_init_block(sc, BLOCK_CCM, init_phase);
17811     ecore_init_block(sc, BLOCK_XCM, init_phase);
17812     ecore_init_block(sc, BLOCK_TSEM, init_phase);
17813     ecore_init_block(sc, BLOCK_USEM, init_phase);
17814     ecore_init_block(sc, BLOCK_CSEM, init_phase);
17815     ecore_init_block(sc, BLOCK_XSEM, init_phase);
17816
17817     if (!CHIP_IS_E1x(sc))
17818         REG_WR(sc, QM_REG_PF_EN, 1);
17819
17820     if (!CHIP_IS_E1x(sc)) {
17821         REG_WR(sc, TSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17822         REG_WR(sc, USEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17823         REG_WR(sc, CSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17824         REG_WR(sc, XSEM_REG_VFPF_ERR_NUM, BXE_MAX_NUM_OF_VFS + func);
17825     }
17826     ecore_init_block(sc, BLOCK_QM, init_phase);
17827
17828     ecore_init_block(sc, BLOCK_TM, init_phase);
17829     ecore_init_block(sc, BLOCK_DORQ, init_phase);
17830
17831     bxe_iov_init_dq(sc);
17832
17833     ecore_init_block(sc, BLOCK_BRB1, init_phase);
17834     ecore_init_block(sc, BLOCK_PRS, init_phase);
17835     ecore_init_block(sc, BLOCK_TSDM, init_phase);
17836     ecore_init_block(sc, BLOCK_CSDM, init_phase);
17837     ecore_init_block(sc, BLOCK_USDM, init_phase);
17838     ecore_init_block(sc, BLOCK_XSDM, init_phase);
17839     ecore_init_block(sc, BLOCK_UPB, init_phase);
17840     ecore_init_block(sc, BLOCK_XPB, init_phase);
17841     ecore_init_block(sc, BLOCK_PBF, init_phase);
17842     if (!CHIP_IS_E1x(sc))
17843         REG_WR(sc, PBF_REG_DISABLE_PF, 0);
17844
17845     ecore_init_block(sc, BLOCK_CDU, init_phase);
17846
17847     ecore_init_block(sc, BLOCK_CFC, init_phase);
17848
17849     if (!CHIP_IS_E1x(sc))
17850         REG_WR(sc, CFC_REG_WEAK_ENABLE_PF, 1);
17851
17852     if (IS_MF(sc)) {
17853         REG_WR(sc, NIG_REG_LLH0_FUNC_EN + port*8, 1);
17854         REG_WR(sc, NIG_REG_LLH0_FUNC_VLAN_ID + port*8, OVLAN(sc));
17855     }
17856
17857     ecore_init_block(sc, BLOCK_MISC_AEU, init_phase);
17858
17859     /* HC init per function */
17860     if (sc->devinfo.int_block == INT_BLOCK_HC) {
17861         if (CHIP_IS_E1H(sc)) {
17862             REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17863
17864             REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
17865             REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
17866         }
17867         ecore_init_block(sc, BLOCK_HC, init_phase);
17868
17869     } else {
17870         int num_segs, sb_idx, prod_offset;
17871
17872         REG_WR(sc, MISC_REG_AEU_GENERAL_ATTN_12 + func*4, 0);
17873
17874         if (!CHIP_IS_E1x(sc)) {
17875             REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
17876             REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
17877         }
17878
17879         ecore_init_block(sc, BLOCK_IGU, init_phase);
17880
17881         if (!CHIP_IS_E1x(sc)) {
17882             int dsb_idx = 0;
17883             /**
17884              * Producer memory:
17885              * E2 mode: address 0-135 match to the mapping memory;
17886              * 136 - PF0 default prod; 137 - PF1 default prod;
17887              * 138 - PF2 default prod; 139 - PF3 default prod;
17888              * 140 - PF0 attn prod;    141 - PF1 attn prod;
17889              * 142 - PF2 attn prod;    143 - PF3 attn prod;
17890              * 144-147 reserved.
17891              *
17892              * E1.5 mode - In backward compatible mode;
17893              * for non default SB; each even line in the memory
17894              * holds the U producer and each odd line hold
17895              * the C producer. The first 128 producers are for
17896              * NDSB (PF0 - 0-31; PF1 - 32-63 and so on). The last 20
17897              * producers are for the DSB for each PF.
17898              * Each PF has five segments: (the order inside each
17899              * segment is PF0; PF1; PF2; PF3) - 128-131 U prods;
17900              * 132-135 C prods; 136-139 X prods; 140-143 T prods;
17901              * 144-147 attn prods;
17902              */
17903             /* non-default-status-blocks */
17904             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17905                 IGU_BC_NDSB_NUM_SEGS : IGU_NORM_NDSB_NUM_SEGS;
17906             for (sb_idx = 0; sb_idx < sc->igu_sb_cnt; sb_idx++) {
17907                 prod_offset = (sc->igu_base_sb + sb_idx) *
17908                     num_segs;
17909
17910                 for (i = 0; i < num_segs; i++) {
17911                     addr = IGU_REG_PROD_CONS_MEMORY +
17912                             (prod_offset + i) * 4;
17913                     REG_WR(sc, addr, 0);
17914                 }
17915                 /* send consumer update with value 0 */
17916                 bxe_ack_sb(sc, sc->igu_base_sb + sb_idx,
17917                            USTORM_ID, 0, IGU_INT_NOP, 1);
17918                 bxe_igu_clear_sb(sc, sc->igu_base_sb + sb_idx);
17919             }
17920
17921             /* default-status-blocks */
17922             num_segs = CHIP_INT_MODE_IS_BC(sc) ?
17923                 IGU_BC_DSB_NUM_SEGS : IGU_NORM_DSB_NUM_SEGS;
17924
17925             if (CHIP_IS_MODE_4_PORT(sc))
17926                 dsb_idx = SC_FUNC(sc);
17927             else
17928                 dsb_idx = SC_VN(sc);
17929
17930             prod_offset = (CHIP_INT_MODE_IS_BC(sc) ?
17931                        IGU_BC_BASE_DSB_PROD + dsb_idx :
17932                        IGU_NORM_BASE_DSB_PROD + dsb_idx);
17933
17934             /*
17935              * igu prods come in chunks of E1HVN_MAX (4) -
17936              * does not matters what is the current chip mode
17937              */
17938             for (i = 0; i < (num_segs * E1HVN_MAX);
17939                  i += E1HVN_MAX) {
17940                 addr = IGU_REG_PROD_CONS_MEMORY +
17941                             (prod_offset + i)*4;
17942                 REG_WR(sc, addr, 0);
17943             }
17944             /* send consumer update with 0 */
17945             if (CHIP_INT_MODE_IS_BC(sc)) {
17946                 bxe_ack_sb(sc, sc->igu_dsb_id,
17947                            USTORM_ID, 0, IGU_INT_NOP, 1);
17948                 bxe_ack_sb(sc, sc->igu_dsb_id,
17949                            CSTORM_ID, 0, IGU_INT_NOP, 1);
17950                 bxe_ack_sb(sc, sc->igu_dsb_id,
17951                            XSTORM_ID, 0, IGU_INT_NOP, 1);
17952                 bxe_ack_sb(sc, sc->igu_dsb_id,
17953                            TSTORM_ID, 0, IGU_INT_NOP, 1);
17954                 bxe_ack_sb(sc, sc->igu_dsb_id,
17955                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17956             } else {
17957                 bxe_ack_sb(sc, sc->igu_dsb_id,
17958                            USTORM_ID, 0, IGU_INT_NOP, 1);
17959                 bxe_ack_sb(sc, sc->igu_dsb_id,
17960                            ATTENTION_ID, 0, IGU_INT_NOP, 1);
17961             }
17962             bxe_igu_clear_sb(sc, sc->igu_dsb_id);
17963
17964             /* !!! these should become driver const once
17965                rf-tool supports split-68 const */
17966             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_LSB, 0);
17967             REG_WR(sc, IGU_REG_SB_INT_BEFORE_MASK_MSB, 0);
17968             REG_WR(sc, IGU_REG_SB_MASK_LSB, 0);
17969             REG_WR(sc, IGU_REG_SB_MASK_MSB, 0);
17970             REG_WR(sc, IGU_REG_PBA_STATUS_LSB, 0);
17971             REG_WR(sc, IGU_REG_PBA_STATUS_MSB, 0);
17972         }
17973     }
17974
17975     /* Reset PCIE errors for debug */
17976     REG_WR(sc, 0x2114, 0xffffffff);
17977     REG_WR(sc, 0x2120, 0xffffffff);
17978
17979     if (CHIP_IS_E1x(sc)) {
17980         main_mem_size = HC_REG_MAIN_MEMORY_SIZE / 2; /*dwords*/
17981         main_mem_base = HC_REG_MAIN_MEMORY +
17982                 SC_PORT(sc) * (main_mem_size * 4);
17983         main_mem_prty_clr = HC_REG_HC_PRTY_STS_CLR;
17984         main_mem_width = 8;
17985
17986         val = REG_RD(sc, main_mem_prty_clr);
17987         if (val) {
17988             BLOGD(sc, DBG_LOAD,
17989                   "Parity errors in HC block during function init (0x%x)!\n",
17990                   val);
17991         }
17992
17993         /* Clear "false" parity errors in MSI-X table */
17994         for (i = main_mem_base;
17995              i < main_mem_base + main_mem_size * 4;
17996              i += main_mem_width) {
17997             bxe_read_dmae(sc, i, main_mem_width / 4);
17998             bxe_write_dmae(sc, BXE_SP_MAPPING(sc, wb_data),
17999                            i, main_mem_width / 4);
18000         }
18001         /* Clear HC parity attention */
18002         REG_RD(sc, main_mem_prty_clr);
18003     }
18004
18005 #if 1
18006     /* Enable STORMs SP logging */
18007     REG_WR8(sc, BAR_USTRORM_INTMEM +
18008            USTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18009     REG_WR8(sc, BAR_TSTRORM_INTMEM +
18010            TSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18011     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18012            CSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18013     REG_WR8(sc, BAR_XSTRORM_INTMEM +
18014            XSTORM_RECORD_SLOW_PATH_OFFSET(SC_FUNC(sc)), 1);
18015 #endif
18016
18017     elink_phy_probe(&sc->link_params);
18018
18019     return (0);
18020 }
18021
18022 static void
18023 bxe_link_reset(struct bxe_softc *sc)
18024 {
18025     if (!BXE_NOMCP(sc)) {
18026         bxe_acquire_phy_lock(sc);
18027         elink_lfa_reset(&sc->link_params, &sc->link_vars);
18028         bxe_release_phy_lock(sc);
18029     } else {
18030         if (!CHIP_REV_IS_SLOW(sc)) {
18031             BLOGW(sc, "Bootcode is missing - cannot reset link\n");
18032         }
18033     }
18034 }
18035
18036 static void
18037 bxe_reset_port(struct bxe_softc *sc)
18038 {
18039     int port = SC_PORT(sc);
18040     uint32_t val;
18041
18042     /* reset physical Link */
18043     bxe_link_reset(sc);
18044
18045     REG_WR(sc, NIG_REG_MASK_INTERRUPT_PORT0 + port*4, 0);
18046
18047     /* Do not rcv packets to BRB */
18048     REG_WR(sc, NIG_REG_LLH0_BRB1_DRV_MASK + port*4, 0x0);
18049     /* Do not direct rcv packets that are not for MCP to the BRB */
18050     REG_WR(sc, (port ? NIG_REG_LLH1_BRB1_NOT_MCP :
18051                NIG_REG_LLH0_BRB1_NOT_MCP), 0x0);
18052
18053     /* Configure AEU */
18054     REG_WR(sc, MISC_REG_AEU_MASK_ATTN_FUNC_0 + port*4, 0);
18055
18056     DELAY(100000);
18057
18058     /* Check for BRB port occupancy */
18059     val = REG_RD(sc, BRB1_REG_PORT_NUM_OCC_BLOCKS_0 + port*4);
18060     if (val) {
18061         BLOGD(sc, DBG_LOAD,
18062               "BRB1 is not empty, %d blocks are occupied\n", val);
18063     }
18064
18065     /* TODO: Close Doorbell port? */
18066 }
18067
18068 static void
18069 bxe_ilt_wr(struct bxe_softc *sc,
18070            uint32_t         index,
18071            bus_addr_t       addr)
18072 {
18073     int reg;
18074     uint32_t wb_write[2];
18075
18076     if (CHIP_IS_E1(sc)) {
18077         reg = PXP2_REG_RQ_ONCHIP_AT + index*8;
18078     } else {
18079         reg = PXP2_REG_RQ_ONCHIP_AT_B0 + index*8;
18080     }
18081
18082     wb_write[0] = ONCHIP_ADDR1(addr);
18083     wb_write[1] = ONCHIP_ADDR2(addr);
18084     REG_WR_DMAE(sc, reg, wb_write, 2);
18085 }
18086
18087 static void
18088 bxe_clear_func_ilt(struct bxe_softc *sc,
18089                    uint32_t         func)
18090 {
18091     uint32_t i, base = FUNC_ILT_BASE(func);
18092     for (i = base; i < base + ILT_PER_FUNC; i++) {
18093         bxe_ilt_wr(sc, i, 0);
18094     }
18095 }
18096
18097 static void
18098 bxe_reset_func(struct bxe_softc *sc)
18099 {
18100     struct bxe_fastpath *fp;
18101     int port = SC_PORT(sc);
18102     int func = SC_FUNC(sc);
18103     int i;
18104
18105     /* Disable the function in the FW */
18106     REG_WR8(sc, BAR_XSTRORM_INTMEM + XSTORM_FUNC_EN_OFFSET(func), 0);
18107     REG_WR8(sc, BAR_CSTRORM_INTMEM + CSTORM_FUNC_EN_OFFSET(func), 0);
18108     REG_WR8(sc, BAR_TSTRORM_INTMEM + TSTORM_FUNC_EN_OFFSET(func), 0);
18109     REG_WR8(sc, BAR_USTRORM_INTMEM + USTORM_FUNC_EN_OFFSET(func), 0);
18110
18111     /* FP SBs */
18112     FOR_EACH_ETH_QUEUE(sc, i) {
18113         fp = &sc->fp[i];
18114         REG_WR8(sc, BAR_CSTRORM_INTMEM +
18115                 CSTORM_STATUS_BLOCK_DATA_STATE_OFFSET(fp->fw_sb_id),
18116                 SB_DISABLED);
18117     }
18118
18119     /* SP SB */
18120     REG_WR8(sc, BAR_CSTRORM_INTMEM +
18121             CSTORM_SP_STATUS_BLOCK_DATA_STATE_OFFSET(func),
18122             SB_DISABLED);
18123
18124     for (i = 0; i < XSTORM_SPQ_DATA_SIZE / 4; i++) {
18125         REG_WR(sc, BAR_XSTRORM_INTMEM + XSTORM_SPQ_DATA_OFFSET(func), 0);
18126     }
18127
18128     /* Configure IGU */
18129     if (sc->devinfo.int_block == INT_BLOCK_HC) {
18130         REG_WR(sc, HC_REG_LEADING_EDGE_0 + port*8, 0);
18131         REG_WR(sc, HC_REG_TRAILING_EDGE_0 + port*8, 0);
18132     } else {
18133         REG_WR(sc, IGU_REG_LEADING_EDGE_LATCH, 0);
18134         REG_WR(sc, IGU_REG_TRAILING_EDGE_LATCH, 0);
18135     }
18136
18137     if (CNIC_LOADED(sc)) {
18138         /* Disable Timer scan */
18139         REG_WR(sc, TM_REG_EN_LINEAR0_TIMER + port*4, 0);
18140         /*
18141          * Wait for at least 10ms and up to 2 second for the timers
18142          * scan to complete
18143          */
18144         for (i = 0; i < 200; i++) {
18145             DELAY(10000);
18146             if (!REG_RD(sc, TM_REG_LIN0_SCAN_ON + port*4))
18147                 break;
18148         }
18149     }
18150
18151     /* Clear ILT */
18152     bxe_clear_func_ilt(sc, func);
18153
18154     /*
18155      * Timers workaround bug for E2: if this is vnic-3,
18156      * we need to set the entire ilt range for this timers.
18157      */
18158     if (!CHIP_IS_E1x(sc) && SC_VN(sc) == 3) {
18159         struct ilt_client_info ilt_cli;
18160         /* use dummy TM client */
18161         memset(&ilt_cli, 0, sizeof(struct ilt_client_info));
18162         ilt_cli.start = 0;
18163         ilt_cli.end = ILT_NUM_PAGE_ENTRIES - 1;
18164         ilt_cli.client_num = ILT_CLIENT_TM;
18165
18166         ecore_ilt_boundry_init_op(sc, &ilt_cli, 0, INITOP_CLEAR);
18167     }
18168
18169     /* this assumes that reset_port() called before reset_func()*/
18170     if (!CHIP_IS_E1x(sc)) {
18171         bxe_pf_disable(sc);
18172     }
18173
18174     sc->dmae_ready = 0;
18175 }
18176
18177 static int
18178 bxe_gunzip_init(struct bxe_softc *sc)
18179 {
18180     return (0);
18181 }
18182
18183 static void
18184 bxe_gunzip_end(struct bxe_softc *sc)
18185 {
18186     return;
18187 }
18188
18189 static int
18190 bxe_init_firmware(struct bxe_softc *sc)
18191 {
18192     if (CHIP_IS_E1(sc)) {
18193         ecore_init_e1_firmware(sc);
18194         sc->iro_array = e1_iro_arr;
18195     } else if (CHIP_IS_E1H(sc)) {
18196         ecore_init_e1h_firmware(sc);
18197         sc->iro_array = e1h_iro_arr;
18198     } else if (!CHIP_IS_E1x(sc)) {
18199         ecore_init_e2_firmware(sc);
18200         sc->iro_array = e2_iro_arr;
18201     } else {
18202         BLOGE(sc, "Unsupported chip revision\n");
18203         return (-1);
18204     }
18205
18206     return (0);
18207 }
18208
18209 static void
18210 bxe_release_firmware(struct bxe_softc *sc)
18211 {
18212     /* Do nothing */
18213     return;
18214 }
18215
18216 static int
18217 ecore_gunzip(struct bxe_softc *sc,
18218              const uint8_t    *zbuf,
18219              int              len)
18220 {
18221     /* XXX : Implement... */
18222     BLOGD(sc, DBG_LOAD, "ECORE_GUNZIP NOT IMPLEMENTED\n");
18223     return (FALSE);
18224 }
18225
18226 static void
18227 ecore_reg_wr_ind(struct bxe_softc *sc,
18228                  uint32_t         addr,
18229                  uint32_t         val)
18230 {
18231     bxe_reg_wr_ind(sc, addr, val);
18232 }
18233
18234 static void
18235 ecore_write_dmae_phys_len(struct bxe_softc *sc,
18236                           bus_addr_t       phys_addr,
18237                           uint32_t         addr,
18238                           uint32_t         len)
18239 {
18240     bxe_write_dmae_phys_len(sc, phys_addr, addr, len);
18241 }
18242
18243 void
18244 ecore_storm_memset_struct(struct bxe_softc *sc,
18245                           uint32_t         addr,
18246                           size_t           size,
18247                           uint32_t         *data)
18248 {
18249     uint8_t i;
18250     for (i = 0; i < size/4; i++) {
18251         REG_WR(sc, addr + (i * 4), data[i]);
18252     }
18253 }
18254
18255
18256 /*
18257  * character device - ioctl interface definitions
18258  */
18259
18260
18261 #include "bxe_dump.h"
18262 #include "bxe_ioctl.h"
18263 #include <sys/conf.h>
18264
18265 static int bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18266                 struct thread *td);
18267
18268 static struct cdevsw bxe_cdevsw = {
18269     .d_version = D_VERSION,
18270     .d_ioctl = bxe_eioctl,
18271     .d_name = "bxecnic",
18272 };
18273
18274 #define BXE_PATH(sc)    (CHIP_IS_E1x(sc) ? 0 : (sc->pcie_func & 1))
18275
18276
18277 #define DUMP_ALL_PRESETS        0x1FFF
18278 #define DUMP_MAX_PRESETS        13
18279 #define IS_E1_REG(chips)        ((chips & DUMP_CHIP_E1) == DUMP_CHIP_E1)
18280 #define IS_E1H_REG(chips)       ((chips & DUMP_CHIP_E1H) == DUMP_CHIP_E1H)
18281 #define IS_E2_REG(chips)        ((chips & DUMP_CHIP_E2) == DUMP_CHIP_E2)
18282 #define IS_E3A0_REG(chips)      ((chips & DUMP_CHIP_E3A0) == DUMP_CHIP_E3A0)
18283 #define IS_E3B0_REG(chips)      ((chips & DUMP_CHIP_E3B0) == DUMP_CHIP_E3B0)
18284
18285 #define IS_REG_IN_PRESET(presets, idx)  \
18286                 ((presets & (1 << (idx-1))) == (1 << (idx-1)))
18287
18288
18289 static int
18290 bxe_get_preset_regs_len(struct bxe_softc *sc, uint32_t preset)
18291 {
18292     if (CHIP_IS_E1(sc))
18293         return dump_num_registers[0][preset-1];
18294     else if (CHIP_IS_E1H(sc))
18295         return dump_num_registers[1][preset-1];
18296     else if (CHIP_IS_E2(sc))
18297         return dump_num_registers[2][preset-1];
18298     else if (CHIP_IS_E3A0(sc))
18299         return dump_num_registers[3][preset-1];
18300     else if (CHIP_IS_E3B0(sc))
18301         return dump_num_registers[4][preset-1];
18302     else
18303         return 0;
18304 }
18305
18306 static int
18307 bxe_get_total_regs_len32(struct bxe_softc *sc)
18308 {
18309     uint32_t preset_idx;
18310     int regdump_len32 = 0;
18311
18312
18313     /* Calculate the total preset regs length */
18314     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18315         regdump_len32 += bxe_get_preset_regs_len(sc, preset_idx);
18316     }
18317
18318     return regdump_len32;
18319 }
18320
18321 static const uint32_t *
18322 __bxe_get_page_addr_ar(struct bxe_softc *sc)
18323 {
18324     if (CHIP_IS_E2(sc))
18325         return page_vals_e2;
18326     else if (CHIP_IS_E3(sc))
18327         return page_vals_e3;
18328     else
18329         return NULL;
18330 }
18331
18332 static uint32_t
18333 __bxe_get_page_reg_num(struct bxe_softc *sc)
18334 {
18335     if (CHIP_IS_E2(sc))
18336         return PAGE_MODE_VALUES_E2;
18337     else if (CHIP_IS_E3(sc))
18338         return PAGE_MODE_VALUES_E3;
18339     else
18340         return 0;
18341 }
18342
18343 static const uint32_t *
18344 __bxe_get_page_write_ar(struct bxe_softc *sc)
18345 {
18346     if (CHIP_IS_E2(sc))
18347         return page_write_regs_e2;
18348     else if (CHIP_IS_E3(sc))
18349         return page_write_regs_e3;
18350     else
18351         return NULL;
18352 }
18353
18354 static uint32_t
18355 __bxe_get_page_write_num(struct bxe_softc *sc)
18356 {
18357     if (CHIP_IS_E2(sc))
18358         return PAGE_WRITE_REGS_E2;
18359     else if (CHIP_IS_E3(sc))
18360         return PAGE_WRITE_REGS_E3;
18361     else
18362         return 0;
18363 }
18364
18365 static const struct reg_addr *
18366 __bxe_get_page_read_ar(struct bxe_softc *sc)
18367 {
18368     if (CHIP_IS_E2(sc))
18369         return page_read_regs_e2;
18370     else if (CHIP_IS_E3(sc))
18371         return page_read_regs_e3;
18372     else
18373         return NULL;
18374 }
18375
18376 static uint32_t
18377 __bxe_get_page_read_num(struct bxe_softc *sc)
18378 {
18379     if (CHIP_IS_E2(sc))
18380         return PAGE_READ_REGS_E2;
18381     else if (CHIP_IS_E3(sc))
18382         return PAGE_READ_REGS_E3;
18383     else
18384         return 0;
18385 }
18386
18387 static bool
18388 bxe_is_reg_in_chip(struct bxe_softc *sc, const struct reg_addr *reg_info)
18389 {
18390     if (CHIP_IS_E1(sc))
18391         return IS_E1_REG(reg_info->chips);
18392     else if (CHIP_IS_E1H(sc))
18393         return IS_E1H_REG(reg_info->chips);
18394     else if (CHIP_IS_E2(sc))
18395         return IS_E2_REG(reg_info->chips);
18396     else if (CHIP_IS_E3A0(sc))
18397         return IS_E3A0_REG(reg_info->chips);
18398     else if (CHIP_IS_E3B0(sc))
18399         return IS_E3B0_REG(reg_info->chips);
18400     else
18401         return 0;
18402 }
18403
18404 static bool
18405 bxe_is_wreg_in_chip(struct bxe_softc *sc, const struct wreg_addr *wreg_info)
18406 {
18407     if (CHIP_IS_E1(sc))
18408         return IS_E1_REG(wreg_info->chips);
18409     else if (CHIP_IS_E1H(sc))
18410         return IS_E1H_REG(wreg_info->chips);
18411     else if (CHIP_IS_E2(sc))
18412         return IS_E2_REG(wreg_info->chips);
18413     else if (CHIP_IS_E3A0(sc))
18414         return IS_E3A0_REG(wreg_info->chips);
18415     else if (CHIP_IS_E3B0(sc))
18416         return IS_E3B0_REG(wreg_info->chips);
18417     else
18418         return 0;
18419 }
18420
18421 /**
18422  * bxe_read_pages_regs - read "paged" registers
18423  *
18424  * @bp          device handle
18425  * @p           output buffer
18426  *
18427  * Reads "paged" memories: memories that may only be read by first writing to a
18428  * specific address ("write address") and then reading from a specific address
18429  * ("read address"). There may be more than one write address per "page" and
18430  * more than one read address per write address.
18431  */
18432 static void
18433 bxe_read_pages_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18434 {
18435     uint32_t i, j, k, n;
18436
18437     /* addresses of the paged registers */
18438     const uint32_t *page_addr = __bxe_get_page_addr_ar(sc);
18439     /* number of paged registers */
18440     int num_pages = __bxe_get_page_reg_num(sc);
18441     /* write addresses */
18442     const uint32_t *write_addr = __bxe_get_page_write_ar(sc);
18443     /* number of write addresses */
18444     int write_num = __bxe_get_page_write_num(sc);
18445     /* read addresses info */
18446     const struct reg_addr *read_addr = __bxe_get_page_read_ar(sc);
18447     /* number of read addresses */
18448     int read_num = __bxe_get_page_read_num(sc);
18449     uint32_t addr, size;
18450
18451     for (i = 0; i < num_pages; i++) {
18452         for (j = 0; j < write_num; j++) {
18453             REG_WR(sc, write_addr[j], page_addr[i]);
18454
18455             for (k = 0; k < read_num; k++) {
18456                 if (IS_REG_IN_PRESET(read_addr[k].presets, preset)) {
18457                     size = read_addr[k].size;
18458                     for (n = 0; n < size; n++) {
18459                         addr = read_addr[k].addr + n*4;
18460                         *p++ = REG_RD(sc, addr);
18461                     }
18462                 }
18463             }
18464         }
18465     }
18466     return;
18467 }
18468
18469
18470 static int
18471 bxe_get_preset_regs(struct bxe_softc *sc, uint32_t *p, uint32_t preset)
18472 {
18473     uint32_t i, j, addr;
18474     const struct wreg_addr *wreg_addr_p = NULL;
18475
18476     if (CHIP_IS_E1(sc))
18477         wreg_addr_p = &wreg_addr_e1;
18478     else if (CHIP_IS_E1H(sc))
18479         wreg_addr_p = &wreg_addr_e1h;
18480     else if (CHIP_IS_E2(sc))
18481         wreg_addr_p = &wreg_addr_e2;
18482     else if (CHIP_IS_E3A0(sc))
18483         wreg_addr_p = &wreg_addr_e3;
18484     else if (CHIP_IS_E3B0(sc))
18485         wreg_addr_p = &wreg_addr_e3b0;
18486     else
18487         return (-1);
18488
18489     /* Read the idle_chk registers */
18490     for (i = 0; i < IDLE_REGS_COUNT; i++) {
18491         if (bxe_is_reg_in_chip(sc, &idle_reg_addrs[i]) &&
18492             IS_REG_IN_PRESET(idle_reg_addrs[i].presets, preset)) {
18493             for (j = 0; j < idle_reg_addrs[i].size; j++)
18494                 *p++ = REG_RD(sc, idle_reg_addrs[i].addr + j*4);
18495         }
18496     }
18497
18498     /* Read the regular registers */
18499     for (i = 0; i < REGS_COUNT; i++) {
18500         if (bxe_is_reg_in_chip(sc, &reg_addrs[i]) &&
18501             IS_REG_IN_PRESET(reg_addrs[i].presets, preset)) {
18502             for (j = 0; j < reg_addrs[i].size; j++)
18503                 *p++ = REG_RD(sc, reg_addrs[i].addr + j*4);
18504         }
18505     }
18506
18507     /* Read the CAM registers */
18508     if (bxe_is_wreg_in_chip(sc, wreg_addr_p) &&
18509         IS_REG_IN_PRESET(wreg_addr_p->presets, preset)) {
18510         for (i = 0; i < wreg_addr_p->size; i++) {
18511             *p++ = REG_RD(sc, wreg_addr_p->addr + i*4);
18512
18513             /* In case of wreg_addr register, read additional
18514                registers from read_regs array
18515              */
18516             for (j = 0; j < wreg_addr_p->read_regs_count; j++) {
18517                 addr = *(wreg_addr_p->read_regs);
18518                 *p++ = REG_RD(sc, addr + j*4);
18519             }
18520         }
18521     }
18522
18523     /* Paged registers are supported in E2 & E3 only */
18524     if (CHIP_IS_E2(sc) || CHIP_IS_E3(sc)) {
18525         /* Read "paged" registers */
18526         bxe_read_pages_regs(sc, p, preset);
18527     }
18528
18529     return 0;
18530 }
18531
18532 int
18533 bxe_grc_dump(struct bxe_softc *sc)
18534 {
18535     int rval = 0;
18536     uint32_t preset_idx;
18537     uint8_t *buf;
18538     uint32_t size;
18539     struct  dump_header *d_hdr;
18540     uint32_t i;
18541     uint32_t reg_val;
18542     uint32_t reg_addr;
18543     uint32_t cmd_offset;
18544     int context_size;
18545     int allocated;
18546     struct ecore_ilt *ilt = SC_ILT(sc);
18547     struct bxe_fastpath *fp;
18548     struct ilt_client_info *ilt_cli;
18549     int grc_dump_size;
18550
18551
18552     if (sc->grcdump_done || sc->grcdump_started)
18553         return (rval);
18554     
18555     sc->grcdump_started = 1;
18556     BLOGI(sc, "Started collecting grcdump\n");
18557
18558     grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18559                 sizeof(struct  dump_header);
18560
18561     sc->grc_dump = malloc(grc_dump_size, M_DEVBUF, M_NOWAIT);
18562
18563     if (sc->grc_dump == NULL) {
18564         BLOGW(sc, "Unable to allocate memory for grcdump collection\n");
18565         return(ENOMEM);
18566     }
18567
18568
18569
18570     /* Disable parity attentions as long as following dump may
18571      * cause false alarms by reading never written registers. We
18572      * will re-enable parity attentions right after the dump.
18573      */
18574
18575     /* Disable parity on path 0 */
18576     bxe_pretend_func(sc, 0);
18577
18578     ecore_disable_blocks_parity(sc);
18579
18580     /* Disable parity on path 1 */
18581     bxe_pretend_func(sc, 1);
18582     ecore_disable_blocks_parity(sc);
18583
18584     /* Return to current function */
18585     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18586
18587     buf = sc->grc_dump;
18588     d_hdr = sc->grc_dump;
18589
18590     d_hdr->header_size = (sizeof(struct  dump_header) >> 2) - 1;
18591     d_hdr->version = BNX2X_DUMP_VERSION;
18592     d_hdr->preset = DUMP_ALL_PRESETS;
18593
18594     if (CHIP_IS_E1(sc)) {
18595         d_hdr->dump_meta_data = DUMP_CHIP_E1;
18596     } else if (CHIP_IS_E1H(sc)) {
18597         d_hdr->dump_meta_data = DUMP_CHIP_E1H;
18598     } else if (CHIP_IS_E2(sc)) {
18599         d_hdr->dump_meta_data = DUMP_CHIP_E2 |
18600                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18601     } else if (CHIP_IS_E3A0(sc)) {
18602         d_hdr->dump_meta_data = DUMP_CHIP_E3A0 |
18603                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18604     } else if (CHIP_IS_E3B0(sc)) {
18605         d_hdr->dump_meta_data = DUMP_CHIP_E3B0 |
18606                 (BXE_PATH(sc) ? DUMP_PATH_1 : DUMP_PATH_0);
18607     }
18608
18609     buf += sizeof(struct  dump_header);
18610
18611     for (preset_idx = 1; preset_idx <= DUMP_MAX_PRESETS; preset_idx++) {
18612
18613         /* Skip presets with IOR */
18614         if ((preset_idx == 2) || (preset_idx == 5) || (preset_idx == 8) ||
18615             (preset_idx == 11))
18616             continue;
18617
18618         rval = bxe_get_preset_regs(sc, (uint32_t *)buf, preset_idx);
18619
18620         if (rval)
18621             break;
18622
18623         size = bxe_get_preset_regs_len(sc, preset_idx) * (sizeof (uint32_t));
18624
18625         buf += size;
18626     }
18627
18628     bxe_pretend_func(sc, 0);
18629     ecore_clear_blocks_parity(sc);
18630     ecore_enable_blocks_parity(sc);
18631
18632     bxe_pretend_func(sc, 1);
18633     ecore_clear_blocks_parity(sc);
18634     ecore_enable_blocks_parity(sc);
18635
18636     /* Return to current function */
18637     bxe_pretend_func(sc, SC_ABS_FUNC(sc));
18638
18639
18640     context_size = (sizeof(union cdu_context) * BXE_L2_CID_COUNT(sc));
18641     for (i = 0, allocated = 0; allocated < context_size; i++) {
18642
18643         BLOGI(sc, "cdu_context i %d paddr %#jx vaddr %p size 0x%zx\n", i,
18644             (uintmax_t)sc->context[i].vcxt_dma.paddr,
18645             sc->context[i].vcxt_dma.vaddr,
18646             sc->context[i].size);
18647         allocated += sc->context[i].size;
18648     }
18649     BLOGI(sc, "fw stats start_paddr %#jx end_paddr %#jx vaddr %p size 0x%x\n",
18650         (uintmax_t)sc->fw_stats_req_mapping,
18651         (uintmax_t)sc->fw_stats_data_mapping,
18652         sc->fw_stats_req, (sc->fw_stats_req_size + sc->fw_stats_data_size));
18653     BLOGI(sc, "def_status_block paddr %p vaddr %p size 0x%zx\n",
18654         (void *)sc->def_sb_dma.paddr, sc->def_sb,
18655         sizeof(struct host_sp_status_block));
18656     BLOGI(sc, "event_queue paddr %#jx vaddr %p size 0x%x\n",
18657         (uintmax_t)sc->eq_dma.paddr, sc->eq_dma.vaddr, BCM_PAGE_SIZE);
18658     BLOGI(sc, "slow path paddr %#jx vaddr %p size 0x%zx\n",
18659         (uintmax_t)sc->sp_dma.paddr, sc->sp_dma.vaddr,
18660         sizeof(struct bxe_slowpath));
18661     BLOGI(sc, "slow path queue paddr %#jx vaddr %p size 0x%x\n",
18662         (uintmax_t)sc->spq_dma.paddr, sc->spq_dma.vaddr, BCM_PAGE_SIZE);
18663     BLOGI(sc, "fw_buf paddr %#jx vaddr %p size 0x%x\n",
18664         (uintmax_t)sc->gz_buf_dma.paddr, sc->gz_buf_dma.vaddr,
18665         FW_BUF_SIZE);
18666     for (i = 0; i < sc->num_queues; i++) {
18667         fp = &sc->fp[i];
18668         BLOGI(sc, "FP status block fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18669             (uintmax_t)fp->sb_dma.paddr, fp->sb_dma.vaddr,
18670             sizeof(union bxe_host_hc_status_block));
18671         BLOGI(sc, "TX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18672             (uintmax_t)fp->tx_dma.paddr, fp->tx_dma.vaddr,
18673             (BCM_PAGE_SIZE * TX_BD_NUM_PAGES));
18674         BLOGI(sc, "RX BD CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18675             (uintmax_t)fp->rx_dma.paddr, fp->rx_dma.vaddr,
18676             (BCM_PAGE_SIZE * RX_BD_NUM_PAGES));
18677         BLOGI(sc, "RX RCQ CHAIN fp %d paddr %#jx vaddr %p size 0x%zx\n", i,
18678             (uintmax_t)fp->rcq_dma.paddr, fp->rcq_dma.vaddr,
18679             (BCM_PAGE_SIZE * RCQ_NUM_PAGES));
18680         BLOGI(sc, "RX SGE CHAIN fp %d paddr %#jx vaddr %p size 0x%x\n", i,
18681             (uintmax_t)fp->rx_sge_dma.paddr, fp->rx_sge_dma.vaddr,
18682             (BCM_PAGE_SIZE * RX_SGE_NUM_PAGES));
18683     }
18684
18685     ilt_cli = &ilt->clients[1];
18686     for (i = ilt_cli->start; i <= ilt_cli->end; i++) {
18687         BLOGI(sc, "ECORE_ILT paddr %#jx vaddr %p size 0x%x\n",
18688             (uintmax_t)(((struct bxe_dma *)((&ilt->lines[i])->page))->paddr),
18689             ((struct bxe_dma *)((&ilt->lines[i])->page))->vaddr, BCM_PAGE_SIZE);
18690     }
18691
18692
18693     cmd_offset = DMAE_REG_CMD_MEM;
18694     for (i = 0; i < 224; i++) {
18695         reg_addr = (cmd_offset +(i * 4));
18696         reg_val = REG_RD(sc, reg_addr);
18697         BLOGI(sc, "DMAE_REG_CMD_MEM i=%d reg_addr 0x%x reg_val 0x%08x\n",i,
18698             reg_addr, reg_val);
18699     }
18700
18701
18702     BLOGI(sc, "Collection of grcdump done\n");
18703     sc->grcdump_done = 1;
18704     return(rval);
18705 }
18706
18707 static int
18708 bxe_add_cdev(struct bxe_softc *sc)
18709 {
18710     sc->eeprom = malloc(BXE_EEPROM_MAX_DATA_LEN, M_DEVBUF, M_NOWAIT);
18711
18712     if (sc->eeprom == NULL) {
18713         BLOGW(sc, "Unable to alloc for eeprom size buffer\n");
18714         return (-1);
18715     }
18716
18717     sc->ioctl_dev = make_dev(&bxe_cdevsw,
18718                             sc->ifnet->if_dunit,
18719                             UID_ROOT,
18720                             GID_WHEEL,
18721                             0600,
18722                             "%s",
18723                             if_name(sc->ifnet));
18724
18725     if (sc->ioctl_dev == NULL) {
18726         free(sc->eeprom, M_DEVBUF);
18727         sc->eeprom = NULL;
18728         return (-1);
18729     }
18730
18731     sc->ioctl_dev->si_drv1 = sc;
18732
18733     return (0);
18734 }
18735
18736 static void
18737 bxe_del_cdev(struct bxe_softc *sc)
18738 {
18739     if (sc->ioctl_dev != NULL)
18740         destroy_dev(sc->ioctl_dev);
18741
18742     if (sc->eeprom != NULL) {
18743         free(sc->eeprom, M_DEVBUF);
18744         sc->eeprom = NULL;
18745     }
18746     sc->ioctl_dev = NULL;
18747
18748     return;
18749 }
18750
18751 static bool bxe_is_nvram_accessible(struct bxe_softc *sc)
18752 {
18753
18754     if ((sc->ifnet->if_drv_flags & IFF_DRV_RUNNING) == 0)
18755         return FALSE;
18756
18757     return TRUE;
18758 }
18759
18760
18761 static int
18762 bxe_wr_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18763 {
18764     int rval = 0;
18765
18766     if(!bxe_is_nvram_accessible(sc)) {
18767         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18768         return (-EAGAIN);
18769     }
18770     rval = bxe_nvram_write(sc, offset, (uint8_t *)data, len);
18771
18772
18773    return (rval);
18774 }
18775
18776 static int
18777 bxe_rd_eeprom(struct bxe_softc *sc, void *data, uint32_t offset, uint32_t len)
18778 {
18779     int rval = 0;
18780
18781     if(!bxe_is_nvram_accessible(sc)) {
18782         BLOGW(sc, "Cannot access eeprom when interface is down\n");
18783         return (-EAGAIN);
18784     }
18785     rval = bxe_nvram_read(sc, offset, (uint8_t *)data, len);
18786
18787    return (rval);
18788 }
18789
18790 static int
18791 bxe_eeprom_rd_wr(struct bxe_softc *sc, bxe_eeprom_t *eeprom)
18792 {
18793     int rval = 0;
18794
18795     switch (eeprom->eeprom_cmd) {
18796
18797     case BXE_EEPROM_CMD_SET_EEPROM:
18798
18799         rval = copyin(eeprom->eeprom_data, sc->eeprom,
18800                        eeprom->eeprom_data_len);
18801
18802         if (rval)
18803             break;
18804
18805         rval = bxe_wr_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18806                        eeprom->eeprom_data_len);
18807         break;
18808
18809     case BXE_EEPROM_CMD_GET_EEPROM:
18810
18811         rval = bxe_rd_eeprom(sc, sc->eeprom, eeprom->eeprom_offset,
18812                        eeprom->eeprom_data_len);
18813
18814         if (rval) {
18815             break;
18816         }
18817
18818         rval = copyout(sc->eeprom, eeprom->eeprom_data,
18819                        eeprom->eeprom_data_len);
18820         break;
18821
18822     default:
18823             rval = EINVAL;
18824             break;
18825     }
18826
18827     if (rval) {
18828         BLOGW(sc, "ioctl cmd %d  failed rval %d\n", eeprom->eeprom_cmd, rval);
18829     }
18830
18831     return (rval);
18832 }
18833
18834 static int
18835 bxe_get_settings(struct bxe_softc *sc, bxe_dev_setting_t *dev_p)
18836 {
18837     uint32_t ext_phy_config;
18838     int port = SC_PORT(sc);
18839     int cfg_idx = bxe_get_link_cfg_idx(sc);
18840
18841     dev_p->supported = sc->port.supported[cfg_idx] |
18842             (sc->port.supported[cfg_idx ^ 1] &
18843             (ELINK_SUPPORTED_TP | ELINK_SUPPORTED_FIBRE));
18844     dev_p->advertising = sc->port.advertising[cfg_idx];
18845     if(sc->link_params.phy[bxe_get_cur_phy_idx(sc)].media_type ==
18846         ELINK_ETH_PHY_SFP_1G_FIBER) {
18847         dev_p->supported = ~(ELINK_SUPPORTED_10000baseT_Full);
18848         dev_p->advertising &= ~(ADVERTISED_10000baseT_Full);
18849     }
18850     if ((sc->state == BXE_STATE_OPEN) && sc->link_vars.link_up &&
18851         !(sc->flags & BXE_MF_FUNC_DIS)) {
18852         dev_p->duplex = sc->link_vars.duplex;
18853         if (IS_MF(sc) && !BXE_NOMCP(sc))
18854             dev_p->speed = bxe_get_mf_speed(sc);
18855         else
18856             dev_p->speed = sc->link_vars.line_speed;
18857     } else {
18858         dev_p->duplex = DUPLEX_UNKNOWN;
18859         dev_p->speed = SPEED_UNKNOWN;
18860     }
18861
18862     dev_p->port = bxe_media_detect(sc);
18863
18864     ext_phy_config = SHMEM_RD(sc,
18865                          dev_info.port_hw_config[port].external_phy_config);
18866     if((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) ==
18867         PORT_HW_CFG_XGXS_EXT_PHY_TYPE_DIRECT)
18868         dev_p->phy_address =  sc->port.phy_addr;
18869     else if(((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18870             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_FAILURE) &&
18871         ((ext_phy_config & PORT_HW_CFG_XGXS_EXT_PHY_TYPE_MASK) !=
18872             PORT_HW_CFG_XGXS_EXT_PHY_TYPE_NOT_CONN))
18873         dev_p->phy_address = ELINK_XGXS_EXT_PHY_ADDR(ext_phy_config);
18874     else
18875         dev_p->phy_address = 0;
18876
18877     if(sc->link_params.req_line_speed[cfg_idx] == ELINK_SPEED_AUTO_NEG)
18878         dev_p->autoneg = AUTONEG_ENABLE;
18879     else
18880        dev_p->autoneg = AUTONEG_DISABLE;
18881
18882
18883     return 0;
18884 }
18885
18886 static int
18887 bxe_eioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
18888         struct thread *td)
18889 {
18890     struct bxe_softc    *sc;
18891     int                 rval = 0;
18892     device_t            pci_dev;
18893     bxe_grcdump_t       *dump = NULL;
18894     int grc_dump_size;
18895     bxe_drvinfo_t   *drv_infop = NULL;
18896     bxe_dev_setting_t  *dev_p;
18897     bxe_dev_setting_t  dev_set;
18898     bxe_get_regs_t  *reg_p;
18899     bxe_reg_rdw_t *reg_rdw_p;
18900     bxe_pcicfg_rdw_t *cfg_rdw_p;
18901     bxe_perm_mac_addr_t *mac_addr_p;
18902
18903
18904     if ((sc = (struct bxe_softc *)dev->si_drv1) == NULL)
18905         return ENXIO;
18906
18907     pci_dev= sc->dev;
18908
18909     dump = (bxe_grcdump_t *)data;
18910
18911     switch(cmd) {
18912
18913         case BXE_GRC_DUMP_SIZE:
18914             dump->pci_func = sc->pcie_func;
18915             dump->grcdump_size =
18916                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18917                      sizeof(struct  dump_header);
18918             break;
18919
18920         case BXE_GRC_DUMP:
18921             
18922             grc_dump_size = (bxe_get_total_regs_len32(sc) * sizeof(uint32_t)) +
18923                                 sizeof(struct  dump_header);
18924             if ((!sc->trigger_grcdump) || (dump->grcdump == NULL) ||
18925                 (dump->grcdump_size < grc_dump_size)) {
18926                 rval = EINVAL;
18927                 break;
18928             }
18929
18930             if((sc->trigger_grcdump) && (!sc->grcdump_done) &&
18931                 (!sc->grcdump_started)) {
18932                 rval =  bxe_grc_dump(sc);
18933             }
18934
18935             if((!rval) && (sc->grcdump_done) && (sc->grcdump_started) &&
18936                 (sc->grc_dump != NULL))  {
18937                 dump->grcdump_dwords = grc_dump_size >> 2;
18938                 rval = copyout(sc->grc_dump, dump->grcdump, grc_dump_size);
18939                 free(sc->grc_dump, M_DEVBUF);
18940                 sc->grc_dump = NULL;
18941                 sc->grcdump_started = 0;
18942                 sc->grcdump_done = 0;
18943             }
18944
18945             break;
18946
18947         case BXE_DRV_INFO:
18948             drv_infop = (bxe_drvinfo_t *)data;
18949             snprintf(drv_infop->drv_name, BXE_DRV_NAME_LENGTH, "%s", "bxe");
18950             snprintf(drv_infop->drv_version, BXE_DRV_VERSION_LENGTH, "v:%s",
18951                 BXE_DRIVER_VERSION);
18952             snprintf(drv_infop->mfw_version, BXE_MFW_VERSION_LENGTH, "%s",
18953                 sc->devinfo.bc_ver_str);
18954             snprintf(drv_infop->stormfw_version, BXE_STORMFW_VERSION_LENGTH,
18955                 "%s", sc->fw_ver_str);
18956             drv_infop->eeprom_dump_len = sc->devinfo.flash_size;
18957             drv_infop->reg_dump_len =
18958                 (bxe_get_total_regs_len32(sc) * sizeof(uint32_t))
18959                     + sizeof(struct  dump_header);
18960             snprintf(drv_infop->bus_info, BXE_BUS_INFO_LENGTH, "%d:%d:%d",
18961                 sc->pcie_bus, sc->pcie_device, sc->pcie_func);
18962             break;
18963
18964         case BXE_DEV_SETTING:
18965             dev_p = (bxe_dev_setting_t *)data;
18966             bxe_get_settings(sc, &dev_set);
18967             dev_p->supported = dev_set.supported;
18968             dev_p->advertising = dev_set.advertising;
18969             dev_p->speed = dev_set.speed;
18970             dev_p->duplex = dev_set.duplex;
18971             dev_p->port = dev_set.port;
18972             dev_p->phy_address = dev_set.phy_address;
18973             dev_p->autoneg = dev_set.autoneg;
18974
18975             break;
18976
18977         case BXE_GET_REGS:
18978
18979             reg_p = (bxe_get_regs_t *)data;
18980             grc_dump_size = reg_p->reg_buf_len;
18981
18982             if((!sc->grcdump_done) && (!sc->grcdump_started)) {
18983                 bxe_grc_dump(sc);
18984             }
18985             if((sc->grcdump_done) && (sc->grcdump_started) &&
18986                 (sc->grc_dump != NULL))  {
18987                 rval = copyout(sc->grc_dump, reg_p->reg_buf, grc_dump_size);
18988                 free(sc->grc_dump, M_DEVBUF);
18989                 sc->grc_dump = NULL;
18990                 sc->grcdump_started = 0;
18991                 sc->grcdump_done = 0;
18992             }
18993
18994             break;
18995
18996         case BXE_RDW_REG:
18997             reg_rdw_p = (bxe_reg_rdw_t *)data;
18998             if((reg_rdw_p->reg_cmd == BXE_READ_REG_CMD) &&
18999                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19000                 reg_rdw_p->reg_val = REG_RD(sc, reg_rdw_p->reg_id);
19001
19002             if((reg_rdw_p->reg_cmd == BXE_WRITE_REG_CMD) &&
19003                 (reg_rdw_p->reg_access_type == BXE_REG_ACCESS_DIRECT))
19004                 REG_WR(sc, reg_rdw_p->reg_id, reg_rdw_p->reg_val);
19005
19006             break;
19007
19008         case BXE_RDW_PCICFG:
19009             cfg_rdw_p = (bxe_pcicfg_rdw_t *)data;
19010             if(cfg_rdw_p->cfg_cmd == BXE_READ_PCICFG) {
19011
19012                 cfg_rdw_p->cfg_val = pci_read_config(sc->dev, cfg_rdw_p->cfg_id,
19013                                          cfg_rdw_p->cfg_width);
19014
19015             } else if(cfg_rdw_p->cfg_cmd == BXE_WRITE_PCICFG) {
19016                 pci_write_config(sc->dev, cfg_rdw_p->cfg_id, cfg_rdw_p->cfg_val,
19017                             cfg_rdw_p->cfg_width);
19018             } else {
19019                 BLOGW(sc, "BXE_RDW_PCICFG ioctl wrong cmd passed\n");
19020             }
19021             break;
19022
19023         case BXE_MAC_ADDR:
19024             mac_addr_p = (bxe_perm_mac_addr_t *)data;
19025             snprintf(mac_addr_p->mac_addr_str, sizeof(sc->mac_addr_str), "%s",
19026                 sc->mac_addr_str);
19027             break;
19028
19029         case BXE_EEPROM:
19030             rval = bxe_eeprom_rd_wr(sc, (bxe_eeprom_t *)data);
19031             break;
19032
19033
19034         default:
19035             break;
19036     }
19037
19038     return (rval);
19039 }